Skip to main content

qualia_core_db/specialized_libs/medical_computing/
diagnosis.rs

1use super::*;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4
5/// Clinical analyzer for medical data analysis
6pub struct ClinicalAnalyzer {
7    diagnostic_engine: DiagnosticEngine,
8    risk_assessment: ClinicalRiskAssessment,
9    treatment_planner: TreatmentPlanner,
10    outcome_predictor: OutcomePredictor,
11}
12
13/// Diagnostic engine
14pub struct DiagnosticEngine {
15    diagnostic_algorithms: HashMap<String, DiagnosticAlgorithm>,
16    symptom_analyzer: SymptomAnalyzer,
17    lab_interpreter: LabInterpreter,
18}
19
20/// Diagnostic algorithms
21#[derive(Debug, Clone)]
22pub struct DiagnosticAlgorithm {
23    pub algorithm_id: String,
24    pub algorithm_name: String,
25    pub algorithm_type: DiagnosticAlgorithmType,
26    pub accuracy: f64,
27}
28
29/// Diagnostic algorithm types
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub enum DiagnosticAlgorithmType {
32    RuleBased,
33    MachineLearning,
34    Bayesian,
35    NeuralNetwork,
36}
37
38/// Symptom analyzer
39pub struct SymptomAnalyzer {
40    symptom_patterns: HashMap<String, SymptomPattern>,
41    symptom_correlations: HashMap<String, SymptomCorrelation>,
42}
43
44/// Symptom patterns
45#[derive(Debug, Clone)]
46pub struct SymptomPattern {
47    pub pattern_id: String,
48    pub pattern_name: String,
49    pub symptoms: Vec<String>,
50    pub associated_conditions: Vec<String>,
51}
52
53/// Symptom correlations
54#[derive(Debug, Clone)]
55pub struct SymptomCorrelation {
56    pub correlation_id: String,
57    pub symptom1: String,
58    pub symptom2: String,
59    pub correlation_coefficient: f64,
60}
61
62/// Lab interpreter
63pub struct LabInterpreter {
64    reference_ranges: HashMap<String, ReferenceRange>,
65    abnormality_detector: AbnormalityDetector,
66}
67
68/// Abnormality detector
69#[derive(Debug, Clone)]
70pub struct AbnormalityDetector {
71    detection_algorithms: HashMap<String, DetectionAlgorithm>,
72    severity_assessment: SeverityAssessment,
73}
74
75/// Severity assessment
76#[derive(Debug, Clone)]
77pub struct SeverityAssessment {
78    assessment_criteria: HashMap<String, AssessmentCriterion>,
79    scoring_system: ScoringSystem,
80}
81
82/// Assessment criteria
83#[derive(Debug, Clone)]
84pub struct AssessmentCriterion {
85    pub criterion_id: String,
86    pub criterion_name: String,
87    pub weight: f64,
88    pub threshold: f64,
89}
90
91/// Scoring system
92#[derive(Debug, Clone)]
93pub struct ScoringSystem {
94    pub system_id: String,
95    pub system_name: String,
96    pub scoring_algorithm: ScoringAlgorithm,
97}
98
99/// Scoring algorithms
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub enum ScoringAlgorithm {
102    WeightedSum,
103    Bayesian,
104    FuzzyLogic,
105    NeuralNetwork,
106}
107
108/// Clinical risk assessment
109pub struct ClinicalRiskAssessment {
110    risk_models: HashMap<String, ClinicalRiskModel>,
111    risk_factors: HashMap<String, ClinicalRiskFactor>,
112}
113
114/// Clinical risk models
115#[derive(Debug, Clone)]
116pub struct ClinicalRiskModel {
117    pub model_id: String,
118    pub model_name: String,
119    pub model_type: ClinicalRiskModelType,
120    pub validation_results: ValidationResults,
121}
122
123/// Clinical risk model types
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub enum ClinicalRiskModelType {
126    Cardiovascular,
127    Cancer,
128    Diabetes,
129    Respiratory,
130    Custom(String),
131}
132
133/// Validation results
134#[derive(Debug, Clone)]
135pub struct ValidationResults {
136    pub accuracy: f64,
137    pub sensitivity: f64,
138    pub specificity: f64,
139    pub auc: f64,
140}
141
142/// Clinical risk factors
143#[derive(Debug, Clone)]
144pub struct ClinicalRiskFactor {
145    pub factor_id: String,
146    pub factor_name: String,
147    pub factor_category: FactorCategory,
148    pub factor_weight: f64,
149}
150
151/// Factor categories
152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
153pub enum FactorCategory {
154    Demographic,
155    Lifestyle,
156    Medical,
157    Genetic,
158    Environmental,
159}
160
161/// Treatment planner
162pub struct TreatmentPlanner {
163    treatment_guidelines: HashMap<String, TreatmentGuideline>,
164    decision_support: DecisionSupport,
165}
166
167/// Treatment guidelines
168#[derive(Debug, Clone)]
169pub struct TreatmentGuideline {
170    pub guideline_id: String,
171    pub guideline_name: String,
172    pub guideline_type: GuidelineType,
173    pub recommendations: Vec<TreatmentRecommendation>,
174}
175
176/// Guideline types
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
178pub enum GuidelineType {
179    Clinical,
180    Protocol,
181    StandardOfCare,
182    BestPractice,
183}
184
185/// Treatment recommendations
186#[derive(Debug, Clone)]
187pub struct TreatmentRecommendation {
188    pub recommendation_id: String,
189    pub condition: String,
190    pub treatment: String,
191    pub evidence_level: EvidenceLevel,
192    pub strength: RecommendationStrength,
193}
194
195/// Evidence levels
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
197pub enum EvidenceLevel {
198    LevelA,
199    LevelB,
200    LevelC,
201    ExpertOpinion,
202}
203
204/// Recommendation strength
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
206pub enum RecommendationStrength {
207    Strong,
208    Moderate,
209    Weak,
210    ExpertConsensus,
211}
212
213/// Decision support
214pub struct DecisionSupport {
215    decision_trees: HashMap<String, DecisionTree>,
216    scoring_systems: HashMap<String, ScoringSystem>,
217}
218
219/// Decision trees
220#[derive(Debug, Clone)]
221pub struct DecisionTree {
222    pub tree_id: String,
223    pub tree_name: String,
224    pub root_node: DecisionNode,
225}
226
227/// Decision nodes
228#[derive(Debug, Clone)]
229pub struct DecisionNode {
230    pub node_id: String,
231    pub node_type: NodeType,
232    pub condition: Option<String>,
233    pub threshold: Option<f64>,
234    pub children: Vec<DecisionNode>,
235    pub outcome: Option<String>,
236}
237
238/// Node types
239#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
240pub enum NodeType {
241    Root,
242    Decision,
243    Leaf,
244}
245
246/// Outcome predictor
247pub struct OutcomePredictor {
248    prediction_models: HashMap<String, PredictionModel>,
249    outcome_metrics: HashMap<String, OutcomeMetric>,
250}
251
252/// Prediction models
253#[derive(Debug, Clone)]
254pub struct PredictionModel {
255    pub model_id: String,
256    pub model_name: String,
257    pub model_type: PredictionModelType,
258    pub performance_metrics: ModelPerformanceMetrics,
259}
260
261/// Prediction model types
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263pub enum PredictionModelType {
264    Survival,
265    Response,
266    Recurrence,
267    Complication,
268}
269
270/// Model performance metrics
271#[derive(Debug, Clone)]
272pub struct ModelPerformanceMetrics {
273    pub accuracy: f64,
274    pub precision: f64,
275    pub recall: f64,
276    pub f1_score: f64,
277}
278
279/// Outcome metrics
280#[derive(Debug, Clone)]
281pub struct OutcomeMetric {
282    pub metric_id: String,
283    pub metric_name: String,
284    pub metric_type: OutcomeMetricType,
285    pub measurement_method: MeasurementMethod,
286}
287
288/// Outcome metric types
289#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
290pub enum OutcomeMetricType {
291    Mortality,
292    Morbidity,
293    QualityOfLife,
294    FunctionalStatus,
295}
296
297/// Measurement methods
298#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
299pub enum MeasurementMethod {
300    Scale,
301    Binary,
302    Continuous,
303    Categorical,
304}
305impl ClinicalAnalyzer {
306    /// Create a `ClinicalAnalyzer` with default sub-components.
307    pub fn new() -> Self {
308        Self {
309            diagnostic_engine: DiagnosticEngine::new(),
310            risk_assessment: ClinicalRiskAssessment::new(),
311            treatment_planner: TreatmentPlanner::new(),
312            outcome_predictor: OutcomePredictor::new(),
313        }
314    }
315
316    /// Initialise the `ClinicalAnalyzer` sub-components; propagates the domain error.
317    pub fn initialize(&mut self) -> Result<(), MedicalError> {
318        self.diagnostic_engine.initialize()?;
319        self.risk_assessment.initialize()?;
320        self.treatment_planner.initialize()?;
321        self.outcome_predictor.initialize()?;
322        Ok(())
323    }
324
325    /// Patient-only convenience entry point. The real differential engine
326    /// ([`Self::analyze_differential`]) requires a CALLER-SUPPLIED knowledge base
327    /// (priors + per-finding likelihoods); this overload is handed no such KB, so it
328    /// fails closed with `InsufficientData` rather than fabricating a diagnosis or a
329    /// confidence. Supply findings + a knowledge base via `analyze_differential` to get
330    /// a real, ranked, honestly-labeled proposal.
331    pub fn analyze_data(
332        &mut self,
333        _patient: &Patient,
334        _data_type: ClinicalDataType,
335    ) -> Result<ClinicalAnalysis, MedicalError> {
336        Err(MedicalError::InsufficientData(
337            "clinical diagnostic analysis (analyze_clinical_data): no knowledge base was \
338             supplied through the patient-only path. Use analyze_differential(findings, \
339             knowledge_base) with a caller-supplied, non-authoritative KB to obtain a ranked \
340             epistemic proposal. Refusing to emit a fabricated diagnosis or confidence."
341                .to_string(),
342        ))
343    }
344
345    /// Real transparent Bayesian differential over a **caller-supplied, non-authoritative**
346    /// knowledge base. Delegates to [`super::analyze_differential`]. Returns a ranked
347    /// epistemic proposal (never a diagnosis); the honest label lives in
348    /// `DifferentialProposal::epistemic_status`.
349    pub fn analyze_differential(
350        &self,
351        observed_findings: &[String],
352        kb: &super::DiagnosticKnowledgeBase,
353    ) -> Result<super::DifferentialProposal, MedicalError> {
354        super::analyze_differential(observed_findings, kb)
355    }
356}
357
358impl DiagnosticEngine {
359    /// Create a `DiagnosticEngine` with default sub-components.
360    pub fn new() -> Self {
361        Self {
362            diagnostic_algorithms: HashMap::new(),
363            symptom_analyzer: SymptomAnalyzer::new(),
364            lab_interpreter: LabInterpreter::new(),
365        }
366    }
367
368    /// Initialise the `DiagnosticEngine` sub-components; propagates the domain error.
369    pub fn initialize(&mut self) -> Result<(), MedicalError> {
370        Ok(())
371    }
372
373    /// Register `diagnostic_algorithm` in the `DiagnosticEngine` collection.
374    pub fn add_diagnostic_algorithm(&mut self, algorithm: DiagnosticAlgorithm) {
375        self.diagnostic_algorithms
376            .insert(algorithm.algorithm_id.clone(), algorithm);
377    }
378
379    /// Borrow `diagnostic_algorithm` by id, or `None` when absent.
380    pub fn get_diagnostic_algorithm(&self, algorithm_id: &str) -> Option<&DiagnosticAlgorithm> {
381        self.diagnostic_algorithms.get(algorithm_id)
382    }
383
384    /// Borrow the `symptom_analyzer` component.
385    pub fn symptom_analyzer(&self) -> &SymptomAnalyzer {
386        &self.symptom_analyzer
387    }
388
389    /// Borrow the `lab_interpreter` component.
390    pub fn lab_interpreter(&self) -> &LabInterpreter {
391        &self.lab_interpreter
392    }
393}
394
395impl SymptomAnalyzer {
396    /// Create a `SymptomAnalyzer` with default sub-components.
397    pub fn new() -> Self {
398        Self {
399            symptom_patterns: HashMap::new(),
400            symptom_correlations: HashMap::new(),
401        }
402    }
403
404    /// Register `symptom_pattern` in the `SymptomAnalyzer` collection.
405    pub fn add_symptom_pattern(&mut self, pattern: SymptomPattern) {
406        self.symptom_patterns
407            .insert(pattern.pattern_id.clone(), pattern);
408    }
409
410    /// Borrow `symptom_pattern` by id, or `None` when absent.
411    pub fn get_symptom_pattern(&self, pattern_id: &str) -> Option<&SymptomPattern> {
412        self.symptom_patterns.get(pattern_id)
413    }
414
415    /// Register `symptom_correlation` in the `SymptomAnalyzer` collection.
416    pub fn add_symptom_correlation(&mut self, correlation: SymptomCorrelation) {
417        self.symptom_correlations
418            .insert(correlation.correlation_id.clone(), correlation);
419    }
420
421    /// Borrow `symptom_correlation` by id, or `None` when absent.
422    pub fn get_symptom_correlation(&self, correlation_id: &str) -> Option<&SymptomCorrelation> {
423        self.symptom_correlations.get(correlation_id)
424    }
425}
426
427impl LabInterpreter {
428    /// Create a `LabInterpreter` with default sub-components.
429    pub fn new() -> Self {
430        Self {
431            reference_ranges: HashMap::new(),
432            abnormality_detector: AbnormalityDetector::new(),
433        }
434    }
435
436    /// Register `reference_range` in the `LabInterpreter` collection.
437    pub fn add_reference_range(&mut self, test_code: &str, range: ReferenceRange) {
438        self.reference_ranges.insert(test_code.to_string(), range);
439    }
440
441    /// Borrow `reference_range` by id, or `None` when absent.
442    pub fn get_reference_range(&self, test_code: &str) -> Option<&ReferenceRange> {
443        self.reference_ranges.get(test_code)
444    }
445
446    /// Borrow the `abnormality_detector` component.
447    pub fn abnormality_detector(&self) -> &AbnormalityDetector {
448        &self.abnormality_detector
449    }
450
451    /// Interpret `result` against the reference ranges; returns a `ResultStatus`.
452    pub fn interpret_result(&self, result: &LabResult) -> ResultStatus {
453        if let Some(range) = self.reference_ranges.get(&result.test_code) {
454            if result.value < range.minimum || result.value > range.maximum {
455                ResultStatus::Abnormal
456            } else {
457                ResultStatus::Normal
458            }
459        } else {
460            result.status.clone()
461        }
462    }
463}
464
465impl AbnormalityDetector {
466    /// Create a `AbnormalityDetector` with default sub-components.
467    pub fn new() -> Self {
468        Self {
469            detection_algorithms: HashMap::new(),
470            severity_assessment: SeverityAssessment::new(),
471        }
472    }
473
474    /// Register `detection_algorithm` in the `AbnormalityDetector` collection.
475    pub fn add_detection_algorithm(&mut self, algorithm: DetectionAlgorithm) {
476        self.detection_algorithms
477            .insert(algorithm.algorithm_id.clone(), algorithm);
478    }
479
480    /// Borrow `detection_algorithm` by id, or `None` when absent.
481    pub fn get_detection_algorithm(&self, algorithm_id: &str) -> Option<&DetectionAlgorithm> {
482        self.detection_algorithms.get(algorithm_id)
483    }
484
485    /// Borrow the `severity_assessment` component.
486    pub fn severity_assessment(&self) -> &SeverityAssessment {
487        &self.severity_assessment
488    }
489}
490
491impl SeverityAssessment {
492    /// Create a `SeverityAssessment` with default sub-components.
493    pub fn new() -> Self {
494        Self {
495            assessment_criteria: HashMap::new(),
496            scoring_system: ScoringSystem::new(),
497        }
498    }
499
500    /// Register `criterion` in the `SeverityAssessment` collection.
501    pub fn add_criterion(&mut self, criterion: AssessmentCriterion) {
502        self.assessment_criteria
503            .insert(criterion.criterion_id.clone(), criterion);
504    }
505
506    /// Borrow `criterion` by id, or `None` when absent.
507    pub fn get_criterion(&self, criterion_id: &str) -> Option<&AssessmentCriterion> {
508        self.assessment_criteria.get(criterion_id)
509    }
510
511    /// Borrow the `scoring_system` component.
512    pub fn scoring_system(&self) -> &ScoringSystem {
513        &self.scoring_system
514    }
515}
516
517impl ScoringSystem {
518    /// Create a `ScoringSystem` with default sub-components.
519    pub fn new() -> Self {
520        Self {
521            system_id: "system_1".to_string(),
522            system_name: "Clinical Scoring System".to_string(),
523            scoring_algorithm: ScoringAlgorithm::WeightedSum,
524        }
525    }
526}
527
528impl ClinicalRiskAssessment {
529    /// Create a `ClinicalRiskAssessment` with default sub-components.
530    pub fn new() -> Self {
531        Self {
532            risk_models: HashMap::new(),
533            risk_factors: HashMap::new(),
534        }
535    }
536
537    /// Initialise the `ClinicalRiskAssessment` sub-components; propagates the domain error.
538    pub fn initialize(&mut self) -> Result<(), MedicalError> {
539        Ok(())
540    }
541
542    /// Register `risk_model` in the `ClinicalRiskAssessment` collection.
543    pub fn add_risk_model(&mut self, model: ClinicalRiskModel) {
544        self.risk_models.insert(model.model_id.clone(), model);
545    }
546
547    /// Borrow `risk_model` by id, or `None` when absent.
548    pub fn get_risk_model(&self, model_id: &str) -> Option<&ClinicalRiskModel> {
549        self.risk_models.get(model_id)
550    }
551
552    /// Register `risk_factor` in the `ClinicalRiskAssessment` collection.
553    pub fn add_risk_factor(&mut self, factor: ClinicalRiskFactor) {
554        self.risk_factors.insert(factor.factor_id.clone(), factor);
555    }
556
557    /// Borrow `risk_factor` by id, or `None` when absent.
558    pub fn get_risk_factor(&self, factor_id: &str) -> Option<&ClinicalRiskFactor> {
559        self.risk_factors.get(factor_id)
560    }
561
562    /// Borrow the `compute_risk_score` component.
563    pub fn compute_risk_score(&self, factor_ids: &[String]) -> f64 {
564        if factor_ids.is_empty() {
565            return 0.0;
566        }
567        let total_weight: f64 = factor_ids
568            .iter()
569            .filter_map(|id| self.risk_factors.get(id))
570            .map(|f| f.factor_weight)
571            .sum();
572        total_weight / factor_ids.len() as f64
573    }
574}
575
576impl TreatmentPlanner {
577    /// Create a `TreatmentPlanner` with default sub-components.
578    pub fn new() -> Self {
579        Self {
580            treatment_guidelines: HashMap::new(),
581            decision_support: DecisionSupport::new(),
582        }
583    }
584
585    /// Initialise the `TreatmentPlanner` sub-components; propagates the domain error.
586    pub fn initialize(&mut self) -> Result<(), MedicalError> {
587        Ok(())
588    }
589
590    /// Register `treatment_guideline` in the `TreatmentPlanner` collection.
591    pub fn add_treatment_guideline(&mut self, guideline: TreatmentGuideline) {
592        self.treatment_guidelines
593            .insert(guideline.guideline_id.clone(), guideline);
594    }
595
596    /// Borrow `treatment_guideline` by id, or `None` when absent.
597    pub fn get_treatment_guideline(&self, guideline_id: &str) -> Option<&TreatmentGuideline> {
598        self.treatment_guidelines.get(guideline_id)
599    }
600
601    /// Borrow the `decision_support` component.
602    pub fn decision_support(&self) -> &DecisionSupport {
603        &self.decision_support
604    }
605}
606
607impl DecisionSupport {
608    /// Create a `DecisionSupport` with default sub-components.
609    pub fn new() -> Self {
610        Self {
611            decision_trees: HashMap::new(),
612            scoring_systems: HashMap::new(),
613        }
614    }
615
616    /// Register `decision_tree` in the `DecisionSupport` collection.
617    pub fn add_decision_tree(&mut self, tree: DecisionTree) {
618        self.decision_trees.insert(tree.tree_id.clone(), tree);
619    }
620
621    /// Borrow `decision_tree` by id, or `None` when absent.
622    pub fn get_decision_tree(&self, tree_id: &str) -> Option<&DecisionTree> {
623        self.decision_trees.get(tree_id)
624    }
625
626    /// Register `scoring_system` in the `DecisionSupport` collection.
627    pub fn add_scoring_system(&mut self, system: ScoringSystem) {
628        self.scoring_systems
629            .insert(system.system_id.clone(), system);
630    }
631
632    /// Borrow `scoring_system` by id, or `None` when absent.
633    pub fn get_scoring_system(&self, system_id: &str) -> Option<&ScoringSystem> {
634        self.scoring_systems.get(system_id)
635    }
636}
637
638impl OutcomePredictor {
639    /// Create a `OutcomePredictor` with default sub-components.
640    pub fn new() -> Self {
641        Self {
642            prediction_models: HashMap::new(),
643            outcome_metrics: HashMap::new(),
644        }
645    }
646
647    /// Initialise the `OutcomePredictor` sub-components; propagates the domain error.
648    pub fn initialize(&mut self) -> Result<(), MedicalError> {
649        Ok(())
650    }
651
652    /// Register `prediction_model` in the `OutcomePredictor` collection.
653    pub fn add_prediction_model(&mut self, model_id: &str, model: PredictionModel) {
654        self.prediction_models.insert(model_id.to_string(), model);
655    }
656
657    /// Borrow `prediction_model` by id, or `None` when absent.
658    pub fn get_prediction_model(&self, model_id: &str) -> Option<&PredictionModel> {
659        self.prediction_models.get(model_id)
660    }
661
662    /// Register `outcome_metric` in the `OutcomePredictor` collection.
663    pub fn add_outcome_metric(&mut self, metric_id: &str, value: OutcomeMetric) {
664        self.outcome_metrics.insert(metric_id.to_string(), value);
665    }
666
667    /// Borrow `outcome_metric` by id, or `None` when absent.
668    pub fn get_outcome_metric(&self, metric_id: &str) -> Option<&OutcomeMetric> {
669        self.outcome_metrics.get(metric_id)
670    }
671}