Skip to main content

wellfare_core/anatomy/
knowledge_context.rs

1//! Ethnicity and genetic ancestry as **knowledge context**, not appearance and not a body type.
2//!
3//! Self-identified ethnicity is biomedical *and* personal. It can change which prevalence,
4//! pharmacology, and screening edges are *relevant* (always [`EpistemicStatus::Hypothesis`]).
5//! It must not pick a stereotyped mesh, invent skin/hair/eyes, or stand in for karyotype.
6//! Cosmetic appearance stays on explicit eye / hair / skin declarations.
7//!
8//! There is **no closed racial taxonomy** in the engine. Tokens are the person's words (or a
9//! jurisdiction pack IRI). Genetic ancestry is a **separate** record and only exists if they
10//! imported one they chose — never inferred from a photo or from ethnicity.
11//!
12//! The shipped [`illustrative_context_pack`] is machinery + a few well-cited public examples.
13//! It is not a guideline set. Timothy / a clinician pack replaces it.
14
15use serde::{Deserialize, Serialize};
16
17use crate::record::EpistemicStatus;
18
19use super::factor::EvidenceTier;
20use super::observations::{BodyObservation, RepresentationBind, bind_for_code};
21use super::slugify;
22
23/// One self-identified affiliation. Repeatable. Open vocabulary.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct EthnicityAffiliation {
26    /// Slug or pack IRI used for matching. Not a race enum.
27    pub token: String,
28    /// What they wrote (or the pack's display label).
29    pub label: String,
30}
31
32impl EthnicityAffiliation {
33    /// Declared entries.
34    pub fn declared(label: &str) -> Option<Self> {
35        let label = label.trim();
36        if label.is_empty() {
37            return None;
38        }
39        Some(Self {
40            token: slugify(label),
41            label: label.to_string(),
42        })
43    }
44}
45
46/// Why an ancestry record was refused.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AncestryInvalid {
49    /// Ancestry is import-only. Typing ethnicity, a photo, or an empty source is not enough.
50    NotImported,
51    EmptyLabel,
52}
53
54/// Genetic-ancestry context. Exists only when the person imported a record they chose.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct AncestryRecord {
57    pub token: String,
58    pub label: String,
59    /// Provenance of the imported record (lab, file, pack id). Required.
60    pub imported_from: String,
61}
62
63impl AncestryRecord {
64    /// Constructs from import.
65    pub fn from_import(label: &str, imported_from: &str) -> Result<Self, AncestryInvalid> {
66        let label = label.trim();
67        let imported_from = imported_from.trim();
68        if label.is_empty() {
69            return Err(AncestryInvalid::EmptyLabel);
70        }
71        if imported_from.is_empty() {
72            return Err(AncestryInvalid::NotImported);
73        }
74        Ok(Self {
75            token: slugify(label),
76            label: label.to_string(),
77            imported_from: imported_from.to_string(),
78        })
79    }
80}
81
82/// The person's declared / imported knowledge context. Never a fit input.
83#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
84pub struct SubjectKnowledgeContext {
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub ethnicities: Vec<EthnicityAffiliation>,
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub genetic_ancestry: Vec<AncestryRecord>,
89}
90
91impl SubjectKnowledgeContext {
92    ///  when empty.
93    pub fn is_empty(&self) -> bool {
94        self.ethnicities.is_empty() && self.genetic_ancestry.is_empty()
95    }
96
97    /// Slugs used to match a context pack (ethnicity ∪ imported ancestry).
98    pub fn match_tokens(&self) -> Vec<String> {
99        let mut out = Vec::new();
100        for e in &self.ethnicities {
101            push_token(&mut out, &e.token);
102        }
103        for a in &self.genetic_ancestry {
104            push_token(&mut out, &a.token);
105        }
106        out
107    }
108}
109
110/// Kind of biomedical edge a context token can activate.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113pub enum ContextEdgeKind {
114    Prevalence,
115    Pharmacology,
116    Screening,
117}
118
119/// One curated (or illustrative) context → topic edge.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct KnowledgeContextEdge {
122    pub id: String,
123    pub kind: ContextEdgeKind,
124    /// Open tokens that activate this edge (slugs). Not a closed race list.
125    pub context_tokens: Vec<String>,
126    /// Topic key (`g6pd`, `carbamazepine-hla-b1502`, a MONDO / drug slug).
127    pub topic: String,
128    pub note: String,
129    pub evidence: EvidenceTier,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub citation: Option<String>,
132    /// Shipped example, not a curated guideline pack.
133    #[serde(default)]
134    pub illustrative: bool,
135}
136
137/// A hypothesis produced when the person's context matches a pack edge.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub struct KnowledgeConsideration {
140    pub kind: ContextEdgeKind,
141    pub topic: String,
142    pub note: String,
143    pub matched_tokens: Vec<String>,
144    pub evidence: EvidenceTier,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub citation: Option<String>,
147    pub epistemic_status: EpistemicStatus,
148    pub illustrative: bool,
149}
150
151/// Collect declared ethnicity observations. Genetic-ancestry codes are **not** turned into
152/// affiliations here — ancestry requires [`AncestryRecord::from_import`].
153pub fn affiliations_from_observations(obs: &[BodyObservation]) -> Vec<EthnicityAffiliation> {
154    let mut out = Vec::new();
155    for o in obs {
156        if o.code.trim() != "q42:ethnicity" {
157            continue;
158        }
159        if bind_for_code(&o.code) != RepresentationBind::KnowledgeContext {
160            continue;
161        }
162        if let Some(a) = o.named.as_deref().and_then(EthnicityAffiliation::declared) {
163            if !out
164                .iter()
165                .any(|x: &EthnicityAffiliation| x.token == a.token)
166            {
167                out.push(a);
168            }
169        }
170    }
171    out
172}
173
174/// Match the person's context against a pack. Empty pack or no matching tokens → no considerations
175/// (honest empty, not a guess). Every hit is a [`EpistemicStatus::Hypothesis`].
176///
177/// `live_topics` filters to issues already on the graph (MONDO / drug / UniProt slugs). Empty
178/// means "show every matching edge" (education / any-person study).
179pub fn considerations_for_context(
180    subject: &SubjectKnowledgeContext,
181    pack: &[KnowledgeContextEdge],
182    live_topics: &[String],
183) -> Vec<KnowledgeConsideration> {
184    let tokens = subject.match_tokens();
185    if tokens.is_empty() {
186        return Vec::new();
187    }
188    let live: Vec<String> = live_topics.iter().map(|t| slugify(t)).collect();
189    let mut out = Vec::new();
190    for edge in pack {
191        let matched: Vec<String> = edge
192            .context_tokens
193            .iter()
194            .map(|t| slugify(t))
195            .filter(|et| tokens.iter().any(|st| tokens_match(st, et)))
196            .collect();
197        if matched.is_empty() {
198            continue;
199        }
200        if !live.is_empty() {
201            let topic = slugify(&edge.topic);
202            if !live.iter().any(|t| t == &topic || tokens_match(t, &topic)) {
203                continue;
204            }
205        }
206        out.push(KnowledgeConsideration {
207            kind: edge.kind,
208            topic: edge.topic.clone(),
209            note: edge.note.clone(),
210            matched_tokens: matched,
211            evidence: edge.evidence,
212            citation: edge.citation.clone(),
213            epistemic_status: EpistemicStatus::Hypothesis,
214            illustrative: edge.illustrative,
215        });
216    }
217    out.sort_by(|a, b| {
218        a.kind
219            .cmp(&b.kind)
220            .then(a.topic.cmp(&b.topic))
221            .then(a.note.cmp(&b.note))
222    });
223    out
224}
225
226/// Small public-knowledge examples so the machinery is exercisable. Not a guideline set,
227/// not a racial typology, not appearance.
228pub fn illustrative_context_pack() -> Vec<KnowledgeContextEdge> {
229    vec![
230        KnowledgeContextEdge {
231            id: "illust-g6pd-pharm".into(),
232            kind: ContextEdgeKind::Pharmacology,
233            context_tokens: vec![
234                "mediterranean".into(),
235                "african".into(),
236                "west-african".into(),
237                "middle-eastern".into(),
238                "southeast-asian".into(),
239                "kurdish".into(),
240            ],
241            topic: "g6pd".into(),
242            note: "Some populations in which this affiliation is often recorded have a higher \
243published prevalence of G6PD deficiency. That can be relevant to oxidant drugs \
244(e.g. primaquine) and fava beans — a pharmacology hypothesis to discuss, not a diagnosis \
245and not a type of human."
246                .into(),
247            evidence: EvidenceTier::ClinicalEvidence,
248            citation: Some("WHO G6PD deficiency (public monograph)".into()),
249            illustrative: true,
250        },
251        KnowledgeContextEdge {
252            id: "illust-hla-b1502".into(),
253            kind: ContextEdgeKind::Pharmacology,
254            context_tokens: vec![
255                "han-chinese".into(),
256                "thai".into(),
257                "malay".into(),
258                "filipino".into(),
259                "east-asian".into(),
260                "southeast-asian".into(),
261            ],
262            topic: "carbamazepine-hla-b1502".into(),
263            note: "HLA-B*1502 is more frequent in some East and South-East Asian groups and is \
264linked to severe cutaneous reactions with carbamazepine. A labelled pharmacology \
265hypothesis (FDA boxed warning), not a prescription decision and not a facial type."
266                .into(),
267            evidence: EvidenceTier::ClinicalEvidence,
268            citation: Some("FDA carbamazepine boxed warning — HLA-B*1502 / SJS-TEN".into()),
269            illustrative: true,
270        },
271        KnowledgeContextEdge {
272            id: "illust-sickle-screen".into(),
273            kind: ContextEdgeKind::Screening,
274            context_tokens: vec![
275                "west-african".into(),
276                "central-african".into(),
277                "african".into(),
278                "mediterranean".into(),
279                "middle-eastern".into(),
280                "south-asian".into(),
281            ],
282            topic: "sickle-cell".into(),
283            note: "Sickle-cell trait and disease have higher published prevalence in several \
284African, Mediterranean, Middle-Eastern, and South-Asian populations. A screening \
285hypothesis if relevant to the person — never inferred from appearance."
286                .into(),
287            evidence: EvidenceTier::ClinicalEvidence,
288            citation: Some("CDC sickle cell disease (public fact sheet)".into()),
289            illustrative: true,
290        },
291        KnowledgeContextEdge {
292            id: "illust-taysachs-screen".into(),
293            kind: ContextEdgeKind::Screening,
294            context_tokens: vec![
295                "ashkenazi".into(),
296                "ashkenazi-jewish".into(),
297                "french-canadian".into(),
298                "cajun".into(),
299            ],
300            topic: "tay-sachs".into(),
301            note:
302                "Tay-Sachs carrier frequency is higher in some Ashkenazi Jewish, French-Canadian, \
303and Cajun communities. A carrier-screening hypothesis, not a diagnosis and not a \
304cosmetic cue."
305                    .into(),
306            evidence: EvidenceTier::ClinicalEvidence,
307            citation: Some("ACMG / ACOG carrier-screening statements (public)".into()),
308            illustrative: true,
309        },
310    ]
311}
312
313fn push_token(out: &mut Vec<String>, token: &str) {
314    let t = slugify(token);
315    if t.is_empty() {
316        return;
317    }
318    if !out.iter().any(|x| x == &t) {
319        out.push(t);
320    }
321}
322
323fn tokens_match(subject: &str, edge: &str) -> bool {
324    subject == edge || subject.starts_with(edge) || edge.starts_with(subject)
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330    use crate::anatomy::constitution::{BodyConstitution, BodyFit};
331    use crate::anatomy::observations::{InstrumentKind, bind_for_code};
332
333    #[test]
334    fn ethnicity_does_not_change_body_fit() {
335        let mut with = BodyConstitution::default();
336        with.knowledge
337            .ethnicities
338            .push(EthnicityAffiliation::declared("Ashkenazi Jewish").unwrap());
339        with.knowledge
340            .ethnicities
341            .push(EthnicityAffiliation::declared("Greek").unwrap());
342        let empty = BodyConstitution::default();
343        let a = with.fit();
344        let b = empty.fit();
345        assert!(same_geometry(&a, &b));
346        assert!(a.identity);
347        assert!(
348            a.honesty_notes
349                .iter()
350                .any(|n| n.contains("knowledge context"))
351        );
352        assert!(!a.used_fields.iter().any(|f| f.contains("ethnic")));
353    }
354
355    #[test]
356    fn ancestry_requires_an_import_the_person_chose() {
357        assert_eq!(
358            AncestryRecord::from_import("Yoruba", ""),
359            Err(AncestryInvalid::NotImported)
360        );
361        assert!(AncestryRecord::from_import("Yoruba", "imported:lab-report.vcf").is_ok());
362    }
363
364    #[test]
365    fn ethnicity_observation_is_not_ancestry_and_not_appearance() {
366        let obs = [BodyObservation {
367            code: "q42:ethnicity".into(),
368            value_milli: 0,
369            unit: "{named}".into(),
370            instrument: InstrumentKind::Declared,
371            at_unix: 1,
372            note: None,
373            named: Some("Han Chinese".into()),
374        }];
375        let aff = affiliations_from_observations(&obs);
376        assert_eq!(aff.len(), 1);
377        assert_eq!(aff[0].token, "han-chinese");
378        assert_eq!(
379            bind_for_code("q42:ethnicity"),
380            RepresentationBind::KnowledgeContext
381        );
382        assert_ne!(
383            bind_for_code("q42:ethnicity"),
384            RepresentationBind::AppearanceSkin
385        );
386        assert_eq!(
387            bind_for_code("q42:skin-tone"),
388            RepresentationBind::AppearanceSkin
389        );
390        // Ethnicity never becomes an ancestry record.
391        assert!(AncestryRecord::from_import(&aff[0].label, "").is_err());
392    }
393
394    #[test]
395    fn considerations_are_hypotheses_and_token_matched() {
396        let mut subject = SubjectKnowledgeContext::default();
397        subject
398            .ethnicities
399            .push(EthnicityAffiliation::declared("Ashkenazi").unwrap());
400        let all = considerations_for_context(&subject, &illustrative_context_pack(), &[]);
401        assert!(all.iter().any(|c| c.topic == "tay-sachs"));
402        assert!(
403            all.iter()
404                .all(|c| c.epistemic_status == EpistemicStatus::Hypothesis)
405        );
406        assert!(all.iter().all(|c| c.illustrative));
407        assert!(!all.iter().any(|c| c.topic == "g6pd"));
408
409        let filtered = considerations_for_context(
410            &subject,
411            &illustrative_context_pack(),
412            &["tay-sachs".into()],
413        );
414        assert_eq!(filtered.len(), 1);
415        assert_eq!(filtered[0].kind, ContextEdgeKind::Screening);
416    }
417
418    #[test]
419    fn empty_context_or_pack_is_honest_empty() {
420        let subject = SubjectKnowledgeContext::default();
421        assert!(considerations_for_context(&subject, &illustrative_context_pack(), &[]).is_empty());
422        let mut declared = SubjectKnowledgeContext::default();
423        declared
424            .ethnicities
425            .push(EthnicityAffiliation::declared("Sámi").unwrap());
426        assert!(considerations_for_context(&declared, &[], &[]).is_empty());
427        // Unmatched token: no invented consideration.
428        assert!(
429            considerations_for_context(&declared, &illustrative_context_pack(), &[]).is_empty()
430        );
431    }
432
433    #[test]
434    fn repeatable_affiliations_and_imported_ancestry_both_match() {
435        let mut subject = SubjectKnowledgeContext::default();
436        subject
437            .ethnicities
438            .push(EthnicityAffiliation::declared("Italian").unwrap());
439        subject
440            .genetic_ancestry
441            .push(AncestryRecord::from_import("West African", "imported:ancestry.pack").unwrap());
442        let hits = considerations_for_context(&subject, &illustrative_context_pack(), &[]);
443        assert!(hits.iter().any(|c| c.topic == "sickle-cell"));
444        assert!(hits.iter().any(|c| c.topic == "g6pd"));
445    }
446
447    fn same_geometry(a: &BodyFit, b: &BodyFit) -> bool {
448        a.stature_scale == b.stature_scale
449            && a.torso_scale_y == b.torso_scale_y
450            && a.leg_scale_y == b.leg_scale_y
451            && a.arm_span_scale_x == b.arm_span_scale_x
452            && a.shoulder_scale_x == b.shoulder_scale_x
453            && a.chest_radial == b.chest_radial
454            && a.waist_radial == b.waist_radial
455            && a.hip_radial == b.hip_radial
456            && a.pregnancy_abdomen == b.pregnancy_abdomen
457            && a.hidden_keys == b.hidden_keys
458            && a.identity == b.identity
459    }
460}