Skip to main content

qualia_core_db/medical/
comorbidity_eval.rs

1//! Defeasible comorbidity evaluation for the Core 1 Prolog Sentinel.
2//!
3//! Traverses nested RDF-Star Quins (subject bit 63) and compounding `q42:exacerbates`
4//! edges without heap allocation. Contradictory diagnoses route through paraconsistent
5//! isolation rather than halting evaluation.
6
7use crate::modalities::paraconsistent::route_paraconsistent;
8use crate::q_hash;
9use crate::NQuin;
10
11pub const MAX_CONDITION_SLOTS: usize = 32;
12pub const MAX_COMORBIDITY_VERDICTS: usize = 64;
13pub const NESTED_SUBJECT_MASK: u64 = 1u64 << 63;
14pub const NESTED_PAYLOAD_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
15
16pub const PRED_EXACERBATES: u64 = q_hash("q42:exacerbates");
17pub const PRED_HAS_CONDITION: u64 = q_hash("q42:hasCondition");
18pub const PRED_HAS_SEVERITY: u64 = q_hash("q42:hasSeverity");
19
20const INLINE_TAG_DECIMAL: u64 = 0b010u64 << 60;
21const INLINE_TAG_MASK: u64 = 0b111u64 << 60;
22const INLINE_VALUE_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
23
24#[repr(u8)]
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ComorbidityStatus {
27    Active = 0,
28    Isolated = 1,
29    Defeated = 2,
30}
31
32#[repr(C, align(8))]
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct ComorbidityVerdict {
35    pub condition_hash: u64,
36    pub compounded_risk_milli: u32,
37    pub status: ComorbidityStatus,
38    pub _pad: [u8; 3],
39}
40
41#[derive(Debug, PartialEq, Eq)]
42pub enum ComorbidityError {
43    OutputBufferFull,
44}
45
46/// Fingerprint for a nested RDF-Star claim: `<< ante pred cons >>`.
47#[inline]
48pub fn nested_claim_fingerprint(ante: u64, pred: u64, cons: u64) -> u64 {
49    let body = (ante ^ pred ^ cons) & NESTED_PAYLOAD_MASK;
50    body | NESTED_SUBJECT_MASK
51}
52
53#[inline]
54/// `true` when nested-subject.
55pub fn is_nested_subject(subject: u64) -> bool {
56    (subject & NESTED_SUBJECT_MASK) != 0
57}
58
59#[inline]
60fn decode_severity_milli(object: u64) -> u32 {
61    if (object & INLINE_TAG_MASK) == INLINE_TAG_DECIMAL {
62        let scaled = (object & INLINE_VALUE_MASK) as u32;
63        // Object stores severity × 10⁶; map to 0–1000 milli scale.
64        ((scaled as u64 * 1000) / 1_000_000).min(1000) as u32
65    } else {
66        500
67    }
68}
69
70#[inline]
71fn encode_severity_object(severity: f32) -> u64 {
72    let clamped = severity.clamp(0.0, 1.0);
73    let scaled = (clamped * 1_000_000.0).round() as u64;
74    (scaled & INLINE_VALUE_MASK) | INLINE_TAG_DECIMAL
75}
76
77/// Compile a nested exacerbation Quin pair (relationship + severity).
78pub fn compile_exacerbation_quins(
79    ante_condition: u64,
80    cons_condition: u64,
81    patient_context: u64,
82    severity: f32,
83    out: &mut [NQuin; 2],
84) -> usize {
85    let nested = nested_claim_fingerprint(ante_condition, PRED_EXACERBATES, cons_condition);
86
87    let mut edge = NQuin::default();
88    edge.subject = ante_condition;
89    edge.predicate = PRED_EXACERBATES;
90    edge.object = cons_condition;
91    edge.context = patient_context;
92    edge.parity = edge.subject ^ edge.predicate ^ edge.object ^ edge.context;
93    out[0] = edge;
94
95    let mut severity_quin = NQuin::default();
96    severity_quin.subject = nested;
97    severity_quin.predicate = PRED_HAS_SEVERITY;
98    severity_quin.object = encode_severity_object(severity);
99    severity_quin.context = patient_context;
100    severity_quin.parity = severity_quin.subject
101        ^ severity_quin.predicate
102        ^ severity_quin.object
103        ^ severity_quin.context;
104    out[1] = severity_quin;
105
106    2
107}
108
109/// Returns `true` when `condition_hash` plausibly intersects the target organ hash.
110#[inline]
111fn condition_intersects_organ(condition_hash: u64, target_organ_hash: u64) -> bool {
112    if target_organ_hash == 0 {
113        return true;
114    }
115    if condition_hash == target_organ_hash {
116        return true;
117    }
118    // Lightweight organ–system intersection via hashed clinical tokens.
119    let cardio = q_hash("Heart");
120    let diabetes = q_hash("Type 2 Diabetes Mellitus");
121    let neuropathy = q_hash("Diabetic Neuropathy");
122    let hypertension = q_hash("Hypertension");
123
124    if target_organ_hash == cardio {
125        return matches!(
126            condition_hash,
127            x if x == diabetes || x == hypertension || x == cardio || x == neuropathy
128        );
129    }
130
131    condition_hash == target_organ_hash
132}
133
134/// Core 1 evaluator — zero heap allocation; caller supplies output buffers.
135pub fn eval_comorbidity(
136    patient_did_hash: u64,
137    target_organ_hash: u64,
138    quins: &[NQuin],
139    out: &mut [ComorbidityVerdict],
140) -> Result<usize, ComorbidityError> {
141    let mut consistent_buf = [NQuin::default(); 128];
142    let mut isolated_buf = [NQuin::default(); 32];
143    let (consistent_count, isolated_count) =
144        route_paraconsistent(quins, &mut consistent_buf, &mut isolated_buf)
145            .map_err(|_| ComorbidityError::OutputBufferFull)?;
146    let graph = &consistent_buf[..consistent_count];
147
148    let mut conditions = [0u64; MAX_CONDITION_SLOTS];
149    let mut condition_count = 0usize;
150    let mut severities = [(0u64, 0u32); MAX_CONDITION_SLOTS];
151    let mut severity_count = 0usize;
152
153    for quin in graph {
154        if quin.context != patient_did_hash && quin.subject != patient_did_hash {
155            continue;
156        }
157
158        if quin.predicate == PRED_HAS_CONDITION && quin.subject == patient_did_hash {
159            if condition_count < MAX_CONDITION_SLOTS {
160                conditions[condition_count] = quin.object;
161                condition_count += 1;
162            }
163        }
164
165        if is_nested_subject(quin.subject) && quin.predicate == PRED_HAS_SEVERITY {
166            if severity_count < MAX_CONDITION_SLOTS {
167                severities[severity_count] = (quin.subject, decode_severity_milli(quin.object));
168                severity_count += 1;
169            }
170        }
171    }
172
173    let mut emitted = 0usize;
174
175    for i in 0..condition_count {
176        let condition = conditions[i];
177        if !condition_intersects_organ(condition, target_organ_hash) {
178            continue;
179        }
180
181        let mut risk_milli: u32 = 400;
182
183        for quin in graph {
184            if quin.predicate != PRED_EXACERBATES || quin.context != patient_did_hash {
185                continue;
186            }
187            if quin.subject != condition && quin.object != condition {
188                continue;
189            }
190            let nested_fp = nested_claim_fingerprint(quin.subject, quin.predicate, quin.object);
191            let mut matched_severity = 0u32;
192            for j in 0..severity_count {
193                if severities[j].0 == nested_fp {
194                    matched_severity = severities[j].1;
195                    break;
196                }
197            }
198            if matched_severity > 0 {
199                risk_milli = risk_milli.saturating_add(matched_severity / 2);
200                risk_milli = ((risk_milli as u64 * 14) / 10).min(1000) as u32;
201            } else {
202                risk_milli = ((risk_milli as u64 * 12) / 10).min(1000) as u32;
203            }
204        }
205
206        if emitted >= out.len() {
207            return Err(ComorbidityError::OutputBufferFull);
208        }
209
210        out[emitted] = ComorbidityVerdict {
211            condition_hash: condition,
212            compounded_risk_milli: risk_milli.min(1000),
213            status: ComorbidityStatus::Active,
214            _pad: [0; 3],
215        };
216        emitted += 1;
217    }
218
219    for quin in &isolated_buf[..isolated_count] {
220        if quin.subject != patient_did_hash && quin.context != patient_did_hash {
221            continue;
222        }
223        if emitted >= out.len() {
224            return Err(ComorbidityError::OutputBufferFull);
225        }
226        out[emitted] = ComorbidityVerdict {
227            condition_hash: quin.object,
228            compounded_risk_milli: 0,
229            status: ComorbidityStatus::Isolated,
230            _pad: [0; 3],
231        };
232        emitted += 1;
233    }
234
235    Ok(emitted)
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    fn patient_ctx() -> u64 {
243        q_hash("did:patient:comorb-test")
244    }
245
246    fn compile_demo_graph(patient: u64, out: &mut [NQuin; 16]) -> usize {
247        let diabetes = q_hash("Type 2 Diabetes Mellitus");
248        let neuropathy = q_hash("Diabetic Neuropathy");
249        let heart = q_hash("Heart");
250
251        let mut idx = 0usize;
252
253        let mut has_diabetes = NQuin::default();
254        has_diabetes.subject = patient;
255        has_diabetes.predicate = PRED_HAS_CONDITION;
256        has_diabetes.object = diabetes;
257        has_diabetes.context = patient;
258        has_diabetes.parity = has_diabetes.subject
259            ^ has_diabetes.predicate
260            ^ has_diabetes.object
261            ^ has_diabetes.context;
262        out[idx] = has_diabetes;
263        idx += 1;
264
265        let mut has_neuropathy = NQuin::default();
266        has_neuropathy.subject = patient;
267        has_neuropathy.predicate = PRED_HAS_CONDITION;
268        has_neuropathy.object = neuropathy;
269        has_neuropathy.context = patient;
270        has_neuropathy.parity = has_neuropathy.subject
271            ^ has_neuropathy.predicate
272            ^ has_neuropathy.object
273            ^ has_neuropathy.context;
274        out[idx] = has_neuropathy;
275        idx += 1;
276
277        let mut pair = [NQuin::default(); 2];
278        let wrote = compile_exacerbation_quins(diabetes, neuropathy, patient, 0.85, &mut pair);
279        out[idx..idx + wrote].copy_from_slice(&pair[..wrote]);
280        idx += wrote;
281
282        let mut cardio = NQuin::default();
283        cardio.subject = patient;
284        cardio.predicate = PRED_HAS_CONDITION;
285        cardio.object = heart;
286        cardio.context = patient;
287        cardio.parity = cardio.subject ^ cardio.predicate ^ cardio.object ^ cardio.context;
288        out[idx] = cardio;
289        idx += 1;
290
291        idx
292    }
293
294    #[test]
295    fn nested_fingerprint_sets_msb() {
296        let fp = nested_claim_fingerprint(1, 2, 3);
297        assert!(is_nested_subject(fp));
298    }
299
300    #[test]
301    fn eval_finds_compounded_diabetes_neuropathy_risk() {
302        let patient = patient_ctx();
303        let mut graph = [NQuin::default(); 16];
304        let n = compile_demo_graph(patient, &mut graph);
305
306        let mut verdicts = [ComorbidityVerdict {
307            condition_hash: 0,
308            compounded_risk_milli: 0,
309            status: ComorbidityStatus::Defeated,
310            _pad: [0; 3],
311        }; 8];
312
313        let count = eval_comorbidity(patient, q_hash("Heart"), &graph[..n], &mut verdicts).unwrap();
314        assert!(count >= 2);
315        assert!(verdicts[0].compounded_risk_milli > 400);
316    }
317
318    #[test]
319    fn zero_heap_eval_comorbidity() {
320        let patient = patient_ctx();
321        let mut graph = [NQuin::default(); 16];
322        let n = compile_demo_graph(patient, &mut graph);
323
324        let _profiler = dhat::Profiler::builder().testing().build();
325        let mut verdicts = [ComorbidityVerdict {
326            condition_hash: 0,
327            compounded_risk_milli: 0,
328            status: ComorbidityStatus::Active,
329            _pad: [0; 3],
330        }; MAX_COMORBIDITY_VERDICTS];
331
332        let result = eval_comorbidity(patient, q_hash("Heart"), &graph[..n], &mut verdicts);
333        assert!(result.is_ok());
334
335        let stats = dhat::HeapStats::get();
336        assert_eq!(
337            stats.curr_blocks, 0,
338            "eval_comorbidity must not allocate on the heap"
339        );
340        assert_eq!(stats.curr_bytes, 0);
341    }
342}