Skip to main content

wellfare_core/anatomy/
model.rs

1//! Which anatomical **reference model** the 3D body uses, and how each organ maps to a body system.
2//!
3//! The model is selected from the user's declared **chromosomal basis** — their "DNA selection",
4//! `XY` or `XX`. This is a *biological-substrate attribute the user declares*, **not** a gender or an
5//! identity claim: it is one attribute among many, never collapsed into identity (see the
6//! DID-is-identifier-not-identity stance). It selects which Visible Human reference mesh set applies
7//! (the CCF / HRA `ccf-3d-reference-object-library`, CC-BY-4.0: `VH_Male` / `VH_Female`), so a person's
8//! records are mapped onto anatomy that matches their body.
9//!
10//! `XY`/`XX` are the two Timothy named and the two the CCF library ships. The type is deliberately a
11//! small closed enum rather than a free string so a caller cannot smuggle an unvalidated value in; if
12//! additional karyotypes are ever curated they are an explicit, reviewed extension, not silent drift.
13
14use serde::{Deserialize, Serialize};
15
16/// The declared chromosomal basis — the user's "DNA selection". A biological-substrate attribute, not
17/// an identity or gender claim.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19pub enum Karyotype {
20    /// XY → the male reference model.
21    Xy,
22    /// XX → the female reference model.
23    Xx,
24}
25
26/// Which Visible Human reference model the 3D body renders.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28pub enum AnatomyModel {
29    Male,
30    Female,
31}
32
33impl Karyotype {
34    /// The reference model this chromosomal basis selects: `XY → Male`, `XX → Female`.
35    pub fn anatomy_model(self) -> AnatomyModel {
36        match self {
37            Karyotype::Xy => AnatomyModel::Male,
38            Karyotype::Xx => AnatomyModel::Female,
39        }
40    }
41
42    /// The canonical two-letter token (`"XY"` / `"XX"`).
43    pub fn as_str(self) -> &'static str {
44        match self {
45            Karyotype::Xy => "XY",
46            Karyotype::Xx => "XX",
47        }
48    }
49
50    /// Parse a declared selection (case-insensitive, trimmed). `None` for anything but the two
51    /// curated values — the caller decides how to handle an unrecognised declaration (fail-closed,
52    /// prompt, etc.) rather than us guessing a body for someone.
53    pub fn parse(s: &str) -> Option<Self> {
54        match s.trim().to_ascii_uppercase().as_str() {
55            "XY" => Some(Karyotype::Xy),
56            "XX" => Some(Karyotype::Xx),
57            _ => None,
58        }
59    }
60}
61
62impl AnatomyModel {
63    /// The CCF / HRA asset-set directory prefix (`"VH_Male"` / `"VH_Female"`).
64    pub fn asset_set(self) -> &'static str {
65        match self {
66            AnatomyModel::Male => "VH_Male",
67            AnatomyModel::Female => "VH_Female",
68        }
69    }
70
71    /// The organ-filename infix the CCF assets use (`3d-vh-`**`m`**`-lung.glb` /
72    /// `3d-vh-`**`f`**`-lung.glb`).
73    pub fn file_infix(self) -> &'static str {
74        match self {
75            AnatomyModel::Male => "m",
76            AnatomyModel::Female => "f",
77        }
78    }
79
80    /// Lowercase model token for manifest facts / DTOs (`"male"` / `"female"`).
81    pub fn as_str(self) -> &'static str {
82        match self {
83            AnatomyModel::Male => "male",
84            AnatomyModel::Female => "female",
85        }
86    }
87
88    /// Parse a model token (case-insensitive).
89    pub fn parse(s: &str) -> Option<Self> {
90        match s.trim().to_ascii_lowercase().as_str() {
91            "male" => Some(AnatomyModel::Male),
92            "female" => Some(AnatomyModel::Female),
93            _ => None,
94        }
95    }
96}
97
98/// Normalize a CCF/HRA organ key to a model-agnostic base token: strip the `3d-vh-m-` / `3d-vh-f-`
99/// asset prefix, the `.glb` suffix, and a trailing laterality (`-l`/`-r`/`-left`/`-right`), leaving the
100/// bare organ (`"3d-vh-m-eye-l.glb"` → `"eye"`, `"blood-vasculature"` → `"blood-vasculature"`).
101pub fn normalize_organ_key(raw: &str) -> String {
102    let mut s = raw.trim().to_ascii_lowercase();
103    for ext in [".glb", ".gltf", ".obj", ".stl"] {
104        if let Some(rest) = s.strip_suffix(ext) {
105            s = rest.to_string();
106            break;
107        }
108    }
109    // Strip the CCF asset prefix up to and including the sex marker `-m-`/`-f-`. The provider varies
110    // (`vh`, `allen`, `sbu`, `nih`, …), so match the marker rather than a fixed prefix; organ tokens
111    // never contain a dash-bounded single `m`/`f`, so the first occurrence is always the sex marker.
112    let has_3d = s.starts_with("3d-");
113    if let Some(pos) = s.find("-m-").or_else(|| s.find("-f-")) {
114        if has_3d || pos <= 8 {
115            s = s[pos + 3..].to_string();
116        }
117    }
118    for lat in ["-left", "-right", "-l", "-r"] {
119        if let Some(rest) = s.strip_suffix(lat) {
120            s = rest.to_string();
121            break;
122        }
123    }
124    s
125}
126
127/// Model-agnostic organ → body-system map for the common HRA/CCF organs. The `AnatomyModel` decides
128/// which organs are *present* in a body (a `VH_Male` set has `prostate`, a `VH_Female` set has
129/// `uterus`); this table only says which of the 17 systems an organ belongs to, so a loaded organ mesh
130/// can be coloured by that system's burden. Curated, not guessed — an unknown organ returns `None` and
131/// is reported by the caller, never silently coloured.
132static ORGAN_SYSTEMS: &[(&str, &str)] = &[
133    // Circulatory
134    ("blood-vasculature", "circulatory"),
135    ("heart", "circulatory"),
136    ("vasculature", "circulatory"),
137    // Respiratory
138    ("lung", "respiratory"),
139    ("larynx", "respiratory"),
140    ("trachea", "respiratory"),
141    ("bronchus", "respiratory"),
142    ("main-bronchus", "respiratory"),
143    ("respiratory-system", "respiratory"),
144    // Digestive
145    ("liver", "digestive"),
146    ("stomach", "digestive"),
147    ("mouth", "digestive"),
148    ("small-intestine", "digestive"),
149    ("large-intestine", "digestive"),
150    ("colon", "digestive"),
151    ("pancreas", "digestive"),
152    ("gallbladder", "digestive"),
153    ("esophagus", "digestive"),
154    // Nervous
155    ("brain", "nervous"),
156    ("spinal-cord", "nervous"),
157    ("nerve", "nervous"),
158    // Sensory
159    ("eye", "sensory"),
160    ("ear", "sensory"),
161    ("cochlea", "sensory"),
162    // Vestibular (balance — the inner-ear apparatus; distinct from hearing)
163    ("inner-ear", "vestibular"),
164    ("semicircular-canal", "vestibular"),
165    ("vestibule", "vestibular"),
166    // Urinary
167    ("kidney", "urinary"),
168    ("bladder", "urinary"),
169    ("urinary-bladder", "urinary"),
170    ("ureter", "urinary"),
171    ("urethra", "urinary"),
172    ("renal-pyramid", "urinary"),
173    // Immune / lymphatic
174    ("spleen", "immune_lymphatic"),
175    ("thymus", "immune_lymphatic"),
176    ("lymph-node", "immune_lymphatic"),
177    ("tonsil", "immune_lymphatic"),
178    ("lymphatic-system", "immune_lymphatic"),
179    // Integumentary
180    ("skin", "integumentary"),
181    ("mammary-gland", "integumentary"),
182    // Skeletal
183    ("bone", "skeletal"),
184    ("skeleton", "skeletal"),
185    ("rib", "skeletal"),
186    ("pelvis", "skeletal"),
187    // Muscular
188    ("muscle", "muscular"),
189    ("diaphragm", "muscular"), // a muscle (primary) that is also the engine of respiration (secondary)
190    // Endocrine
191    ("thyroid-gland", "endocrine"),
192    ("thyroid", "endocrine"),
193    ("adrenal-gland", "endocrine"),
194    ("pituitary-gland", "endocrine"),
195    // Exocrine (duct glands; several are functionally shared with digestive/integumentary — the
196    // liver and pancreas are dual-role and mapped to digestive as their primary macroscopic organ).
197    ("salivary-gland", "exocrine"),
198    ("parotid-gland", "exocrine"),
199    ("submandibular-gland", "exocrine"),
200    ("sublingual-gland", "exocrine"),
201    ("lacrimal-gland", "exocrine"),
202    ("sweat-gland", "exocrine"),
203    ("sebaceous-gland", "exocrine"),
204    // Reproductive (model-specific organs — present per the loaded model's asset set)
205    ("prostate", "reproductive"),
206    ("testis", "reproductive"),
207    ("uterus", "reproductive"),
208    ("ovary", "reproductive"),
209    ("fallopian-tube", "reproductive"),
210    ("vagina", "reproductive"),
211    ("placenta", "reproductive"),
212    ("placenta-full-term", "reproductive"),
213];
214
215/// The **primary** body-system id for an HRA/CCF organ (after [`normalize_organ_key`]), or `None` if the
216/// organ is not in the curated map. An organ is a *building block that participates in several systems*
217/// (the pancreas is digestive **and** endocrine); this returns its primary macroscopic home — the one
218/// used for default colour/placement. Use [`system_memberships_for_organ`] for the full set.
219pub fn body_system_for_organ(organ: &str) -> Option<&'static str> {
220    let key = normalize_organ_key(organ);
221    ORGAN_SYSTEMS
222        .iter()
223        .find(|(o, _)| *o == key)
224        .map(|(_, sys)| *sys)
225}
226
227/// An organ's **additional** system memberships beyond its primary — the dual/multi-role structures. An
228/// organ is a building block shared across systems: the pancreas secretes digestive enzymes *and* insulin
229/// (endocrine); the kidney filters blood *and* makes hormones (renin/EPO/vit-D); skin is a barrier that
230/// also senses and secretes. Curation-grade (well-established textbook roles), extensible. Every id here
231/// is a real body system (a test asserts it). This is the data behind organ→**many** systems.
232static ORGAN_SECONDARY_SYSTEMS: &[(&str, &str)] = &[
233    ("pancreas", "endocrine"),     // islets of Langerhans → insulin/glucagon
234    ("pancreas", "exocrine"),      // acinar cells → digestive enzymes via ducts
235    ("liver", "endocrine"),        // IGF-1, angiotensinogen, thrombopoietin, hormone metabolism
236    ("liver", "exocrine"),         // bile secreted via the biliary ducts
237    ("kidney", "endocrine"),       // renin, erythropoietin, calcitriol activation
238    ("ovary", "endocrine"),        // oestrogen / progesterone
239    ("testis", "endocrine"),       // testosterone
240    ("bone", "immune_lymphatic"),  // red marrow → haematopoiesis of immune cells
241    ("skin", "sensory"),           // cutaneous mechano/thermo/nociceptors
242    ("skin", "exocrine"),          // sweat + sebaceous glands
243    ("mammary-gland", "exocrine"), // milk secreted via ducts
244    ("diaphragm", "respiratory"),  // the principal muscle of ventilation
245];
246
247/// All body systems an organ participates in, as `(system_id, is_primary)` — the primary first, then any
248/// additional memberships. Empty if the organ is unmapped. This is what makes an organ a shared building
249/// block rather than a leaf of one system: a caller can colour by the primary (default) **or** blend across
250/// all memberships, and a person's condition on any member system lights the organ.
251/// Seeded primary organ → system pairs (cold authoring / coverage). Overlay systems
252/// do not appear as primaries.
253pub fn primary_organ_system_pairs() -> &'static [(&'static str, &'static str)] {
254    ORGAN_SYSTEMS
255}
256
257/// Seeded extra memberships (an organ participates in more than its primary system).
258pub fn secondary_organ_system_pairs() -> &'static [(&'static str, &'static str)] {
259    ORGAN_SECONDARY_SYSTEMS
260}
261
262/// System memberships for an organ.
263pub fn system_memberships_for_organ(organ: &str) -> Vec<(&'static str, bool)> {
264    let key = normalize_organ_key(organ);
265    let mut out: Vec<(&'static str, bool)> = Vec::new();
266    if let Some((_, sys)) = ORGAN_SYSTEMS.iter().find(|(o, _)| *o == key) {
267        out.push((*sys, true));
268    }
269    for (o, sys) in ORGAN_SECONDARY_SYSTEMS {
270        if *o == key && !out.iter().any(|(s, _)| s == sys) {
271            out.push((*sys, false));
272        }
273    }
274    out
275}
276
277/// How a body system is rendered on the 3D body.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
279pub enum SystemRepresentation {
280    /// Has one or more characteristic organ meshes — colour them directly (the σ percept paints the mesh).
281    DiscreteOrgans,
282    /// No standalone organ mesh — a signalling / neural / clearance network that lives *across* other
283    /// organs, rendered as a highlight/overlay on its host structures (or a whole-body cue).
284    DistributedOverlay,
285}
286
287/// Classify one of the 17 systems by how it is rendered. This is an anatomical fact, not a coverage
288/// gap: the **endocannabinoid** system (CB1/CB2 receptors throughout the CNS + periphery), the
289/// **enteric-nervous** system (the ~500-million-neuron web lining the gut), and the **glymphatic**
290/// system (astrocyte + cerebrospinal-fluid clearance in the brain) are real and first-class in the
291/// taxonomy — they accumulate burden and get a σ percept — but they have no single organ to paint, so
292/// they are surfaced as an overlay on their host structures. Every other system has discrete organs.
293pub fn system_representation(system_id: &str) -> SystemRepresentation {
294    match system_id {
295        "ecs" | "ens" | "glymphatic" => SystemRepresentation::DistributedOverlay,
296        _ => SystemRepresentation::DiscreteOrgans,
297    }
298}
299
300/// For a [`SystemRepresentation::DistributedOverlay`] system, the discrete systems whose organ meshes
301/// it should be highlighted **over** — anatomical placement hints for the overlay render. The enteric
302/// nervous system lines the gut → overlay the digestive organs; the glymphatic system clears the brain
303/// → overlay the nervous system; the endocannabinoid system's receptors are body-wide → an empty slice
304/// meaning a **whole-body** cue rather than a localised highlight. Returns `&[]` for discrete-organ
305/// systems (they paint their own mesh and have no overlay host); call it only for distributed systems.
306pub fn overlay_host_systems(system_id: &str) -> &'static [&'static str] {
307    match system_id {
308        "ens" => &["digestive"],
309        "glymphatic" => &["nervous"],
310        "ecs" => &[], // receptors are everywhere → whole-body cue
311        _ => &[],
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    // `body_system` (the systems registry validity lookup) is used only by
319    // `every_mapped_system_id_is_a_real_body_system`, so it is scoped to the tests.
320    use crate::anatomy::systems::body_system;
321
322    #[test]
323    fn karyotype_selects_reference_model() {
324        assert_eq!(Karyotype::Xy.anatomy_model(), AnatomyModel::Male);
325        assert_eq!(Karyotype::Xx.anatomy_model(), AnatomyModel::Female);
326        assert_eq!(Karyotype::Xy.anatomy_model().asset_set(), "VH_Male");
327        assert_eq!(Karyotype::Xx.anatomy_model().asset_set(), "VH_Female");
328        assert_eq!(AnatomyModel::Male.file_infix(), "m");
329        assert_eq!(AnatomyModel::Female.file_infix(), "f");
330    }
331
332    #[test]
333    fn karyotype_parse_is_closed_and_case_insensitive() {
334        assert_eq!(Karyotype::parse("xy"), Some(Karyotype::Xy));
335        assert_eq!(Karyotype::parse("  XX "), Some(Karyotype::Xx));
336        // Not a curated value → None (caller fails closed rather than guessing a body).
337        assert_eq!(Karyotype::parse("XXY"), None);
338        assert_eq!(Karyotype::parse(""), None);
339        // Round-trip.
340        assert_eq!(
341            Karyotype::parse(Karyotype::Xy.as_str()),
342            Some(Karyotype::Xy)
343        );
344    }
345
346    #[test]
347    fn organ_keys_normalize_across_asset_and_lateral_forms() {
348        assert_eq!(normalize_organ_key("3d-vh-m-eye-l.glb"), "eye");
349        assert_eq!(normalize_organ_key("3d-vh-f-eye-r.glb"), "eye");
350        assert_eq!(normalize_organ_key("eye-left"), "eye");
351        assert_eq!(
352            normalize_organ_key("blood-vasculature"),
353            "blood-vasculature"
354        );
355        assert_eq!(normalize_organ_key("  VH-M-Lung  "), "lung");
356        // The provider varies across the real CCF set — strip on the sex marker, not a fixed prefix.
357        assert_eq!(normalize_organ_key("3d-allen-m-brain.glb"), "brain");
358        assert_eq!(
359            normalize_organ_key("3d-sbu-m-large-intestine.glb"),
360            "large-intestine"
361        );
362        assert_eq!(normalize_organ_key("3d-nih-f-lymph-node.glb"), "lymph-node");
363        assert_eq!(
364            normalize_organ_key("3d-vh-m-main-bronchus.glb"),
365            "main-bronchus"
366        );
367    }
368
369    #[test]
370    fn organs_map_to_systems_and_unknowns_are_none() {
371        assert_eq!(
372            body_system_for_organ("3d-vh-m-lung.glb"),
373            Some("respiratory")
374        );
375        assert_eq!(
376            body_system_for_organ("blood-vasculature"),
377            Some("circulatory")
378        );
379        assert_eq!(body_system_for_organ("eye-left"), Some("sensory"));
380        assert_eq!(body_system_for_organ("kidney-r"), Some("urinary"));
381        // Model-specific reproductive organs.
382        assert_eq!(body_system_for_organ("prostate"), Some("reproductive"));
383        assert_eq!(body_system_for_organ("uterus"), Some("reproductive"));
384        // The organs the first real full-body run surfaced (multi-provider prefixes + new tokens).
385        assert_eq!(
386            body_system_for_organ("3d-allen-m-brain.glb"),
387            Some("nervous")
388        );
389        assert_eq!(
390            body_system_for_organ("3d-nih-m-lymph-node.glb"),
391            Some("immune_lymphatic")
392        );
393        assert_eq!(
394            body_system_for_organ("3d-vh-m-main-bronchus.glb"),
395            Some("respiratory")
396        );
397        assert_eq!(
398            body_system_for_organ("3d-vh-m-mouth.glb"),
399            Some("digestive")
400        );
401        assert_eq!(
402            body_system_for_organ("3d-vh-m-pelvis.glb"),
403            Some("skeletal")
404        );
405        assert_eq!(
406            body_system_for_organ("3d-vh-m-urinary-bladder.glb"),
407            Some("urinary")
408        );
409        // Unknown → reported as None, never guessed.
410        assert_eq!(body_system_for_organ("3d-vh-m-flux-capacitor.glb"), None);
411    }
412
413    #[test]
414    fn organs_participate_in_multiple_systems() {
415        use crate::anatomy::systems::body_system;
416        // The pancreas is a building block of THREE systems — primary digestive, plus endocrine + exocrine.
417        let m = system_memberships_for_organ("3d-vh-m-pancreas.glb");
418        assert_eq!(m[0], ("digestive", true), "primary comes first");
419        let ids: Vec<&str> = m.iter().map(|(s, _)| *s).collect();
420        assert!(
421            ids.contains(&"endocrine") && ids.contains(&"exocrine"),
422            "pancreas multi-system: {ids:?}"
423        );
424        // The primary agrees with body_system_for_organ.
425        assert_eq!(body_system_for_organ("pancreas"), Some("digestive"));
426        // Skin: a barrier (primary integumentary) that also senses and secretes.
427        let skin: Vec<&str> = system_memberships_for_organ("skin")
428            .iter()
429            .map(|(s, _)| *s)
430            .collect();
431        assert!(
432            skin.contains(&"integumentary")
433                && skin.contains(&"sensory")
434                && skin.contains(&"exocrine"),
435            "skin memberships: {skin:?}"
436        );
437        // A single-system organ has exactly one membership (the primary).
438        assert_eq!(
439            system_memberships_for_organ("heart"),
440            vec![("circulatory", true)]
441        );
442        // The diaphragm is now a muscle (primary) that is also respiratory.
443        let dia: Vec<&str> = system_memberships_for_organ("diaphragm")
444            .iter()
445            .map(|(s, _)| *s)
446            .collect();
447        assert_eq!(dia, vec!["muscular", "respiratory"]);
448        // Every secondary membership names a real body system (no typo silently colouring nothing).
449        for (organ, sys) in ORGAN_SECONDARY_SYSTEMS {
450            assert!(
451                body_system(sys).is_some(),
452                "organ {organ} secondary → unknown system {sys}"
453            );
454        }
455        // An unknown organ has no memberships (reported, not guessed).
456        assert!(system_memberships_for_organ("flux-capacitor").is_empty());
457    }
458
459    #[test]
460    fn every_mapped_system_id_is_a_real_body_system() {
461        // Guards against a typo'd system id silently colouring nothing.
462        for (organ, sys) in ORGAN_SYSTEMS {
463            assert!(
464                body_system(sys).is_some(),
465                "organ {organ} maps to unknown system id {sys}"
466            );
467        }
468    }
469
470    #[test]
471    fn every_one_of_the_17_systems_is_accounted_for() {
472        // The honest completeness guarantee: no system is silently unsupported. Each of the 17 is
473        // either a discrete-organ system with at least one organ in the paint map, or an explicitly
474        // distributed-overlay network (ECS / ENS / glymphatic) with deliberately no standalone organ.
475        use crate::anatomy::systems::BODY_SYSTEMS;
476        assert_eq!(BODY_SYSTEMS.len(), 17);
477        for s in BODY_SYSTEMS {
478            let has_organ = ORGAN_SYSTEMS.iter().any(|(_, sys)| *sys == s.id);
479            match system_representation(s.id) {
480                SystemRepresentation::DiscreteOrgans => assert!(
481                    has_organ,
482                    "discrete-organ system {} has no organ in the paint map",
483                    s.id
484                ),
485                SystemRepresentation::DistributedOverlay => assert!(
486                    !has_organ,
487                    "distributed system {} should not carry a standalone organ",
488                    s.id
489                ),
490            }
491        }
492    }
493
494    #[test]
495    fn only_ecs_ens_glymphatic_are_distributed_overlays() {
496        for &distributed in &["ecs", "ens", "glymphatic"] {
497            assert_eq!(
498                system_representation(distributed),
499                SystemRepresentation::DistributedOverlay
500            );
501        }
502        // The newly-added discrete systems now paint real organs.
503        assert_eq!(body_system_for_organ("inner-ear"), Some("vestibular"));
504        assert_eq!(body_system_for_organ("salivary-gland"), Some("exocrine"));
505        for &discrete in &["circulatory", "vestibular", "exocrine", "reproductive"] {
506            assert_eq!(
507                system_representation(discrete),
508                SystemRepresentation::DiscreteOrgans
509            );
510        }
511    }
512
513    #[test]
514    fn distributed_overlays_carry_anatomical_host_hints() {
515        // ENS lines the gut, glymphatic clears the brain, ECS is whole-body (empty = no local host).
516        assert_eq!(overlay_host_systems("ens"), &["digestive"]);
517        assert_eq!(overlay_host_systems("glymphatic"), &["nervous"]);
518        assert_eq!(overlay_host_systems("ecs"), &[] as &[&str]);
519        // Every host hint names a real, discrete-organ system (so the highlight has a mesh to land on).
520        for &distributed in &["ens", "glymphatic", "ecs"] {
521            for host in overlay_host_systems(distributed) {
522                assert!(
523                    body_system(host).is_some(),
524                    "{distributed} host {host} unknown"
525                );
526                assert_eq!(
527                    system_representation(host),
528                    SystemRepresentation::DiscreteOrgans
529                );
530            }
531        }
532    }
533}