Skip to main content

qualia_core_db/
clinical_engine.rs

1//! Clinical Decision Support Engine.
2//!
3//! Validated clinical risk scoring, pharmacological screening, and
4//! FHIR Observation validation — all as pure-Rust, zero-FFI computations.
5//!
6//! Risk models:
7//!   `qualia:computeRiskScore:framingham`  → `framingham_10yr_risk()`
8//!   `qualia:computeRiskScore:cha2ds2`     → `cha2ds2_vasc_score()`
9//!   `qualia:computeRiskScore:score2`      → `score2_risk()`
10//!
11//! Pharmacology:
12//!   `qualia:evaluateDrugInteraction`      → `check_drug_interactions()`
13//!   `qualia:checkContraindication`        → `check_contraindications()`
14//!
15//! Observation validation:
16//!   `qualia:validateFhirObservation`      → `validate_fhir_observation()`
17//!   `qualia:evaluateLongitudinalTrend`    → `longitudinal_trend()`
18//!   `qualia:evaluateGeneExpression`       → `evaluate_gene_expression()`
19
20// ─── Shared enumerations ──────────────────────────────────────────────────────
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum RiskCategory {
24    Low,
25    Moderate,
26    High,
27    VeryHigh,
28}
29
30// ─── Framingham 10-year CVD risk ──────────────────────────────────────────────
31// Anderson et al. 1991 / Wilson et al. 1998 (ATP III sex-specific log-linear model)
32
33#[derive(Debug, Clone)]
34pub struct FraminghamInput {
35    pub age: u8,
36    pub sex_male: bool,
37    pub total_cholesterol_mmol: f64,
38    pub hdl_cholesterol_mmol: f64,
39    pub systolic_bp: f64,
40    /// True if currently on antihypertensive medication.
41    pub bp_treated: bool,
42    pub current_smoker: bool,
43    pub diabetic: bool,
44}
45
46#[derive(Debug, Clone)]
47pub struct FraminghamResult {
48    /// Estimated 10-year absolute risk (0.0–1.0).
49    pub risk_10yr: f64,
50    pub category: RiskCategory,
51    pub log_score: f64,
52}
53
54/// Framingham 10-year cardiovascular risk (Anderson 1991 / Wilson 1998,
55/// ATP III sex-specific log-linear model).
56///
57/// Returns the estimated absolute risk in `[0, 1]` plus a `Low`
58/// (<10%), `Moderate` (≤20%), or `High` (>20%) category. Inputs
59/// must be physiologically plausible (positive cholesterol/SBP values)
60/// — the caller is responsible for range validation; no clamping is
61/// applied beyond the final `[0, 1]` bound.
62pub fn framingham_10yr_risk(input: &FraminghamInput) -> FraminghamResult {
63    // Wilson 1998 coefficients (Table 2).
64    let (b_age, b_tc, b_hdl, b_sbp_unt, b_sbp_trt, b_smoke, b_diab, baseline_surv, mean_sum) =
65        if input.sex_male {
66            (
67                3.06117,
68                1.12370,
69                -0.93263,
70                1.93303,
71                1.99881,
72                0.65451,
73                0.57367,
74                0.88936_f64,
75                23.9802_f64,
76            )
77        } else {
78            (
79                2.32888,
80                1.20904,
81                -0.70833,
82                2.76157,
83                2.82263,
84                0.52873,
85                0.69154,
86                0.95012_f64,
87                26.1931_f64,
88            )
89        };
90
91    let sbp_coeff = if input.bp_treated {
92        b_sbp_trt
93    } else {
94        b_sbp_unt
95    };
96
97    let log_score = b_age * (input.age as f64).ln()
98        + b_tc * input.total_cholesterol_mmol.ln()
99        + b_hdl * input.hdl_cholesterol_mmol.ln()
100        + sbp_coeff * input.systolic_bp.ln()
101        + b_smoke * if input.current_smoker { 1.0 } else { 0.0 }
102        + b_diab * if input.diabetic { 1.0 } else { 0.0 };
103
104    let risk_10yr = (1.0 - baseline_surv.powf((log_score - mean_sum).exp())).clamp(0.0, 1.0);
105
106    let category = if risk_10yr < 0.10 {
107        RiskCategory::Low
108    } else if risk_10yr <= 0.20 {
109        RiskCategory::Moderate
110    } else {
111        RiskCategory::High
112    };
113
114    FraminghamResult {
115        risk_10yr,
116        category,
117        log_score,
118    }
119}
120
121// ─── CHA₂DS₂-VASc ────────────────────────────────────────────────────────────
122// Lip GY 2010 / ESC 2020 guidelines for non-valvular atrial fibrillation
123
124#[derive(Debug, Clone, Default)]
125pub struct Cha2ds2VascInput {
126    pub congestive_heart_failure: bool, // +1
127    pub hypertension: bool,             // +1
128    pub age_75_or_older: bool,          // +2
129    pub diabetes: bool,                 // +1
130    pub stroke_tia_history: bool,       // +2
131    pub vascular_disease: bool,         // +1
132    pub age_65_to_74: bool,             // +1
133    pub sex_female: bool,               // +1
134}
135
136#[derive(Debug, Clone)]
137pub struct Cha2ds2VascResult {
138    pub score: u8,
139    /// Annual stroke risk % from Lip 2010 cohort data.
140    pub annual_stroke_risk_pct: f64,
141    /// ESC 2020: men ≥2, women ≥3.
142    pub anticoagulation_recommended: bool,
143}
144
145/// CHA₂DS₂-VASc stroke-risk score for non-valvular atrial fibrillation
146/// (Lip 2010 / ESC 2020).
147///
148/// Sums the weighted factors (0–9), maps the score to a cohort-derived
149/// annual stroke-risk percentage, and flags whether anticoagulation is
150/// recommended per ESC 2020 thresholds (men ≥2, women ≥3).
151pub fn cha2ds2_vasc_score(input: &Cha2ds2VascInput) -> Cha2ds2VascResult {
152    let score = input.congestive_heart_failure as u8
153        + input.hypertension as u8
154        + if input.age_75_or_older { 2 } else { 0 }
155        + input.diabetes as u8
156        + if input.stroke_tia_history { 2 } else { 0 }
157        + input.vascular_disease as u8
158        + input.age_65_to_74 as u8
159        + input.sex_female as u8;
160
161    let annual_risk = match score {
162        0 => 0.0,
163        1 => 1.3,
164        2 => 2.2,
165        3 => 3.2,
166        4 => 4.0,
167        5 => 6.7,
168        6 => 9.8,
169        7 => 9.6,
170        8 => 12.5,
171        _ => 15.2,
172    };
173
174    let anticoagulation_recommended = if input.sex_female {
175        score >= 3
176    } else {
177        score >= 2
178    };
179
180    Cha2ds2VascResult {
181        score,
182        annual_stroke_risk_pct: annual_risk,
183        anticoagulation_recommended,
184    }
185}
186
187// ─── SCORE2 ───────────────────────────────────────────────────────────────────
188// ESC CVD Risk Collaboration / SCORE2 Working Group 2021
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum Score2Region {
192    Low,
193    Moderate,
194    High,
195    VeryHigh,
196}
197
198#[derive(Debug, Clone)]
199pub struct Score2Input {
200    pub age: u8,
201    pub sex_male: bool,
202    pub systolic_bp: f64,
203    pub total_cholesterol_mmol: f64,
204    pub hdl_cholesterol_mmol: f64,
205    pub current_smoker: bool,
206    pub risk_region: Score2Region,
207}
208
209#[derive(Debug, Clone)]
210pub struct Score2Result {
211    pub risk_10yr_pct: f64,
212    pub category: RiskCategory,
213}
214
215/// SCORE2 10-year cardiovascular risk (ESC CVD Risk Collaboration /
216/// SCORE2 Working Group 2021).
217///
218/// Computes the sex-specific baseline risk from centred age, SBP,
219/// non-HDL cholesterol, and smoking, then applies the regional
220/// calibration multiplier (`Low` 0.71 → `VeryHigh` 2.27). Returns risk
221/// as a percentage in `[0, 100]` with a `Low`/`Moderate`/`High`/
222/// `VeryHigh` category banded at 5/10/20%.
223pub fn score2_risk(input: &Score2Input) -> Score2Result {
224    let non_hdl = input.total_cholesterol_mmol - input.hdl_cholesterol_mmol;
225    let age_c = (input.age as f64 - 60.0) / 5.0;
226    let sbp_c = (input.systolic_bp - 120.0) / 20.0;
227    let chol_c = (non_hdl - 3.3) / 0.5;
228    let smoke = input.current_smoker as u8 as f64;
229
230    let (b_age, b_sbp, b_chol, b_smoke, baseline_surv) = if input.sex_male {
231        (0.3742_f64, 0.2628, 0.1401, 0.5865, 0.9605_f64)
232    } else {
233        (0.4648_f64, 0.3131, 0.1002, 0.7742, 0.9776_f64)
234    };
235
236    let linear = b_age * age_c + b_sbp * sbp_c + b_chol * chol_c + b_smoke * smoke;
237    let base_risk = 1.0 - baseline_surv.powf(linear.exp());
238
239    let calibrated_pct = (base_risk
240        * match input.risk_region {
241            Score2Region::Low => 0.71,
242            Score2Region::Moderate => 1.00,
243            Score2Region::High => 1.56,
244            Score2Region::VeryHigh => 2.27,
245        }
246        * 100.0)
247        .clamp(0.0, 100.0);
248
249    let category = if calibrated_pct < 5.0 {
250        RiskCategory::Low
251    } else if calibrated_pct <= 10.0 {
252        RiskCategory::Moderate
253    } else if calibrated_pct <= 20.0 {
254        RiskCategory::High
255    } else {
256        RiskCategory::VeryHigh
257    };
258
259    Score2Result {
260        risk_10yr_pct: calibrated_pct,
261        category,
262    }
263}
264
265// ─── Drug interaction screening ───────────────────────────────────────────────
266
267/// NCI CTCAE-style severity levels.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
269pub enum InteractionSeverity {
270    None = 0,
271    Minor = 1,
272    Moderate = 2,
273    Major = 3,
274    Contraindicated = 4,
275}
276
277#[derive(Debug, Clone)]
278pub struct DrugInteraction {
279    pub drug_a: u64,
280    pub drug_b: u64,
281    pub severity: InteractionSeverity,
282    pub mechanism: &'static str,
283}
284
285/// CYP450-based drug-drug interaction screening.
286/// Drug identifiers are `q_hash(rxnorm_name)`.
287pub fn check_drug_interactions(active_medications: &[u64]) -> Vec<DrugInteraction> {
288    // (drug_a, drug_b, severity, mechanism)
289    let pairs: &[(&str, &str, InteractionSeverity, &str)] = &[
290        (
291            "warfarin",
292            "ibuprofen",
293            InteractionSeverity::Major,
294            "CYP2C9 inhibition + antiplatelet effect → major bleeding",
295        ),
296        (
297            "warfarin",
298            "naproxen",
299            InteractionSeverity::Major,
300            "CYP2C9 inhibition + antiplatelet effect → major bleeding",
301        ),
302        (
303            "warfarin",
304            "aspirin",
305            InteractionSeverity::Moderate,
306            "Additive antiplatelet: monitor INR closely",
307        ),
308        (
309            "sertraline",
310            "phenelzine",
311            InteractionSeverity::Contraindicated,
312            "Serotonin syndrome risk (SSRI + MAOI)",
313        ),
314        (
315            "fluoxetine",
316            "selegiline",
317            InteractionSeverity::Contraindicated,
318            "Serotonin syndrome risk (SSRI + MAO-B)",
319        ),
320        (
321            "simvastatin",
322            "clarithromycin",
323            InteractionSeverity::Major,
324            "CYP3A4 inhibition → rhabdomyolysis risk",
325        ),
326        (
327            "atorvastatin",
328            "clarithromycin",
329            InteractionSeverity::Moderate,
330            "CYP3A4 inhibition → myopathy risk",
331        ),
332        (
333            "amiodarone",
334            "ciprofloxacin",
335            InteractionSeverity::Major,
336            "Additive QT prolongation → TdP risk",
337        ),
338        (
339            "methadone",
340            "azithromycin",
341            InteractionSeverity::Major,
342            "Additive QT prolongation → TdP risk",
343        ),
344        (
345            "lisinopril",
346            "spironolactone",
347            InteractionSeverity::Moderate,
348            "Hyperkalaemia risk (ACEi + K-sparing diuretic)",
349        ),
350        (
351            "ramipril",
352            "spironolactone",
353            InteractionSeverity::Moderate,
354            "Hyperkalaemia risk (ACEi + K-sparing diuretic)",
355        ),
356        (
357            "metformin",
358            "iohexol",
359            InteractionSeverity::Major,
360            "Lactic acidosis risk — hold metformin 48h before iodinated contrast",
361        ),
362        (
363            "lithium",
364            "ibuprofen",
365            InteractionSeverity::Major,
366            "NSAIDs reduce renal lithium clearance → toxicity",
367        ),
368        (
369            "lithium",
370            "diclofenac",
371            InteractionSeverity::Major,
372            "NSAIDs reduce renal lithium clearance → toxicity",
373        ),
374        (
375            "methotrexate",
376            "trimethoprim",
377            InteractionSeverity::Major,
378            "Additive folate antagonism → pancytopenia",
379        ),
380        (
381            "digoxin",
382            "amiodarone",
383            InteractionSeverity::Major,
384            "Amiodarone increases digoxin levels → toxicity",
385        ),
386        (
387            "clopidogrel",
388            "omeprazole",
389            InteractionSeverity::Moderate,
390            "CYP2C19 inhibition reduces clopidogrel activation",
391        ),
392        (
393            "tramadol",
394            "sertraline",
395            InteractionSeverity::Moderate,
396            "Serotonin syndrome + seizure threshold lowering",
397        ),
398    ];
399
400    let mut found = Vec::new();
401    for (i, &a) in active_medications.iter().enumerate() {
402        for &b in &active_medications[i + 1..] {
403            for &(na, nb, sev, mech) in pairs {
404                let ha = crate::q_hash(na);
405                let hb = crate::q_hash(nb);
406                if (a == ha && b == hb) || (a == hb && b == ha) {
407                    found.push(DrugInteraction {
408                        drug_a: a,
409                        drug_b: b,
410                        severity: sev,
411                        mechanism: mech,
412                    });
413                }
414            }
415        }
416    }
417    found
418}
419
420// ─── Contraindication checking ────────────────────────────────────────────────
421
422#[derive(Debug, Clone)]
423pub struct ContraindicationResult {
424    pub drug: u64,
425    pub condition_snomed: u64,
426    pub severity: InteractionSeverity,
427    pub reason: &'static str,
428}
429
430/// Checks a single medication (by q_hash name) against active conditions (SNOMED CT q_hashes).
431pub fn check_contraindications(
432    drug_hash: u64,
433    condition_hashes: &[u64],
434) -> Vec<ContraindicationResult> {
435    // (drug_name, snomed_name_as_hashed, severity, reason)
436    let table: &[(&str, &str, InteractionSeverity, &str)] = &[
437        (
438            "metformin",
439            "709044004",
440            InteractionSeverity::Contraindicated,
441            "CKD stage 4/5 (eGFR < 30): lactic acidosis risk",
442        ),
443        (
444            "nsaid",
445            "709044004",
446            InteractionSeverity::Major,
447            "CKD: NSAIDs worsen renal haemodynamics",
448        ),
449        (
450            "ibuprofen",
451            "709044004",
452            InteractionSeverity::Major,
453            "CKD: NSAIDs worsen renal haemodynamics",
454        ),
455        (
456            "naproxen",
457            "709044004",
458            InteractionSeverity::Major,
459            "CKD: NSAIDs worsen renal haemodynamics",
460        ),
461        (
462            "atenolol",
463            "195967001",
464            InteractionSeverity::Contraindicated,
465            "Asthma: non-selective beta-blockers precipitate bronchospasm",
466        ),
467        (
468            "propranolol",
469            "195967001",
470            InteractionSeverity::Contraindicated,
471            "Asthma: non-selective beta-blockers precipitate bronchospasm",
472        ),
473        (
474            "metoprolol",
475            "195967001",
476            InteractionSeverity::Moderate,
477            "Asthma: cardioselective beta-blocker — use with caution",
478        ),
479        (
480            "lithium",
481            "709044004",
482            InteractionSeverity::Contraindicated,
483            "CKD: lithium is renally cleared — nephrotoxicity risk",
484        ),
485        (
486            "clozapine",
487            "84989004",
488            InteractionSeverity::Major,
489            "Seizure disorder: clozapine lowers seizure threshold",
490        ),
491        (
492            "tramadol",
493            "84989004",
494            InteractionSeverity::Major,
495            "Seizure disorder: tramadol lowers seizure threshold",
496        ),
497        (
498            "warfarin",
499            "713078009",
500            InteractionSeverity::Major,
501            "Haemorrhagic stroke history: anticoagulation risk",
502        ),
503        (
504            "amiodarone",
505            "49436004",
506            InteractionSeverity::Major,
507            "Pulmonary disease: amiodarone pulmonary toxicity risk",
508        ),
509        (
510            "thalidomide",
511            "77386006",
512            InteractionSeverity::Contraindicated,
513            "Pregnancy: teratogen (Category X)",
514        ),
515        (
516            "isotretinoin",
517            "77386006",
518            InteractionSeverity::Contraindicated,
519            "Pregnancy: teratogen (Category X)",
520        ),
521        (
522            "methotrexate",
523            "77386006",
524            InteractionSeverity::Contraindicated,
525            "Pregnancy: teratogen — folate antagonist",
526        ),
527        (
528            "sildenafil",
529            "194828000",
530            InteractionSeverity::Contraindicated,
531            "Angina on nitrates: severe hypotension risk",
532        ),
533    ];
534
535    condition_hashes
536        .iter()
537        .filter_map(|&cond| {
538            table
539                .iter()
540                .find(|&&(dn, sn, _, _)| {
541                    crate::q_hash(dn) == drug_hash && crate::q_hash(sn) == cond
542                })
543                .map(|&(_, sn, sev, reason)| ContraindicationResult {
544                    drug: drug_hash,
545                    condition_snomed: crate::q_hash(sn),
546                    severity: sev,
547                    reason,
548                })
549        })
550        .collect()
551}
552
553// ─── FHIR Observation validation ─────────────────────────────────────────────
554
555#[derive(Debug, Clone)]
556pub struct FhirObservation {
557    /// LOINC code string, e.g. "4548-4".
558    pub loinc_code: String,
559    pub value: f64,
560    /// UCUM unit string, e.g. "%", "mmol/L".
561    pub unit_ucum: String,
562    pub reference_low: Option<f64>,
563    pub reference_high: Option<f64>,
564}
565
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567pub enum ObservationStatus {
568    Normal,
569    Low,
570    High,
571    CriticalLow,
572    CriticalHigh,
573    Unknown,
574}
575
576#[derive(Debug, Clone)]
577pub struct FhirValidationResult {
578    pub is_valid: bool,
579    pub status: ObservationStatus,
580    /// HL7 interpretation code: N / L / H / LL / HH / U.
581    pub interpretation_code: &'static str,
582}
583
584/// Classify a FHIR Observation value against built-in LOINC reference
585/// ranges, falling back to the caller-provided `reference_low`/`high`
586/// (with half-range critical margins) when the code is unlisted.
587///
588/// Returns `ObservationStatus::{Normal, Low, High, CriticalLow,
589/// CriticalHigh, Unknown}` plus the HL7 interpretation code
590/// (`N`/`L`/`H`/`LL`/`HH`/`U`). `is_valid` is false only when neither a
591/// known range nor caller references exist — the observation is then
592/// `Unknown` rather than guessed.
593pub fn validate_fhir_observation(obs: &FhirObservation) -> FhirValidationResult {
594    // (loinc_code, low, high, critical_low, critical_high)
595    const RANGES: &[(&str, f64, f64, f64, f64)] = &[
596        ("4548-4", 4.0, 5.7, 2.0, 15.0),       // HbA1c %
597        ("1558-6", 3.9, 5.5, 2.2, 25.0),       // Fasting glucose mmol/L
598        ("2093-3", 0.0, 5.17, 0.0, 15.0),      // Total cholesterol mmol/L
599        ("2089-1", 0.0, 3.36, 0.0, 12.0),      // LDL mmol/L
600        ("2085-9", 1.0, 3.0, 0.4, 5.0),        // HDL mmol/L
601        ("2571-8", 0.0, 1.7, 0.0, 10.0),       // Triglycerides mmol/L
602        ("62238-1", 60.0, 200.0, 5.0, 200.0),  // eGFR mL/min/1.73m²
603        ("9318-7", 0.0, 3.0, 0.0, 30.0),       // uACR mg/mmol
604        ("38483-4", 45.0, 90.0, 10.0, 1000.0), // Creatinine µmol/L
605        ("1742-6", 0.0, 41.0, 0.0, 1000.0),    // ALT U/L
606        ("1920-8", 0.0, 40.0, 0.0, 1000.0),    // AST U/L
607        ("718-7", 120.0, 170.0, 60.0, 200.0),  // Haemoglobin g/L
608        ("6690-2", 4.0, 11.0, 1.5, 30.0),      // WBC ×10⁹/L
609        ("30522-7", 0.0, 5.0, 0.0, 50.0),      // CRP mg/L
610        ("3016-3", 0.4, 4.0, 0.01, 100.0),     // TSH mIU/L
611        ("3024-7", 9.0, 19.0, 0.0, 50.0),      // Free T4 pmol/L
612        ("2143-6", 0.0, 500.0, 0.0, 2000.0),   // Cortisol AM nmol/L
613        ("1989-3", 50.0, 250.0, 10.0, 400.0),  // Vitamin D nmol/L
614        ("20448-7", 2.6, 24.9, 0.0, 200.0),    // Fasting insulin pmol/L
615        ("8480-6", 90.0, 140.0, 70.0, 220.0),  // Systolic BP mmHg
616        ("8462-4", 60.0, 90.0, 40.0, 140.0),   // Diastolic BP mmHg
617        ("8867-4", 50.0, 100.0, 30.0, 200.0),  // Resting HR bpm
618        ("80404-7", 20.0, 200.0, 0.0, 500.0),  // HRV RMSSD ms
619        ("59408-5", 95.0, 100.0, 85.0, 100.0), // SpO2 %
620        ("44261-6", 0.0, 4.0, 0.0, 27.0),      // PHQ-9 score
621        ("69737-5", 0.0, 4.0, 0.0, 21.0),      // GAD-7 score
622        ("93832-4", 70.0, 100.0, 40.0, 100.0), // Sleep efficiency %
623    ];
624
625    let range = RANGES
626        .iter()
627        .find(|(code, ..)| *code == obs.loinc_code.as_str());
628
629    let status = if let Some(&(_, low, high, crit_low, crit_high)) = range {
630        let v = obs.value;
631        if v < crit_low {
632            ObservationStatus::CriticalLow
633        } else if v > crit_high {
634            ObservationStatus::CriticalHigh
635        } else if v < low {
636            ObservationStatus::Low
637        } else if v > high {
638            ObservationStatus::High
639        } else {
640            ObservationStatus::Normal
641        }
642    } else if let (Some(low), Some(high)) = (obs.reference_low, obs.reference_high) {
643        let v = obs.value;
644        if v < low * 0.5 {
645            ObservationStatus::CriticalLow
646        } else if v > high * 2.0 {
647            ObservationStatus::CriticalHigh
648        } else if v < low {
649            ObservationStatus::Low
650        } else if v > high {
651            ObservationStatus::High
652        } else {
653            ObservationStatus::Normal
654        }
655    } else {
656        ObservationStatus::Unknown
657    };
658
659    let interp = match status {
660        ObservationStatus::Normal => "N",
661        ObservationStatus::Low => "L",
662        ObservationStatus::High => "H",
663        ObservationStatus::CriticalLow => "LL",
664        ObservationStatus::CriticalHigh => "HH",
665        ObservationStatus::Unknown => "U",
666    };
667
668    FhirValidationResult {
669        is_valid: status != ObservationStatus::Unknown,
670        status,
671        interpretation_code: interp,
672    }
673}
674
675// ─── Longitudinal trend analysis ─────────────────────────────────────────────
676
677#[derive(Debug, Clone)]
678pub struct TimePoint {
679    /// Unix timestamp in seconds.
680    pub timestamp_s: i64,
681    pub value: f64,
682}
683
684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685pub enum TrendDirection {
686    Improving,
687    Worsening,
688    Stable,
689    Insufficient,
690}
691
692#[derive(Debug, Clone)]
693pub struct TrendResult {
694    /// Ordinary least-squares slope in biomarker units per day.
695    pub slope_per_day: f64,
696    /// Coefficient of determination.
697    pub r_squared: f64,
698    /// Predicted value `forecast_days` after the last observation.
699    pub forecast: f64,
700    pub direction: TrendDirection,
701}
702
703/// OLS linear regression over a biomarker time series.
704/// `improvement_direction`: `1` = rising is good (e.g. eGFR), `-1` = falling is good (e.g. BP, HbA1c).
705pub fn longitudinal_trend(
706    series: &[TimePoint],
707    forecast_days: f64,
708    improvement_direction: i8,
709) -> TrendResult {
710    if series.len() < 2 {
711        let v = series.first().map(|p| p.value).unwrap_or(0.0);
712        return TrendResult {
713            slope_per_day: 0.0,
714            r_squared: 0.0,
715            forecast: v,
716            direction: TrendDirection::Insufficient,
717        };
718    }
719
720    let t0 = series[0].timestamp_s as f64;
721    let xs: Vec<f64> = series
722        .iter()
723        .map(|p| (p.timestamp_s as f64 - t0) / 86400.0)
724        .collect();
725    let ys: Vec<f64> = series.iter().map(|p| p.value).collect();
726    let n = xs.len() as f64;
727
728    let sx: f64 = xs.iter().sum();
729    let sy: f64 = ys.iter().sum();
730    let sxx: f64 = xs.iter().map(|x| x * x).sum();
731    let sxy: f64 = xs.iter().zip(ys.iter()).map(|(x, y)| x * y).sum();
732    let denom = n * sxx - sx * sx;
733
734    if denom.abs() < 1e-10 {
735        return TrendResult {
736            slope_per_day: 0.0,
737            r_squared: 1.0,
738            forecast: ys[0],
739            direction: TrendDirection::Stable,
740        };
741    }
742
743    let slope = (n * sxy - sx * sy) / denom;
744    let intercept = (sy - slope * sx) / n;
745    let y_mean = sy / n;
746
747    let ss_res: f64 = ys
748        .iter()
749        .zip(xs.iter())
750        .map(|(y, x)| (y - (intercept + slope * x)).powi(2))
751        .sum();
752    let ss_tot: f64 = ys.iter().map(|y| (y - y_mean).powi(2)).sum();
753    let r_squared = if ss_tot < 1e-10 {
754        1.0
755    } else {
756        1.0 - ss_res / ss_tot
757    };
758
759    let last_x = xs.last().copied().unwrap_or(0.0);
760    let forecast = intercept + slope * (last_x + forecast_days);
761
762    let direction = if slope.abs() < 0.001 {
763        TrendDirection::Stable
764    } else if (slope > 0.0 && improvement_direction > 0)
765        || (slope < 0.0 && improvement_direction < 0)
766    {
767        TrendDirection::Improving
768    } else {
769        TrendDirection::Worsening
770    };
771
772    TrendResult {
773        slope_per_day: slope,
774        r_squared,
775        forecast,
776        direction,
777    }
778}
779
780// ─── Gene expression evaluation ──────────────────────────────────────────────
781
782#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783pub enum ExpressionDirection {
784    Upregulated,
785    Downregulated,
786    Unchanged,
787}
788
789#[derive(Debug, Clone)]
790pub struct GeneExpressionResult {
791    pub gene_id: u64,
792    pub fold_change: f64,
793    pub log2_fold_change: f64,
794    pub is_significant: bool,
795    pub direction: ExpressionDirection,
796}
797
798/// Evaluates normalised expression (RPKM/TPM) against a fold-change threshold.
799pub fn evaluate_gene_expression(
800    gene_id: u64,
801    baseline: f64,
802    treatment: f64,
803    fc_threshold: f64,
804) -> GeneExpressionResult {
805    let fold_change = if baseline > 1e-9 {
806        treatment / baseline
807    } else {
808        f64::INFINITY
809    };
810    let log2_fc = if fold_change.is_finite() {
811        fold_change.log2()
812    } else {
813        f64::INFINITY
814    };
815    let is_significant = fold_change >= fc_threshold
816        || (fold_change.is_finite() && fold_change <= 1.0 / fc_threshold);
817
818    let direction = if !is_significant {
819        ExpressionDirection::Unchanged
820    } else if fold_change >= 1.0 {
821        ExpressionDirection::Upregulated
822    } else {
823        ExpressionDirection::Downregulated
824    };
825
826    GeneExpressionResult {
827        gene_id,
828        fold_change,
829        log2_fold_change: log2_fc,
830        is_significant,
831        direction,
832    }
833}
834
835// ─── Renal Function Estimation ───────────────────────────────────────────────
836
837#[derive(Debug, Clone)]
838pub struct RenalInput {
839    pub age: u8,
840    pub sex_male: bool,
841    pub weight_kg: f64,
842    /// Serum creatinine in mg/dL
843    pub serum_creatinine: f64,
844}
845
846/// Computes Creatinine Clearance (CrCl) via Cockcroft-Gault equation.
847pub fn cockcroft_gault_crcl(input: &RenalInput) -> f64 {
848    let mut crcl = ((140.0 - input.age as f64) * input.weight_kg) / (72.0 * input.serum_creatinine);
849    if !input.sex_male {
850        crcl *= 0.85;
851    }
852    crcl
853}
854
855/// Computes eGFR using the 2021 CKD-EPI equation (creatinine, without race).
856pub fn ckd_epi_egfr(input: &RenalInput) -> f64 {
857    let k = if input.sex_male { 0.9 } else { 0.7 };
858    let a = if input.sex_male { -0.302 } else { -0.241 };
859
860    let scr_k = input.serum_creatinine / k;
861    let min_val = scr_k.min(1.0);
862    let max_val = scr_k.max(1.0);
863
864    let mut egfr =
865        142.0 * min_val.powf(a) * max_val.powf(-1.200) * 0.9938_f64.powf(input.age as f64);
866    if !input.sex_male {
867        egfr *= 1.012;
868    }
869    egfr
870}
871
872// ─── Pharmacokinetics (PK) ───────────────────────────────────────────────────
873
874#[derive(Debug, Clone)]
875pub struct PkOneCompartmentInput {
876    pub dose_mg: f64,
877    /// Volume of distribution (L)
878    pub volume_distribution_l: f64,
879    /// Clearance (L/hr)
880    pub clearance_l_hr: f64,
881    /// Time since dose (hours)
882    pub time_hr: f64,
883}
884
885#[derive(Debug, Clone)]
886pub struct PkResult {
887    /// Concentration at time t (mg/L)
888    pub concentration: f64,
889    /// Half-life (hours)
890    pub half_life_hr: f64,
891}
892
893/// Predicts drug concentration using a 1-compartment IV bolus model.
894pub fn one_compartment_pk_model(input: &PkOneCompartmentInput) -> PkResult {
895    let k_el = input.clearance_l_hr / input.volume_distribution_l;
896    let c0 = input.dose_mg / input.volume_distribution_l;
897    let concentration = c0 * (-k_el * input.time_hr).exp();
898    let half_life_hr = 0.693147 / k_el;
899
900    PkResult {
901        concentration,
902        half_life_hr,
903    }
904}
905
906// ─── SOFA Score (Sequential Organ Failure Assessment) ────────────────────────
907
908#[derive(Debug, Clone, Default)]
909pub struct SofaInput {
910    pub pao2_fio2_ratio: f64, // mmHg
911    pub platelets_10_9_l: f64,
912    pub bilirubin_mg_dl: f64,
913    pub map_mmhg: f64,            // Mean arterial pressure
914    pub dopamine_dose: f64,       // ug/kg/min
915    pub epinephrine_dose: f64,    // ug/kg/min
916    pub norepinephrine_dose: f64, // ug/kg/min
917    pub glasgow_coma_scale: u8,
918    pub creatinine_mg_dl: f64,
919    pub urine_output_ml_d: f64,
920}
921
922/// Evaluates acute sepsis morbidity via the SOFA score (0-24).
923pub fn sofa_score(input: &SofaInput) -> u8 {
924    let mut score = 0;
925
926    // Respiration
927    if input.pao2_fio2_ratio > 0.0 {
928        if input.pao2_fio2_ratio < 100.0 {
929            score += 4;
930        } else if input.pao2_fio2_ratio < 200.0 {
931            score += 3;
932        } else if input.pao2_fio2_ratio < 300.0 {
933            score += 2;
934        } else if input.pao2_fio2_ratio < 400.0 {
935            score += 1;
936        }
937    }
938
939    // Coagulation (Platelets)
940    if input.platelets_10_9_l > 0.0 {
941        if input.platelets_10_9_l < 20.0 {
942            score += 4;
943        } else if input.platelets_10_9_l < 50.0 {
944            score += 3;
945        } else if input.platelets_10_9_l < 100.0 {
946            score += 2;
947        } else if input.platelets_10_9_l < 150.0 {
948            score += 1;
949        }
950    }
951
952    // Liver (Bilirubin)
953    if input.bilirubin_mg_dl >= 12.0 {
954        score += 4;
955    } else if input.bilirubin_mg_dl >= 6.0 {
956        score += 3;
957    } else if input.bilirubin_mg_dl >= 2.0 {
958        score += 2;
959    } else if input.bilirubin_mg_dl >= 1.2 {
960        score += 1;
961    }
962
963    // Cardiovascular
964    if input.dopamine_dose > 15.0 || input.epinephrine_dose > 0.1 || input.norepinephrine_dose > 0.1
965    {
966        score += 4;
967    } else if input.dopamine_dose > 5.0
968        || (input.epinephrine_dose > 0.0 && input.epinephrine_dose <= 0.1)
969        || (input.norepinephrine_dose > 0.0 && input.norepinephrine_dose <= 0.1)
970    {
971        score += 3;
972    } else if input.dopamine_dose > 0.0 {
973        score += 2;
974    } else if input.map_mmhg > 0.0 && input.map_mmhg < 70.0 {
975        score += 1;
976    }
977
978    // Central Nervous System (GCS)
979    if input.glasgow_coma_scale > 0 {
980        if input.glasgow_coma_scale < 6 {
981            score += 4;
982        } else if input.glasgow_coma_scale <= 9 {
983            score += 3;
984        } else if input.glasgow_coma_scale <= 12 {
985            score += 2;
986        } else if input.glasgow_coma_scale <= 14 {
987            score += 1;
988        }
989    }
990
991    // Renal
992    if input.creatinine_mg_dl >= 5.0
993        || (input.urine_output_ml_d < 200.0 && input.urine_output_ml_d > 0.0)
994    {
995        score += 4;
996    } else if input.creatinine_mg_dl >= 3.5
997        || (input.urine_output_ml_d < 500.0 && input.urine_output_ml_d > 0.0)
998    {
999        score += 3;
1000    } else if input.creatinine_mg_dl >= 2.0 {
1001        score += 2;
1002    } else if input.creatinine_mg_dl >= 1.2 {
1003        score += 1;
1004    }
1005
1006    score
1007}
1008
1009// ─── Tests ────────────────────────────────────────────────────────────────────
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::*;
1014
1015    #[test]
1016    fn framingham_high_risk_male() {
1017        let r = framingham_10yr_risk(&FraminghamInput {
1018            age: 60,
1019            sex_male: true,
1020            total_cholesterol_mmol: 6.5,
1021            hdl_cholesterol_mmol: 0.9,
1022            systolic_bp: 162.0,
1023            bp_treated: false,
1024            current_smoker: true,
1025            diabetic: true,
1026        });
1027        assert!(r.risk_10yr > 0.20, "Expected >20% got {:.2}", r.risk_10yr);
1028        assert_eq!(r.category, RiskCategory::High);
1029    }
1030
1031    #[test]
1032    fn framingham_low_risk_female() {
1033        let r = framingham_10yr_risk(&FraminghamInput {
1034            age: 40,
1035            sex_male: false,
1036            total_cholesterol_mmol: 4.5,
1037            hdl_cholesterol_mmol: 1.8,
1038            systolic_bp: 115.0,
1039            bp_treated: false,
1040            current_smoker: false,
1041            diabetic: false,
1042        });
1043        assert!(r.risk_10yr < 0.10, "Expected <10% got {:.2}", r.risk_10yr);
1044        assert_eq!(r.category, RiskCategory::Low);
1045    }
1046
1047    #[test]
1048    fn cha2ds2_max_score() {
1049        let r = cha2ds2_vasc_score(&Cha2ds2VascInput {
1050            congestive_heart_failure: true,
1051            hypertension: true,
1052            age_75_or_older: true,
1053            diabetes: true,
1054            stroke_tia_history: true,
1055            vascular_disease: true,
1056            age_65_to_74: false,
1057            sex_female: true,
1058        });
1059        assert_eq!(r.score, 9);
1060        assert!(r.anticoagulation_recommended);
1061    }
1062
1063    #[test]
1064    fn cha2ds2_zero_male() {
1065        let r = cha2ds2_vasc_score(&Cha2ds2VascInput::default());
1066        assert_eq!(r.score, 0);
1067        assert!(!r.anticoagulation_recommended);
1068    }
1069
1070    #[test]
1071    fn drug_interaction_warfarin_ibuprofen() {
1072        let meds = vec![crate::q_hash("warfarin"), crate::q_hash("ibuprofen")];
1073        let found = check_drug_interactions(&meds);
1074        assert!(!found.is_empty());
1075        assert_eq!(found[0].severity, InteractionSeverity::Major);
1076    }
1077
1078    #[test]
1079    fn drug_interaction_no_false_positive() {
1080        let meds = vec![crate::q_hash("paracetamol"), crate::q_hash("lactulose")];
1081        let found = check_drug_interactions(&meds);
1082        assert!(found.is_empty());
1083    }
1084
1085    #[test]
1086    fn fhir_hba1c_normal() {
1087        let r = validate_fhir_observation(&FhirObservation {
1088            loinc_code: "4548-4".into(),
1089            value: 5.2,
1090            unit_ucum: "%".into(),
1091            reference_low: None,
1092            reference_high: None,
1093        });
1094        assert_eq!(r.status, ObservationStatus::Normal);
1095        assert_eq!(r.interpretation_code, "N");
1096    }
1097
1098    #[test]
1099    fn fhir_hba1c_high() {
1100        let r = validate_fhir_observation(&FhirObservation {
1101            loinc_code: "4548-4".into(),
1102            value: 8.5,
1103            unit_ucum: "%".into(),
1104            reference_low: None,
1105            reference_high: None,
1106        });
1107        assert_eq!(r.status, ObservationStatus::High);
1108        assert_eq!(r.interpretation_code, "H");
1109    }
1110
1111    #[test]
1112    fn trend_worsening_bp() {
1113        let series = vec![
1114            TimePoint {
1115                timestamp_s: 0,
1116                value: 120.0,
1117            },
1118            TimePoint {
1119                timestamp_s: 86400,
1120                value: 125.0,
1121            },
1122            TimePoint {
1123                timestamp_s: 172800,
1124                value: 130.0,
1125            },
1126            TimePoint {
1127                timestamp_s: 259200,
1128                value: 135.0,
1129            },
1130        ];
1131        let r = longitudinal_trend(&series, 7.0, -1);
1132        assert!(r.slope_per_day > 4.0);
1133        assert_eq!(r.direction, TrendDirection::Worsening);
1134        assert!(r.r_squared > 0.99);
1135    }
1136
1137    #[test]
1138    fn gene_expression_upregulated() {
1139        let r = evaluate_gene_expression(0xDEAD, 100.0, 350.0, 2.0);
1140        assert!(r.is_significant);
1141        assert_eq!(r.direction, ExpressionDirection::Upregulated);
1142        assert!((r.log2_fold_change - 1.807).abs() < 0.01);
1143    }
1144
1145    #[test]
1146    fn test_cockcroft_gault() {
1147        let input = RenalInput {
1148            age: 60,
1149            sex_male: true,
1150            weight_kg: 80.0,
1151            serum_creatinine: 1.2,
1152        };
1153        let crcl = cockcroft_gault_crcl(&input);
1154        assert!((crcl - 74.07).abs() < 0.1);
1155    }
1156
1157    #[test]
1158    fn test_ckd_epi() {
1159        let input = RenalInput {
1160            age: 60,
1161            sex_male: false,
1162            weight_kg: 70.0,
1163            serum_creatinine: 1.2,
1164        };
1165        let egfr = ckd_epi_egfr(&input);
1166        assert!((egfr - 51.5).abs() < 1.0);
1167    }
1168
1169    #[test]
1170    fn test_one_compartment_pk() {
1171        let input = PkOneCompartmentInput {
1172            dose_mg: 1000.0,
1173            volume_distribution_l: 50.0,
1174            clearance_l_hr: 5.0,
1175            time_hr: 10.0,
1176        };
1177        let pk = one_compartment_pk_model(&input);
1178        assert!((pk.concentration - 7.35).abs() < 0.1);
1179        assert!((pk.half_life_hr - 6.93).abs() < 0.1);
1180    }
1181
1182    #[test]
1183    fn test_sofa_score() {
1184        let input = SofaInput {
1185            pao2_fio2_ratio: 250.0, // 2 points
1186            platelets_10_9_l: 80.0, // 2 points
1187            bilirubin_mg_dl: 3.0,   // 2 points
1188            map_mmhg: 65.0,         // 1 point
1189            dopamine_dose: 0.0,
1190            epinephrine_dose: 0.0,
1191            norepinephrine_dose: 0.0,
1192            glasgow_coma_scale: 13, // 1 point
1193            creatinine_mg_dl: 2.5,  // 2 points
1194            urine_output_ml_d: 0.0,
1195        };
1196        let score = sofa_score(&input);
1197        assert_eq!(score, 10);
1198    }
1199}