1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct EthnicityAffiliation {
26 pub token: String,
28 pub label: String,
30}
31
32impl EthnicityAffiliation {
33 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AncestryInvalid {
49 NotImported,
51 EmptyLabel,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct AncestryRecord {
57 pub token: String,
58 pub label: String,
59 pub imported_from: String,
61}
62
63impl AncestryRecord {
64 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#[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 pub fn is_empty(&self) -> bool {
94 self.ethnicities.is_empty() && self.genetic_ancestry.is_empty()
95 }
96
97 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct KnowledgeContextEdge {
122 pub id: String,
123 pub kind: ContextEdgeKind,
124 pub context_tokens: Vec<String>,
126 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 #[serde(default)]
134 pub illustrative: bool,
135}
136
137#[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
151pub 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
174pub 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
226pub 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 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 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}