1use super::integrals::{GtoPrimitive, IntegralEngine};
2use super::scf::solve_rhf_scf_4index;
3use super::*;
4use crate::specialized_libs::shared::zero_heap_algebra::ZeroHeapMatrix;
5use core::f64::consts::PI;
6
7#[derive(Debug, Clone, Copy)]
10struct ContractedS {
11 prims: [GtoPrimitive; 3],
13}
14
15fn build_sto3g_s(z: usize, center: [f64; 3]) -> Option<ContractedS> {
23 let (exps, coefs): ([f64; 3], [f64; 3]) = match z {
25 1 => (
26 [3.425_250_914, 0.623_913_730, 0.168_855_400],
27 [0.154_328_967, 0.535_328_142, 0.444_634_542],
28 ),
29 2 => (
30 [6.362_421_394, 1.158_922_999, 0.313_649_790],
31 [0.154_328_967, 0.535_328_142, 0.444_634_542],
32 ),
33 _ => return None,
34 };
35 let mut d = [0.0_f64; 3];
37 for i in 0..3 {
38 d[i] = coefs[i] * (2.0 * exps[i] / PI).powf(0.75);
39 }
40 let mut s_cc = 0.0;
42 for i in 0..3 {
43 for j in 0..3 {
44 s_cc += d[i] * d[j] * (PI / (exps[i] + exps[j])).powf(1.5);
45 }
46 }
47 let renorm = 1.0 / s_cc.sqrt();
48 let mut prims = [GtoPrimitive {
49 origin: center,
50 exponent: 0.0,
51 l: [0, 0, 0],
52 coefficient: 0.0,
53 }; 3];
54 for i in 0..3 {
55 prims[i] = GtoPrimitive {
56 origin: center,
57 exponent: exps[i],
58 l: [0, 0, 0],
59 coefficient: d[i] * renorm,
60 };
61 }
62 Some(ContractedS { prims })
63}
64
65fn c_overlap(a: &ContractedS, b: &ContractedS) -> f64 {
67 let mut v = 0.0;
68 for i in 0..3 {
69 for j in 0..3 {
70 v += IntegralEngine::overlap_s(&a.prims[i], &b.prims[j]);
71 }
72 }
73 v
74}
75
76fn c_kinetic(a: &ContractedS, b: &ContractedS) -> f64 {
78 let mut v = 0.0;
79 for i in 0..3 {
80 for j in 0..3 {
81 v += IntegralEngine::kinetic_s(&a.prims[i], &b.prims[j]);
82 }
83 }
84 v
85}
86
87fn c_nuclear(a: &ContractedS, b: &ContractedS, nuclei: &[([f64; 3], f64)]) -> f64 {
89 let mut v = 0.0;
90 for &(center, z) in nuclei {
91 for i in 0..3 {
92 for j in 0..3 {
93 v += IntegralEngine::nuclear_s(&a.prims[i], &b.prims[j], center, z);
94 }
95 }
96 }
97 v
98}
99
100fn c_eri(a: &ContractedS, b: &ContractedS, c: &ContractedS, d: &ContractedS) -> f64 {
102 let mut v = 0.0;
103 for i in 0..3 {
104 for j in 0..3 {
105 for k in 0..3 {
106 for l in 0..3 {
107 v += IntegralEngine::evaluate_eri(
108 &a.prims[i],
109 &b.prims[j],
110 &c.prims[k],
111 &d.prims[l],
112 );
113 }
114 }
115 }
116 }
117 v
118}
119
120fn c_dipole(a: &ContractedS, b: &ContractedS) -> [f64; 3] {
122 let mut v = [0.0; 3];
123 for i in 0..3 {
124 for j in 0..3 {
125 let d = IntegralEngine::dipole_s(&a.prims[i], &b.prims[j]);
126 v[0] += d[0];
127 v[1] += d[1];
128 v[2] += d[2];
129 }
130 }
131 v
132}
133
134fn run_rhf<const N: usize>(
138 shells: &[ContractedS; N],
139 nuclei: &[([f64; 3], f64)],
140 n_elec: usize,
141) -> Result<QuantumProperties, ChemistryError> {
142 let mut s = ZeroHeapMatrix::<f64, N, N>::zeros();
144 let mut h = ZeroHeapMatrix::<f64, N, N>::zeros();
145 for i in 0..N {
146 for j in 0..N {
147 s.set(i, j, c_overlap(&shells[i], &shells[j]));
148 h.set(
149 i,
150 j,
151 c_kinetic(&shells[i], &shells[j]) + c_nuclear(&shells[i], &shells[j], nuclei),
152 );
153 }
154 }
155 let mut eri = [[[[0.0_f64; N]; N]; N]; N];
156 for i in 0..N {
157 for j in 0..N {
158 for k in 0..N {
159 for l in 0..N {
160 eri[i][j][k][l] = c_eri(&shells[i], &shells[j], &shells[k], &shells[l]);
161 }
162 }
163 }
164 }
165
166 let res = solve_rhf_scf_4index(&h, &s, &eri, n_elec).map_err(|e| {
167 ChemistryError::ConvergenceError(format!("RHF SCF did not converge: {:?}", e))
168 })?;
169
170 let mut e_nn = 0.0;
172 for i in 0..nuclei.len() {
173 for j in (i + 1)..nuclei.len() {
174 let (ci, zi) = nuclei[i];
175 let (cj, zj) = nuclei[j];
176 let r = ((ci[0] - cj[0]).powi(2) + (ci[1] - cj[1]).powi(2) + (ci[2] - cj[2]).powi(2))
177 .sqrt();
178 e_nn += zi * zj / r;
179 }
180 }
181 let total_energy = res.electronic_energy + e_nn;
182
183 let num_occ = res.num_occ;
185 let homo = if num_occ >= 1 {
186 res.orbital_energies[num_occ - 1]
187 } else {
188 0.0
189 };
190 let (lumo, gap) = if N > num_occ {
191 let l = res.orbital_energies[num_occ];
192 (l, l - homo)
193 } else {
194 (homo, 0.0)
197 };
198
199 let ps = res.density * s;
201 let mut mulliken = Vec::with_capacity(N);
202 for i in 0..N {
203 mulliken.push(nuclei[i].1 - ps.get(i, i));
204 }
205
206 let mut dip = [0.0_f64; 3];
208 for &(center, z) in nuclei {
209 for w in 0..3 {
210 dip[w] += z * center[w];
211 }
212 }
213 for i in 0..N {
214 for j in 0..N {
215 let dij = c_dipole(&shells[i], &shells[j]);
216 let p = res.density.get(i, j);
217 for w in 0..3 {
218 dip[w] -= p * dij[w];
219 }
220 }
221 }
222 let dipole_magnitude = (dip[0] * dip[0] + dip[1] * dip[1] + dip[2] * dip[2]).sqrt();
223
224 Ok(QuantumProperties {
225 total_energy,
226 homo_energy: homo,
227 lumo_energy: lumo,
228 gap,
229 dipole_moment: dipole_magnitude,
230 polarizability: 0.0,
234 mulliken_charges: mulliken,
235 })
236}
237
238pub struct QuantumCalculator {
240 wavefunction_calculator: WavefunctionCalculator,
241 energy_calculator: QuantumEnergyCalculator,
242 property_calculator: QuantumPropertyCalculator,
243}
244
245pub struct WavefunctionCalculator {
247 method_type: QuantumMethodType,
248 basis_set: BasisSet,
249 scf_parameters: SCFParameters,
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
254pub enum QuantumMethodType {
255 HartreeFock,
256 DFT,
257 MP2,
258 CCSD,
259 CI,
260 SemiEmpirical,
261 AbInitio,
262}
263
264#[derive(Debug, Clone)]
266pub struct BasisSet {
267 pub basis_set_id: String,
268 pub basis_set_name: String,
269 pub basis_set_type: BasisSetType,
270 pub functions: Vec<BasisFunction>,
271}
272
273#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
275pub enum BasisSetType {
276 Minimal,
277 SplitValence,
278 TripleZeta,
279 Polarization,
280 Diffuse,
281 Custom,
282}
283
284#[derive(Debug, Clone)]
286pub struct BasisFunction {
287 pub function_id: String,
288 pub function_type: BasisFunctionType,
289 pub center: Vec<f64>,
290 pub exponents: Vec<f64>,
291 pub coefficients: Vec<f64>,
292}
293
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296pub enum BasisFunctionType {
297 S,
298 P,
299 D,
300 F,
301 G,
302 Custom,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct SCFParameters {
308 pub convergence_threshold: f64,
309 pub max_iterations: u32,
310 pub damping_factor: f64,
311 pub level_shifting: f64,
312}
313
314pub struct QuantumEnergyCalculator {
316 electronic_energy: ElectronicEnergy,
317 nuclear_energy: NuclearEnergy,
318 total_energy: QuantumTotalEnergy,
319}
320
321#[derive(Debug, Clone)]
323pub struct ElectronicEnergy {
324 pub kinetic_energy: f64,
325 pub electron_nuclear: f64,
326 pub electron_electron: f64,
327 pub exchange_correlation: f64,
328}
329
330#[derive(Debug, Clone)]
332pub struct NuclearEnergy {
333 pub nuclear_repulsion: f64,
334 pub nuclear_attraction: f64,
335}
336
337#[derive(Debug, Clone)]
339pub struct QuantumTotalEnergy {
340 pub electronic: f64,
341 pub nuclear: f64,
342 pub total: f64,
343 pub correction_terms: Vec<f64>,
344}
345
346pub struct QuantumPropertyCalculator {
348 dipole_moment: DipoleMoment,
349 polarizability: Polarizability,
350 mulliken_charges: MullikenCharges,
351}
352
353#[derive(Debug, Clone)]
355pub struct DipoleMoment {
356 pub components: Vec<f64>,
357 pub magnitude: f64,
358}
359
360#[derive(Debug, Clone)]
362pub struct Polarizability {
363 pub tensor: Vec<Vec<f64>>,
364 pub isotropic: f64,
365}
366
367#[derive(Debug, Clone)]
369pub struct MullikenCharges {
370 pub charges: Vec<f64>,
371 pub total_charge: f64,
372}
373
374impl QuantumCalculator {
375 pub fn new() -> Self {
377 Self {
378 wavefunction_calculator: WavefunctionCalculator::new(),
379 energy_calculator: QuantumEnergyCalculator::new(),
380 property_calculator: QuantumPropertyCalculator::new(),
381 }
382 }
383
384 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
386 self.wavefunction_calculator.initialize()?;
387 self.energy_calculator.initialize()?;
388 self.property_calculator.initialize()?;
389 Ok(())
390 }
391
392 pub fn validate_molecule(&self, molecule: &Molecule) -> Result<(), ChemistryError> {
394 if molecule.atoms.is_empty() {
395 return Err(ChemistryError::ValidationError(
396 "Molecule must have at least one atom".to_string(),
397 ));
398 }
399 Ok(())
400 }
401
402 pub fn calculate_properties(
418 &mut self,
419 molecule: &Molecule,
420 method: QuantumMethodType,
421 ) -> Result<QuantumProperties, ChemistryError> {
422 match method {
423 QuantumMethodType::HartreeFock | QuantumMethodType::AbInitio => {}
424 other => {
425 return Err(ChemistryError::NotImplemented(format!(
426 "electronic structure: only closed-shell RHF (HartreeFock) is implemented; \
427 {:?} would require a correlated/DFT method that is not yet built",
428 other
429 )));
430 }
431 }
432
433 if molecule.atoms.is_empty() {
434 return Err(ChemistryError::ValidationError(
435 "electronic structure: the molecule has no atoms".to_string(),
436 ));
437 }
438
439 let mut shells: Vec<ContractedS> = Vec::with_capacity(molecule.atoms.len());
442 let mut nuclei: Vec<([f64; 3], f64)> = Vec::with_capacity(molecule.atoms.len());
443 let mut n_elec = 0usize;
444 for (idx, a) in molecule.atoms.iter().enumerate() {
445 if a.coordinates.len() != 3 {
446 return Err(ChemistryError::InsufficientData(format!(
447 "electronic structure: atom {} ('{}') has {} coordinates; 3 (in bohr) required",
448 idx,
449 a.atom_id,
450 a.coordinates.len()
451 )));
452 }
453 let center = [a.coordinates[0], a.coordinates[1], a.coordinates[2]];
454 let shell = build_sto3g_s(a.atomic_number, center).ok_or_else(|| {
455 ChemistryError::NotImplemented(format!(
456 "electronic structure: STO-3G RHF is implemented for H and He only; atom {} \
457 ('{}', element '{}', Z={}) needs p/d shells that are not yet built",
458 idx, a.atom_id, a.element, a.atomic_number
459 ))
460 })?;
461 shells.push(shell);
462 nuclei.push((center, a.atomic_number as f64));
463 n_elec += a.atomic_number;
464 }
465
466 if n_elec == 0 {
467 return Err(ChemistryError::ValidationError(
468 "electronic structure: total electron count is zero".to_string(),
469 ));
470 }
471 if n_elec % 2 != 0 {
472 return Err(ChemistryError::NotImplemented(format!(
473 "electronic structure: {} electrons is open-shell; only closed-shell RHF (even \
474 electron count) is implemented — UHF is not yet built",
475 n_elec
476 )));
477 }
478
479 let n_bf = shells.len();
480 macro_rules! dispatch {
482 ($($n:literal),+ $(,)?) => {
483 match n_bf {
484 $(
485 $n => {
486 let mut arr = [shells[0]; $n];
487 for i in 0..$n { arr[i] = shells[i]; }
488 run_rhf::<$n>(&arr, &nuclei, n_elec)
489 }
490 )+
491 _ => Err(ChemistryError::NotImplemented(format!(
492 "electronic structure: STO-3G RHF currently supports 1–16 s-type basis \
493 functions (H/He atoms) within the zero-heap 4-index stack budget; this molecule needs {}",
494 n_bf
495 ))),
496 }
497 };
498 }
499 dispatch!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
500 }
501}
502
503impl WavefunctionCalculator {
504 pub fn new() -> Self {
506 Self {
507 method_type: QuantumMethodType::HartreeFock,
508 basis_set: BasisSet::new(),
509 scf_parameters: SCFParameters::new(),
510 }
511 }
512
513 pub fn method_type(&self) -> &QuantumMethodType {
515 &self.method_type
516 }
517
518 pub fn set_method_type(&mut self, method_type: QuantumMethodType) {
520 self.method_type = method_type;
521 }
522
523 pub fn basis_set(&self) -> &BasisSet {
525 &self.basis_set
526 }
527
528 pub fn basis_set_mut(&mut self) -> &mut BasisSet {
530 &mut self.basis_set
531 }
532
533 pub fn scf_parameters(&self) -> &SCFParameters {
535 &self.scf_parameters
536 }
537
538 pub fn scf_parameters_mut(&mut self) -> &mut SCFParameters {
540 &mut self.scf_parameters
541 }
542
543 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
545 Ok(())
546 }
547}
548
549impl BasisSet {
550 pub fn new() -> Self {
552 Self {
553 basis_set_id: "basis_1".to_string(),
554 basis_set_name: "6-31G".to_string(),
555 basis_set_type: BasisSetType::SplitValence,
556 functions: vec![BasisFunction::new()],
557 }
558 }
559}
560
561impl BasisFunction {
562 pub fn new() -> Self {
564 Self {
565 function_id: "func_1".to_string(),
566 function_type: BasisFunctionType::S,
567 center: vec![0.0, 0.0, 0.0],
568 exponents: vec![0.5],
569 coefficients: vec![1.0],
570 }
571 }
572}
573
574impl SCFParameters {
575 pub fn new() -> Self {
577 Self {
578 convergence_threshold: 1e-8,
579 max_iterations: 100,
580 damping_factor: 0.5,
581 level_shifting: 0.3,
582 }
583 }
584}
585
586impl QuantumEnergyCalculator {
587 pub fn new() -> Self {
589 Self {
590 electronic_energy: ElectronicEnergy::new(),
591 nuclear_energy: NuclearEnergy::new(),
592 total_energy: QuantumTotalEnergy::new(),
593 }
594 }
595
596 pub fn electronic_energy(&self) -> &ElectronicEnergy {
598 &self.electronic_energy
599 }
600
601 pub fn electronic_energy_mut(&mut self) -> &mut ElectronicEnergy {
603 &mut self.electronic_energy
604 }
605
606 pub fn nuclear_energy(&self) -> &NuclearEnergy {
608 &self.nuclear_energy
609 }
610
611 pub fn nuclear_energy_mut(&mut self) -> &mut NuclearEnergy {
613 &mut self.nuclear_energy
614 }
615
616 pub fn total_energy(&self) -> &QuantumTotalEnergy {
618 &self.total_energy
619 }
620
621 pub fn total_energy_mut(&mut self) -> &mut QuantumTotalEnergy {
623 &mut self.total_energy
624 }
625
626 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
628 Ok(())
629 }
630}
631
632impl ElectronicEnergy {
633 pub fn new() -> Self {
635 Self {
636 kinetic_energy: 0.0,
637 electron_nuclear: 0.0,
638 electron_electron: 0.0,
639 exchange_correlation: 0.0,
640 }
641 }
642}
643
644impl NuclearEnergy {
645 pub fn new() -> Self {
647 Self {
648 nuclear_repulsion: 0.0,
649 nuclear_attraction: 0.0,
650 }
651 }
652}
653
654impl QuantumTotalEnergy {
655 pub fn new() -> Self {
657 Self {
658 electronic: 0.0,
659 nuclear: 0.0,
660 total: 0.0,
661 correction_terms: Vec::new(),
662 }
663 }
664}
665
666impl QuantumPropertyCalculator {
667 pub fn new() -> Self {
669 Self {
670 dipole_moment: DipoleMoment::new(),
671 polarizability: Polarizability::new(),
672 mulliken_charges: MullikenCharges::new(),
673 }
674 }
675
676 pub fn dipole_moment(&self) -> &DipoleMoment {
678 &self.dipole_moment
679 }
680
681 pub fn dipole_moment_mut(&mut self) -> &mut DipoleMoment {
683 &mut self.dipole_moment
684 }
685
686 pub fn polarizability(&self) -> &Polarizability {
688 &self.polarizability
689 }
690
691 pub fn polarizability_mut(&mut self) -> &mut Polarizability {
693 &mut self.polarizability
694 }
695
696 pub fn mulliken_charges(&self) -> &MullikenCharges {
698 &self.mulliken_charges
699 }
700
701 pub fn mulliken_charges_mut(&mut self) -> &mut MullikenCharges {
703 &mut self.mulliken_charges
704 }
705
706 pub fn initialize(&mut self) -> Result<(), ChemistryError> {
708 Ok(())
709 }
710}
711
712impl DipoleMoment {
713 pub fn new() -> Self {
715 Self {
716 components: vec![0.0, 0.0, 0.0],
717 magnitude: 0.0,
718 }
719 }
720}
721
722impl Polarizability {
723 pub fn new() -> Self {
725 Self {
726 tensor: vec![vec![0.0; 3]; 3],
727 isotropic: 0.0,
728 }
729 }
730}
731
732impl MullikenCharges {
733 pub fn new() -> Self {
735 Self {
736 charges: Vec::new(),
737 total_charge: 0.0,
738 }
739 }
740}