1use super::*;
2
3pub struct PropertyPredictor {
5 property_models: HashMap<String, PropertyModel>,
6 descriptor_calculator: DescriptorCalculator,
7 machine_learning_models: HashMap<String, MLModel>,
8}
9
10#[derive(Debug, Clone)]
12pub struct PropertyModel {
13 pub model_id: String,
14 pub property_type: PropertyType,
15 pub model_type: PropertyModelType,
16 pub parameters: PropertyModelParameters,
17}
18
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub enum PropertyType {
22 BoilingPoint,
23 MeltingPoint,
24 Density,
25 Viscosity,
26 SurfaceTension,
27 HeatCapacity,
28 ThermalConductivity,
29 ElectricalConductivity,
30 OpticalProperties,
31 MagneticProperties,
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub enum PropertyModelType {
37 GroupContribution,
38 QSPR,
39 MachineLearning,
40 MolecularDynamics,
41 QuantumMechanical,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct PropertyModelParameters {
47 pub coefficients: HashMap<String, f64>,
48 pub descriptors: Vec<String>,
49 pub reference_data: Vec<ReferenceData>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ReferenceData {
55 pub molecule_id: String,
56 pub property_value: f64,
57 pub conditions: ReferenceConditions,
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct ReferenceConditions {
63 pub temperature: f64,
64 pub pressure: f64,
65 pub phase: PhaseType,
66}
67
68pub struct DescriptorCalculator {
70 molecular_descriptors: MolecularDescriptors,
71 quantum_descriptors: QuantumDescriptors,
72 topological_descriptors: TopologicalDescriptors,
73}
74
75#[derive(Debug, Clone)]
77pub struct MolecularDescriptors {
78 pub molecular_weight: f64,
79 pub formula: String,
80 pub atom_count: HashMap<String, usize>,
81 pub bond_count: HashMap<String, usize>,
82 pub ring_count: usize,
83}
84
85#[derive(Debug, Clone)]
87pub struct QuantumDescriptors {
88 pub homo_energy: f64,
89 pub lumo_energy: f64,
90 pub gap: f64,
91 pub dipole_moment: f64,
92 pub polarizability: f64,
93}
94
95#[derive(Debug, Clone)]
97pub struct TopologicalDescriptors {
98 pub connectivity_index: f64,
99 pub shape_index: f64,
100 pub wiener_index: f64,
101 pub randic_index: f64,
102}
103
104#[derive(Debug, Clone)]
106pub struct MLModel {
107 pub model_id: String,
108 pub model_type: MLModelType,
109 pub model_parameters: MLModelParameters,
110 pub training_data: TrainingData,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub enum MLModelType {
116 LinearRegression,
117 RandomForest,
118 NeuralNetwork,
119 SupportVector,
120 GaussianProcess,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct MLModelParameters {
126 pub hyperparameters: HashMap<String, f64>,
127 pub feature_importance: HashMap<String, f64>,
128 pub model_performance: ModelPerformance,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct ModelPerformance {
134 pub r_squared: f64,
135 pub rmse: f64,
136 pub mae: f64,
137 pub cross_validation_score: f64,
138}
139
140#[derive(Debug, Clone)]
142pub struct TrainingData {
143 pub data_id: String,
144 pub features: Vec<Vec<f64>>,
145 pub targets: Vec<f64>,
146 pub data_size: usize,
147}
148
149impl PropertyPredictor {
150 pub fn new() -> Self {
152 Self {
153 property_models: HashMap::new(),
154 descriptor_calculator: DescriptorCalculator::new(),
155 machine_learning_models: HashMap::new(),
156 }
157 }
158
159 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
161 self.descriptor_calculator.initialize()?;
162 self.register_standard_qspr_models();
168 Ok(())
169 }
170
171 fn register_standard_qspr_models(&mut self) {
173 self.register_model(
176 "boiling_point",
177 PropertyModel {
178 model_id: "qspr_boiling_point".to_string(),
179 property_type: PropertyType::BoilingPoint,
180 model_type: PropertyModelType::GroupContribution,
181 parameters: PropertyModelParameters {
182 coefficients: {
183 let mut c = HashMap::new();
184 c.insert("intercept".to_string(), 198.2);
185 c.insert("C".to_string(), 23.97);
186 c.insert("H".to_string(), 22.88);
187 c.insert("O".to_string(), 10.0);
188 c.insert("N".to_string(), 5.0);
189 c.insert("ring".to_string(), -50.0);
190 c
191 },
192 descriptors: vec![
193 "C".to_string(),
194 "H".to_string(),
195 "O".to_string(),
196 "N".to_string(),
197 "ring".to_string(),
198 ],
199 reference_data: Vec::new(),
200 },
201 },
202 );
203
204 self.register_model(
207 "melting_point",
208 PropertyModel {
209 model_id: "qspr_melting_point".to_string(),
210 property_type: PropertyType::MeltingPoint,
211 model_type: PropertyModelType::GroupContribution,
212 parameters: PropertyModelParameters {
213 coefficients: {
214 let mut c = HashMap::new();
215 c.insert("intercept".to_string(), 122.5);
216 c.insert("C".to_string(), -5.51);
217 c.insert("H".to_string(), 8.45);
218 c.insert("O".to_string(), 4.0);
219 c.insert("N".to_string(), 2.5);
220 c.insert("ring".to_string(), -20.0);
221 c
222 },
223 descriptors: vec![
224 "C".to_string(),
225 "H".to_string(),
226 "O".to_string(),
227 "N".to_string(),
228 "ring".to_string(),
229 ],
230 reference_data: Vec::new(),
231 },
232 },
233 );
234
235 self.register_model(
238 "solubility",
239 PropertyModel {
240 model_id: "qspr_solubility".to_string(),
241 property_type: PropertyType::Density, model_type: PropertyModelType::GroupContribution,
243 parameters: PropertyModelParameters {
244 coefficients: {
245 let mut c = HashMap::new();
246 c.insert("intercept".to_string(), 0.5);
247 c.insert("logP".to_string(), -0.5);
248 c.insert("molecular_weight".to_string(), -0.01);
249 c
250 },
251 descriptors: vec!["logP".to_string(), "molecular_weight".to_string()],
252 reference_data: Vec::new(),
253 },
254 },
255 );
256
257 self.register_model(
260 "molecular_weight",
261 PropertyModel {
262 model_id: "qspr_molecular_weight".to_string(),
263 property_type: PropertyType::Density, model_type: PropertyModelType::GroupContribution,
265 parameters: PropertyModelParameters {
266 coefficients: {
267 let mut c = HashMap::new();
268 c.insert("intercept".to_string(), 0.0);
269 c.insert("C".to_string(), 12.011);
270 c.insert("H".to_string(), 1.008);
271 c.insert("O".to_string(), 15.999);
272 c.insert("N".to_string(), 14.007);
273 c.insert("S".to_string(), 32.06);
274 c.insert("Cl".to_string(), 35.45);
275 c
276 },
277 descriptors: vec![
278 "C".to_string(),
279 "H".to_string(),
280 "O".to_string(),
281 "N".to_string(),
282 "S".to_string(),
283 "Cl".to_string(),
284 ],
285 reference_data: Vec::new(),
286 },
287 },
288 );
289
290 self.register_model(
292 "density",
293 PropertyModel {
294 model_id: "qspr_density".to_string(),
295 property_type: PropertyType::Density,
296 model_type: PropertyModelType::GroupContribution,
297 parameters: PropertyModelParameters {
298 coefficients: {
299 let mut c = HashMap::new();
300 c.insert("intercept".to_string(), 0.85);
301 c.insert("molecular_weight".to_string(), 0.0018);
302 c.insert("O".to_string(), 0.08);
303 c.insert("N".to_string(), 0.05);
304 c.insert("Cl".to_string(), 0.15);
305 c
306 },
307 descriptors: vec![
308 "molecular_weight".to_string(),
309 "O".to_string(),
310 "N".to_string(),
311 "Cl".to_string(),
312 ],
313 reference_data: Vec::new(),
314 },
315 },
316 );
317
318 self.register_model(
320 "heat_capacity",
321 PropertyModel {
322 model_id: "qspr_heat_capacity".to_string(),
323 property_type: PropertyType::HeatCapacity,
324 model_type: PropertyModelType::GroupContribution,
325 parameters: PropertyModelParameters {
326 coefficients: {
327 let mut c = HashMap::new();
328 c.insert("intercept".to_string(), 25.0);
329 c.insert("C".to_string(), 15.0);
330 c.insert("H".to_string(), 7.5);
331 c.insert("O".to_string(), 18.0);
332 c.insert("N".to_string(), 12.0);
333 c
334 },
335 descriptors: vec![
336 "C".to_string(),
337 "H".to_string(),
338 "O".to_string(),
339 "N".to_string(),
340 ],
341 reference_data: Vec::new(),
342 },
343 },
344 );
345
346 self.register_model(
348 "surface_tension",
349 PropertyModel {
350 model_id: "qspr_surface_tension".to_string(),
351 property_type: PropertyType::SurfaceTension,
352 model_type: PropertyModelType::GroupContribution,
353 parameters: PropertyModelParameters {
354 coefficients: {
355 let mut c = HashMap::new();
356 c.insert("intercept".to_string(), 18.0);
357 c.insert("molecular_weight".to_string(), 0.04);
358 c.insert("O".to_string(), 4.5);
359 c
360 },
361 descriptors: vec!["molecular_weight".to_string(), "O".to_string()],
362 reference_data: Vec::new(),
363 },
364 },
365 );
366
367 self.register_model(
369 "viscosity",
370 PropertyModel {
371 model_id: "qspr_viscosity".to_string(),
372 property_type: PropertyType::Viscosity,
373 model_type: PropertyModelType::GroupContribution,
374 parameters: PropertyModelParameters {
375 coefficients: {
376 let mut c = HashMap::new();
377 c.insert("intercept".to_string(), 0.3);
378 c.insert("molecular_weight".to_string(), 0.005);
379 c
380 },
381 descriptors: vec!["molecular_weight".to_string()],
382 reference_data: Vec::new(),
383 },
384 },
385 );
386 }
387
388 pub fn validate_molecule(&self, molecule: &Molecule) -> Result<(), ChemistryError> {
390 if molecule.atoms.is_empty() {
391 return Err(ChemistryError::ValidationError(
392 "Molecule must have at least one atom".to_string(),
393 ));
394 }
395 Ok(())
396 }
397
398 pub fn predict(
407 &self,
408 property_name: &str,
409 molecular_descriptors: &HashMap<String, f64>,
410 ) -> Result<f64, ChemistryError> {
411 let model = self.property_models.get(property_name).ok_or_else(|| {
412 ChemistryError::NotImplemented(format!(
413 "no QSPR model registered for property '{}'",
414 property_name
415 ))
416 })?;
417
418 let mut predicted = 0.0;
419 for (descriptor, coefficient) in &model.parameters.coefficients {
420 if descriptor == "intercept" {
421 predicted += coefficient;
422 } else {
423 let value = molecular_descriptors
424 .get(descriptor)
425 .copied()
426 .unwrap_or(0.0);
427 predicted += coefficient * value;
428 }
429 }
430 Ok(predicted)
431 }
432
433 pub fn predict_from_molecule(
440 &self,
441 molecule: &Molecule,
442 properties: &[PropertyType],
443 ) -> Result<PredictedProperties, ChemistryError> {
444 self.validate_molecule(molecule)?;
445 let mut descriptors: HashMap<String, f64> = HashMap::new();
447 let mut molecular_weight = 0.0;
448 let mut atom_counts: HashMap<String, f64> = HashMap::new();
449 for atom in &molecule.atoms {
450 molecular_weight += atom.mass;
451 *atom_counts.entry(atom.element.clone()).or_insert(0.0) += 1.0;
452 }
453 descriptors.insert("molecular_weight".to_string(), molecular_weight);
454 for (element, count) in &atom_counts {
455 descriptors.insert(element.clone(), *count);
456 }
457 descriptors.insert("logP".to_string(), 0.0);
460
461 let mut result = PredictedProperties::new();
462 for property_type in properties {
463 let name = match property_type {
464 PropertyType::BoilingPoint => "boiling_point",
465 PropertyType::MeltingPoint => "melting_point",
466 PropertyType::Density => "density",
467 PropertyType::HeatCapacity => "heat_capacity",
468 PropertyType::SurfaceTension => "surface_tension",
469 PropertyType::Viscosity => "viscosity",
470 _ => continue,
472 };
473 match self.predict(name, &descriptors) {
474 Ok(value) => {
475 result.properties.insert(name.to_string(), value);
476 }
477 Err(ChemistryError::NotImplemented(_)) => continue,
478 Err(e) => return Err(e),
479 }
480 }
481
482 if result.properties.is_empty() {
483 return Err(ChemistryError::NotImplemented(
484 "no QSPR models available for the requested property types".to_string(),
485 ));
486 }
487 Ok(result)
488 }
489
490 pub fn register_model(&mut self, name: &str, model: PropertyModel) {
493 self.property_models.insert(name.to_string(), model);
494 }
495
496 pub fn list_properties(&self) -> Vec<String> {
498 self.property_models.keys().cloned().collect()
499 }
500
501 pub fn register_ml_model(&mut self, model: MLModel) {
504 self.machine_learning_models
505 .insert(model.model_id.clone(), model);
506 }
507
508 pub fn get_ml_model(&self, model_id: &str) -> Option<&MLModel> {
510 self.machine_learning_models.get(model_id)
511 }
512
513 pub fn get_ml_model_mut(&mut self, model_id: &str) -> Option<&mut MLModel> {
515 self.machine_learning_models.get_mut(model_id)
516 }
517
518 pub fn list_ml_models(&self) -> Vec<String> {
520 self.machine_learning_models.keys().cloned().collect()
521 }
522
523 pub fn remove_ml_model(&mut self, model_id: &str) -> Option<MLModel> {
525 self.machine_learning_models.remove(model_id)
526 }
527}
528
529impl PropertyModel {
530 pub fn new() -> Self {
532 Self {
533 model_id: "model_1".to_string(),
534 property_type: PropertyType::BoilingPoint,
535 model_type: PropertyModelType::GroupContribution,
536 parameters: PropertyModelParameters::new(),
537 }
538 }
539}
540
541impl PropertyModelParameters {
542 pub fn new() -> Self {
544 Self {
545 coefficients: HashMap::new(),
546 descriptors: vec!["molecular_weight".to_string()],
547 reference_data: vec![ReferenceData::new()],
548 }
549 }
550}
551
552impl ReferenceData {
553 pub fn new() -> Self {
555 Self {
556 molecule_id: "mol_1".to_string(),
557 property_value: 100.0,
558 conditions: ReferenceConditions::new(),
559 }
560 }
561}
562
563impl ReferenceConditions {
564 pub fn new() -> Self {
566 Self {
567 temperature: 298.15,
568 pressure: 1.0,
569 phase: PhaseType::Liquid,
570 }
571 }
572}
573
574impl DescriptorCalculator {
575 pub fn new() -> Self {
577 Self {
578 molecular_descriptors: MolecularDescriptors::new(),
579 quantum_descriptors: QuantumDescriptors::new(),
580 topological_descriptors: TopologicalDescriptors::new(),
581 }
582 }
583
584 pub fn molecular_descriptors(&self) -> &MolecularDescriptors {
586 &self.molecular_descriptors
587 }
588
589 pub fn molecular_descriptors_mut(&mut self) -> &mut MolecularDescriptors {
591 &mut self.molecular_descriptors
592 }
593
594 pub fn quantum_descriptors(&self) -> &QuantumDescriptors {
596 &self.quantum_descriptors
597 }
598
599 pub fn quantum_descriptors_mut(&mut self) -> &mut QuantumDescriptors {
601 &mut self.quantum_descriptors
602 }
603
604 pub fn topological_descriptors(&self) -> &TopologicalDescriptors {
606 &self.topological_descriptors
607 }
608
609 pub fn topological_descriptors_mut(&mut self) -> &mut TopologicalDescriptors {
611 &mut self.topological_descriptors
612 }
613
614 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
616 Ok(())
617 }
618}
619
620impl MolecularDescriptors {
621 pub fn new() -> Self {
623 Self {
624 molecular_weight: 16.04,
625 formula: "CH4".to_string(),
626 atom_count: HashMap::new(),
627 bond_count: HashMap::new(),
628 ring_count: 0,
629 }
630 }
631}
632
633impl QuantumDescriptors {
634 pub fn new() -> Self {
636 Self {
637 homo_energy: -13.6,
638 lumo_energy: 0.0,
639 gap: 13.6,
640 dipole_moment: 0.0,
641 polarizability: 0.0,
642 }
643 }
644}
645
646impl TopologicalDescriptors {
647 pub fn new() -> Self {
649 Self {
650 connectivity_index: 1.0,
651 shape_index: 1.0,
652 wiener_index: 1.0,
653 randic_index: 1.0,
654 }
655 }
656}
657
658impl MLModel {
659 pub fn new() -> Self {
661 Self {
662 model_id: "ml_1".to_string(),
663 model_type: MLModelType::LinearRegression,
664 model_parameters: MLModelParameters::new(),
665 training_data: TrainingData::new(),
666 }
667 }
668}
669
670impl MLModelParameters {
671 pub fn new() -> Self {
673 Self {
674 hyperparameters: HashMap::new(),
675 feature_importance: HashMap::new(),
676 model_performance: ModelPerformance::new(),
677 }
678 }
679}
680
681impl ModelPerformance {
682 pub fn new() -> Self {
684 Self {
685 r_squared: 0.95,
686 rmse: 0.1,
687 mae: 0.08,
688 cross_validation_score: 0.0, }
690 }
691}
692
693impl TrainingData {
694 pub fn new() -> Self {
696 Self {
697 data_id: "data_1".to_string(),
698 features: vec![vec![1.0; 10]; 100],
699 targets: vec![100.0; 100],
700 data_size: 100,
701 }
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708
709 fn water_molecule() -> Molecule {
710 let mut m = Molecule::new();
711 m.formula = "H2O".to_string();
712 m.atoms.push(Atom {
713 atom_id: "O1".to_string(),
714 element: "O".to_string(),
715 atomic_number: 8,
716 mass: 15.999,
717 charge: 0.0,
718 coordinates: vec![0.0, 0.0, 0.0],
719 });
720 m.atoms.push(Atom {
721 atom_id: "H1".to_string(),
722 element: "H".to_string(),
723 atomic_number: 1,
724 mass: 1.008,
725 charge: 0.0,
726 coordinates: vec![0.0, 0.757, 0.586],
727 });
728 m.atoms.push(Atom {
729 atom_id: "H2".to_string(),
730 element: "H".to_string(),
731 atomic_number: 1,
732 mass: 1.008,
733 charge: 0.0,
734 coordinates: vec![0.0, -0.757, 0.586],
735 });
736 m.coordinates = m.atoms.iter().map(|atom| atom.coordinates.clone()).collect();
737 m
738 }
739
740 #[test]
741 fn initialized_predictor_uses_registered_group_contribution_formulas() {
742 let uninitialized = PropertyPredictor::new();
743 let mol = water_molecule();
744 assert_eq!(mol.formula, "H2O");
745 assert_eq!(mol.atoms.len(), 3);
746 assert_eq!(mol.coordinates.len(), 3);
747 assert!(!mol.atoms.iter().any(|atom| atom.element == "C"));
748 assert!(matches!(
749 uninitialized.predict_from_molecule(&mol, &[PropertyType::BoilingPoint]),
750 Err(ChemistryError::NotImplemented(_))
751 ));
752
753 let mut predictor = PropertyPredictor::new();
754 predictor.initialize().unwrap();
755 let registered = predictor.list_properties();
756 assert!(registered.iter().any(|name| name == "boiling_point"));
757 assert!(registered.iter().any(|name| name == "density"));
758 assert!(registered.iter().any(|name| name == "heat_capacity"));
759
760 let descriptors = HashMap::from([
763 ("C".to_string(), 0.0),
764 ("H".to_string(), 2.0),
765 ("O".to_string(), 1.0),
766 ("N".to_string(), 0.0),
767 ("ring".to_string(), 0.0),
768 ]);
769 assert!((predictor.predict("boiling_point", &descriptors).unwrap() - 253.96).abs() < 1e-12);
770 assert!(matches!(
771 predictor.predict("unknown_property", &descriptors),
772 Err(ChemistryError::NotImplemented(_))
773 ));
774
775 let res = predictor
776 .predict_from_molecule(
777 &mol,
778 &[
779 PropertyType::BoilingPoint,
780 PropertyType::Density,
781 PropertyType::HeatCapacity,
782 ],
783 )
784 .unwrap();
785 assert!(res.properties.contains_key("boiling_point"));
786 assert!(res.properties.contains_key("density"));
787 assert!(res.properties.contains_key("heat_capacity"));
788 assert!((res.properties["density"] - 0.962427).abs() < 1e-12);
791 assert!((res.properties["heat_capacity"] - 58.0).abs() < 1e-12);
792 }
793
794 #[test]
795 fn initialized_predictor_rejects_empty_and_formula_only_molecules() {
796 let mut predictor = PropertyPredictor::new();
797 predictor.initialize().unwrap();
798 for formula in ["", "H2O"] {
799 let mut molecule = Molecule::new();
800 molecule.formula = formula.to_string();
801 assert!(matches!(
802 predictor.predict_from_molecule(&molecule, &[PropertyType::Density]),
803 Err(ChemistryError::ValidationError(_))
804 ));
805 }
806 }
807}