Skip to main content

qualia_core_db/specialized_libs/medical_computing/
library.rs

1use super::*;
2
3/// Medical Computing Library Manager
4pub struct MedicalComputingLibrary {
5    patient_manager: PatientManager,
6    clinical_analyzer: ClinicalAnalyzer,
7    medical_imaging: MedicalImaging,
8    drug_discovery: DrugDiscovery,
9    compliance_monitor: MedicalComplianceMonitor,
10}
11impl MedicalComputingLibrary {
12    /// Create new medical computing library
13    pub fn new() -> Self {
14        Self {
15            patient_manager: PatientManager::new(),
16            clinical_analyzer: ClinicalAnalyzer::new(),
17            medical_imaging: MedicalImaging::new(),
18            drug_discovery: DrugDiscovery::new(),
19            compliance_monitor: MedicalComplianceMonitor::new(),
20        }
21    }
22
23    /// Initialize the library
24    pub fn initialize(&mut self) -> Result<(), MedicalError> {
25        // Initialize patient manager
26        self.patient_manager.initialize()?;
27
28        // Initialize clinical analyzer
29        self.clinical_analyzer.initialize()?;
30
31        // Initialize medical imaging
32        self.medical_imaging.initialize()?;
33
34        // Initialize drug discovery
35        self.drug_discovery.initialize()?;
36
37        // Initialize compliance monitor
38        self.compliance_monitor.initialize()?;
39
40        // Seed default patient for testing
41        let default_patient = Patient::new();
42        let _ = self.patient_manager.create_patient(default_patient);
43
44        Ok(())
45    }
46
47    /// Create a new patient record
48    pub fn create_patient_record(
49        &mut self,
50        patient: Patient,
51    ) -> Result<MedicalOperationResult<Patient>, MedicalError> {
52        let start_time = std::time::Instant::now();
53
54        // Validate patient data
55        self.patient_manager.validate_patient(&patient)?;
56
57        // Create patient record
58        let created_patient = self.patient_manager.create_patient(patient)?;
59
60        let execution_time = start_time.elapsed().as_millis() as u64;
61
62        Ok(MedicalOperationResult {
63            result: created_patient,
64            execution_time,
65            privacy_score: None,
66            compliance_status: ComplianceStatus::Compliant,
67            audit_trail: Vec::new(),
68        })
69    }
70
71    /// Analyze clinical data
72    pub fn analyze_clinical_data(
73        &mut self,
74        patient_id: &str,
75        data_type: ClinicalDataType,
76    ) -> Result<MedicalOperationResult<ClinicalAnalysis>, MedicalError> {
77        let start_time = std::time::Instant::now();
78
79        // Get patient data
80        let patient = self.patient_manager.get_patient(patient_id)?;
81
82        // Analyze clinical data
83        let analysis = self.clinical_analyzer.analyze_data(&patient, data_type)?;
84
85        let execution_time = start_time.elapsed().as_millis() as u64;
86
87        Ok(MedicalOperationResult {
88            result: analysis,
89            execution_time,
90            privacy_score: None,
91            compliance_status: ComplianceStatus::Compliant,
92            audit_trail: Vec::new(),
93        })
94    }
95
96    /// Real transparent Bayesian differential over a caller-supplied, non-authoritative
97    /// knowledge base. Returns a ranked epistemic proposal (never a diagnosis); the honest
98    /// label lives in `DifferentialProposal::epistemic_status`.
99    pub fn analyze_differential(
100        &mut self,
101        observed_findings: &[String],
102        knowledge_base: &DiagnosticKnowledgeBase,
103    ) -> Result<MedicalOperationResult<DifferentialProposal>, MedicalError> {
104        let start_time = std::time::Instant::now();
105        let proposal = self
106            .clinical_analyzer
107            .analyze_differential(observed_findings, knowledge_base)?;
108        let execution_time = start_time.elapsed().as_millis() as u64;
109        Ok(MedicalOperationResult {
110            result: proposal,
111            execution_time,
112            privacy_score: None,
113            compliance_status: ComplianceStatus::Compliant,
114            audit_trail: Vec::new(),
115        })
116    }
117
118    /// Real 2-D DSP over a caller-provided intensity grid (statistics, histogram,
119    /// window/level, threshold segmentation, Sobel edge magnitude). The result is
120    /// honestly labeled signal processing, never a diagnosis.
121    pub fn analyze_medical_image_grid(
122        &mut self,
123        data: &[f64],
124        width: usize,
125        height: usize,
126        bins: usize,
127        threshold: SegmentationThreshold,
128        window: Option<(f64, f64)>,
129    ) -> Result<MedicalOperationResult<ImageAnalysisResult>, MedicalError> {
130        let start_time = std::time::Instant::now();
131        let result = self
132            .medical_imaging
133            .analyze_grid(data, width, height, bins, threshold, window)?;
134        let execution_time = start_time.elapsed().as_millis() as u64;
135        Ok(MedicalOperationResult {
136            result,
137            execution_time,
138            privacy_score: None,
139            compliance_status: ComplianceStatus::Compliant,
140            audit_trail: Vec::new(),
141        })
142    }
143
144    /// Process medical image
145    pub fn process_medical_image(
146        &mut self,
147        image: MedicalImage,
148        processing_type: ImageProcessingType,
149    ) -> Result<MedicalOperationResult<ProcessedImage>, MedicalError> {
150        let start_time = std::time::Instant::now();
151
152        // Validate image
153        self.medical_imaging.validate_image(&image)?;
154
155        // Process image
156        let processed_image = self
157            .medical_imaging
158            .process_image(&image, processing_type)?;
159
160        let execution_time = start_time.elapsed().as_millis() as u64;
161
162        Ok(MedicalOperationResult {
163            result: processed_image,
164            execution_time,
165            privacy_score: None,
166            compliance_status: ComplianceStatus::Compliant,
167            audit_trail: Vec::new(),
168        })
169    }
170
171    /// Screen compounds by rule-based filtering + Tanimoto similarity ranking.
172    /// `query_smiles` is an optional reference structure for similarity ranking. The
173    /// result is honestly labeled (see `ScreeningProposal::epistemic_status`) — it is
174    /// NOT a binding-affinity or efficacy prediction.
175    #[cfg(any(
176        not(target_arch = "wasm32"),
177        feature = "portal",
178        feature = "wasm-logic",
179        feature = "wasm-scientific"
180    ))]
181    pub fn screen_compounds(
182        &mut self,
183        compounds: Vec<Compound>,
184        target: DrugTarget,
185        query_smiles: Option<&str>,
186    ) -> Result<MedicalOperationResult<ScreeningProposal>, MedicalError> {
187        let start_time = std::time::Instant::now();
188
189        // Validate compounds
190        self.drug_discovery.validate_compounds(&compounds)?;
191
192        // Screen compounds
193        let results = self
194            .drug_discovery
195            .screen_compounds(&compounds, &target, query_smiles)?;
196
197        let execution_time = start_time.elapsed().as_millis() as u64;
198
199        Ok(MedicalOperationResult {
200            result: results,
201            execution_time,
202            privacy_score: None,
203            compliance_status: ComplianceStatus::Compliant,
204            audit_trail: Vec::new(),
205        })
206    }
207
208    /// Check compliance
209    pub fn check_compliance(
210        &mut self,
211        compliance_type: ComplianceType,
212    ) -> Result<MedicalOperationResult<ComplianceReport>, MedicalError> {
213        let start_time = std::time::Instant::now();
214
215        // Check compliance
216        let report = self.compliance_monitor.check_compliance(compliance_type)?;
217
218        let execution_time = start_time.elapsed().as_millis() as u64;
219
220        Ok(MedicalOperationResult {
221            result: report,
222            execution_time,
223            privacy_score: None,
224            compliance_status: ComplianceStatus::Compliant,
225            audit_trail: Vec::new(),
226        })
227    }
228
229    /// Get performance statistics
230    pub fn get_performance_stats(&self) -> MedicalPerformanceMetrics {
231        self.patient_manager.get_performance_metrics()
232    }
233
234    /// List all patients
235    pub fn list_patients(&self) -> Vec<String> {
236        self.patient_manager.list_patients()
237    }
238
239    /// Get patient information
240    pub fn get_patient_info(&self, patient_id: &str) -> Option<Patient> {
241        self.patient_manager.get_patient(patient_id).ok()
242    }
243}