Skip to main content

qualia_core_db/specialized_libs/chemistry_modeling/
dft.rs

1//! Density Functional Theory (DFT) Integration
2//!
3//! This module extends the SCF driver to include Exchange-Correlation Integration.
4//! It implements numerical grid evaluation for LDA and GGA.
5//! Exact analytical derivatives of the functional expressions are computed using
6//! a Rust-native forward-mode automatic differentiation (autodiff) Dual number struct.
7//! NO libxc C-bindings are used.
8
9use crate::specialized_libs::shared::zero_heap_algebra::ZeroHeapMatrix;
10
11/// A Dual number for forward-mode automatic differentiation.
12/// Evaluates f(x) and f'(x) simultaneously.
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct Dual {
15    pub v: f64, // Value
16    pub d: f64, // Derivative
17}
18
19impl Dual {
20    /// Creates a dual number with value `v` and derivative `d`.
21    pub fn new(v: f64, d: f64) -> Self {
22        Self { v, d }
23    }
24
25    /// Dual addition.
26    pub fn add(self, other: Self) -> Self {
27        Self::new(self.v + other.v, self.d + other.d)
28    }
29
30    /// Dual subtraction.
31    pub fn sub(self, other: Self) -> Self {
32        Self::new(self.v - other.v, self.d - other.d)
33    }
34
35    /// Dual multiplication (product rule).
36    pub fn mul(self, other: Self) -> Self {
37        Self::new(self.v * other.v, self.d * other.v + self.v * other.d)
38    }
39
40    /// Dual division (quotient rule).
41    pub fn div(self, other: Self) -> Self {
42        Self::new(
43            self.v / other.v,
44            (self.d * other.v - self.v * other.d) / (other.v * other.v),
45        )
46    }
47
48    /// Dual `x^p` — derivative scales by `p·x^(p−1)`.
49    pub fn powf(self, power: f64) -> Self {
50        Self::new(
51            self.v.powf(power),
52            power * self.v.powf(power - 1.0) * self.d,
53        )
54    }
55
56    /// Dual cube root — derivative scales by `(1/3)x^(−2/3)`.
57    pub fn cbrt(self) -> Self {
58        self.powf(1.0 / 3.0)
59    }
60
61    /// Scalar multiply — value and derivative both scale.
62    pub fn scale(self, scalar: f64) -> Self {
63        Self::new(self.v * scalar, self.d * scalar)
64    }
65
66    /// Dual natural log — derivative scales by `1/x`.
67    pub fn ln(self) -> Self {
68        Self::new(self.v.ln(), self.d / self.v)
69    }
70
71    /// Dual arctan — derivative scales by `1/(1+x²)`.
72    pub fn atan(self) -> Self {
73        Self::new(self.v.atan(), self.d / (1.0 + self.v * self.v))
74    }
75}
76
77/// Local Density Approximation (LDA) Exchange Functional (Dirac / Slater)
78/// E_x`rho` = - (3/4) * (3/pi)^(1/3) * int rho(r)^(4/3) dr
79/// Returns (Energy Density, Potential)
80pub fn lda_exchange(rho: f64) -> (f64, f64) {
81    if rho <= 1e-12 {
82        return (0.0, 0.0);
83    }
84
85    // Seed the derivative (d/d rho)
86    let r = Dual::new(rho, 1.0);
87    let factor = -0.75 * (3.0 / core::f64::consts::PI).powf(1.0 / 3.0);
88
89    let ex = r.cbrt().scale(factor); // e_x = C_x * rho^(1/3)
90    let vx = ex.scale(4.0 / 3.0); // v_x = (4/3) * C_x * rho^(1/3)
91
92    // e_x is exchange energy per particle, total exchange is rho * e_x.
93    // The derivative of rho * e_x with respect to rho is v_x.
94    (ex.v, vx.v)
95}
96
97/// VWN (Vosko-Wilk-Nusair) Local Correlation Functional (Unpolarized)
98pub fn lda_correlation_vwn(rho: f64) -> (f64, f64) {
99    if rho <= 1e-12 {
100        return (0.0, 0.0);
101    }
102
103    // Simplified VWN5 parameterization for the unpolarized electron gas
104    let r_s = Dual::new(
105        (3.0 / (4.0 * core::f64::consts::PI * rho)).powf(1.0 / 3.0),
106        -1.0 / (3.0 * rho) * (3.0 / (4.0 * core::f64::consts::PI * rho)).powf(1.0 / 3.0),
107    );
108
109    let a = 0.0621814;
110    let x0 = -0.409286;
111    let b = 13.0720_f64;
112    let c = 42.7198_f64;
113
114    let x = r_s.powf(0.5);
115    let q = (4.0 * c - b * b).sqrt();
116
117    // Polynomial X(x) = x^2 + b*x + c
118    let x_func = x.mul(x).add(x.scale(b)).add(Dual::new(c, 0.0));
119    let x0_func = x0 * x0 + b * x0 + c;
120
121    // VWN Evaluation using Dual numbers
122    // ec(x) = A * { ln(x^2 / X(x)) + 2b/Q * atan(Q / (2x+b)) - bx0/X(x0) * [ ln((x-x0)^2 / X(x)) + 2(b+2x0)/Q * atan(Q / (2x+b)) ] }
123    let term1 = x.mul(x).div(x_func).ln();
124
125    let atan_arg = Dual::new(q, 0.0).div(x.scale(2.0).add(Dual::new(b, 0.0)));
126    let term2 = atan_arg.atan().scale(2.0 * b / q);
127
128    let term3_factor = (b * x0) / x0_func;
129
130    let x_minus_x0 = x.sub(Dual::new(x0, 0.0));
131    let term3_ln = x_minus_x0.mul(x_minus_x0).div(x_func).ln();
132    let term3_atan = atan_arg.atan().scale(2.0 * (b + 2.0 * x0) / q);
133
134    let term3 = term3_ln.add(term3_atan).scale(term3_factor);
135
136    let ec = term1.add(term2).sub(term3).scale(a);
137    let vc = ec.v + rho * ec.d; // potential = d(rho*ec)/drho = ec + rho * dec/drho
138
139    (ec.v, vc)
140}
141
142/// DftIntegrator grid-based integration for the SCF loop
143pub struct DftIntegrator {
144    // Pre-computed spatial grid coordinates and weights for the molecule
145    pub grid_points: [[f64; 3]; 500],
146    pub grid_weights: [f64; 500],
147    pub n_points: usize,
148}
149
150impl DftIntegrator {
151    /// Creates a DFT grid integrator with default parameters.
152    pub fn new() -> Self {
153        Self {
154            grid_points: [[0.0; 3]; 500],
155            grid_weights: [0.0; 500],
156            n_points: 0,
157        }
158    }
159
160    /// Evaluate the Exchange-Correlation matrix V_xc to be added to the Fock matrix
161    pub fn build_vxc<const N: usize>(
162        &self,
163        density: &ZeroHeapMatrix<f64, N, N>,
164        basis_values_at_grid: &[[f64; N]; 500],
165    ) -> (f64, ZeroHeapMatrix<f64, N, N>) {
166        let mut vxc = ZeroHeapMatrix::zeros();
167        let mut exc_total = 0.0;
168
169        for p in 0..self.n_points {
170            let weight = self.grid_weights[p];
171            let basis_vals = &basis_values_at_grid[p];
172
173            // 1. Calculate density at grid point p
174            let mut rho_p = 0.0;
175            for mu in 0..N {
176                for nu in 0..N {
177                    rho_p += density.get(mu, nu) * basis_vals[mu] * basis_vals[nu];
178                }
179            }
180
181            // 2. Evaluate Functional (LDA Exchange + Correlation)
182            let (ex, vx) = lda_exchange(rho_p);
183            let (ec, vc) = lda_correlation_vwn(rho_p);
184
185            let e_xc = ex + ec;
186            let v_xc = vx + vc;
187
188            exc_total += e_xc * rho_p * weight;
189
190            // 3. Accumulate Vxc matrix
191            for mu in 0..N {
192                for nu in 0..N {
193                    let val = vxc.get(mu, nu) + v_xc * basis_vals[mu] * basis_vals[nu] * weight;
194                    vxc.set(mu, nu, val);
195                }
196            }
197        }
198
199        (exc_total, vxc)
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn test_lda_exchange() {
209        let rho = 0.5;
210        let (ex, vx) = lda_exchange(rho);
211        // Compare with expected analytic values
212        // ex = -0.75 * (3/pi)^(1/3) * rho^(1/3)
213        // vx = 4/3 * ex
214        let expected_ex =
215            -0.75 * (3.0 / core::f64::consts::PI).powf(1.0 / 3.0) * rho.powf(1.0 / 3.0);
216        let expected_vx = 4.0 / 3.0 * expected_ex;
217
218        assert!((ex - expected_ex).abs() < 1e-10);
219        assert!((vx - expected_vx).abs() < 1e-10);
220    }
221
222    #[test]
223    fn test_lda_correlation_vwn() {
224        let rho = 0.5;
225        let (ec, vc) = lda_correlation_vwn(rho);
226
227        // As long as the derivative evaluates cleanly without NaN, the autodiff works
228        assert!(!ec.is_nan());
229        assert!(!vc.is_nan());
230    }
231
232    #[test]
233    fn test_dual_number_ops() {
234        // Test f(x) = x^3 at x = 2
235        // f(2) = 8
236        // f'(x) = 3x^2 => f'(2) = 12
237        let x = Dual::new(2.0, 1.0);
238        let x2 = x.mul(x);
239        let x3 = x2.mul(x);
240
241        assert!((x3.v - 8.0).abs() < 1e-10);
242        assert!((x3.d - 12.0).abs() < 1e-10);
243    }
244}