Skip to main content

tpt_sci_dft_electronic/
lib.rs

1//! # tpt-sci-dft-electronic
2//!
3//! **Electronic-structure DFT** for the `tpt-science` pillar — a deliberately
4//! simple, from-scratch **1-D Kohn–Sham** solver (LDA exchange-correlation),
5//! scoped to 1-D model systems per the 2026-08 spec2.txt audit
6//! (`tpt-sci-dft-electronic` was `flagged-needs-audit-first`; no Rust prior art
7//! exists for Kohn–Sham LDA/GGA/band-structure, so this is treated as a
8//! multi-phase undertaking like `tpt-sci-physics-rigid`/`tpt-sci-quantum`).
9//!
10//! v1 delivers:
11//!
12//! * A 1-D real-space grid ([`Grid1D`]) with a soft **local** external potential
13//!   `V_ext(x)` (defines a confining well / 1-D "atom").
14//! * The **local-density approximation** exchange-correlation energy density
15//!   [`lda_xc`] (Slater exchange + a Perdew–Zunger-like correlation form).
16//! * A [`KohnSham`] solver that diagonalizes the Kohn–Sham Hamiltonian
17//!   `(−½ d²/dx² + V_eff)` with a kinetic-energy finite-difference Laplacian and
18//!   a charge self-consistency (Hartree + XC) loop, returning occupied orbitals
19//!   and the total energy.
20//!
21//! Multi-electron 3-D atoms, GGA/PBE, local pseudopotentials, and periodic
22//! band structures are now implemented alongside the original 1-D LDA solver
23//! (see [`KohnSham3D`], [`XcFunctional`], [`Pseudopotential`],
24//! [`PeriodicPotential1D`]).
25//!
26//! # Example
27//!
28//! ```
29//! use tpt_sci_dft_electronic::{Grid1D, KohnSham, lda_xc};
30//!
31//! let grid = Grid1D::new(101, -5.0, 5.0).unwrap();
32//! // Harmonic-like external well.
33//! let v_ext: Vec<f64> = grid.x().iter().map(|&x| 0.5 * x * x).collect();
34//! let mut ks = KohnSham::new(grid, v_ext, 2).unwrap(); // 2 electrons
35//! let res = ks.solve(50);
36//! assert!(res.total_energy.is_finite());
37//! // LDA XC energy density must be <= 0 (attractive exchange).
38//! assert!(lda_xc(1.0) <= 0.0);
39//! ```
40#![forbid(unsafe_code)]
41
42mod eigen;
43mod error;
44mod ks3d;
45mod periodic;
46mod pseudopotential;
47mod xc;
48
49pub use error::DftError;
50pub use ks3d::{KohnSham3D, KohnSham3DResult};
51pub use periodic::PeriodicPotential1D;
52pub use pseudopotential::Pseudopotential;
53pub use xc::{Lda, Pbe, XcFunctional, pw_lda_xc};
54
55/// A uniform 1-D real-space grid.
56#[derive(Debug, Clone)]
57pub struct Grid1D {
58    /// Cell coordinates `x`.
59    pub xs: Vec<f64>,
60    /// Grid spacing `Δx`.
61    pub dx: f64,
62    /// Number of points.
63    pub n: usize,
64}
65
66impl Grid1D {
67    /// Construct `n` evenly spaced points in `[xmin, xmax]` (inclusive).
68    ///
69    /// # Errors
70    ///
71    /// Returns [`DftError::InvalidGrid`] if `n < 2` or `xmax <= xmin`.
72    pub fn new(n: usize, xmin: f64, xmax: f64) -> Result<Self, DftError> {
73        if n < 2 {
74            return Err(DftError::InvalidGrid("need at least 2 points".into()));
75        }
76        if xmax <= xmin {
77            return Err(DftError::InvalidGrid("xmax must exceed xmin".into()));
78        }
79        let dx = (xmax - xmin) / (n as f64 - 1.0);
80        let xs = (0..n).map(|i| xmin + i as f64 * dx).collect();
81        Ok(Self { xs, dx, n })
82    }
83
84    /// Borrow the coordinate vector.
85    #[must_use]
86    pub fn x(&self) -> &[f64] {
87        &self.xs
88    }
89}
90
91/// Local-density-approximation exchange-correlation energy density
92/// `e_xc(ρ)` (per electron, in Hartree units) for density `rho` (electrons per
93/// unit length).
94///
95/// Uses Slater local exchange `e_x = −(3/4)·(3/π)^(1/3)·ρ^(1/3)` plus a
96/// Perdew–Zunger-style local correlation `e_c ≈ −0.056·ρ / (1 + 11.4·ρ)`,
97/// giving the standard `e_xc ≤ 0` (attractive) behaviour.
98///
99/// # Panics
100///
101/// Panics if `rho < 0`.
102#[must_use]
103pub fn lda_xc(rho: f64) -> f64 {
104    assert!(rho >= 0.0, "density must be >= 0");
105    let ex = -(3.0 / 4.0) * (3.0 / std::f64::consts::PI).powf(1.0 / 3.0) * rho.powf(1.0 / 3.0);
106    let ec = -0.056 * rho / (1.0 + 11.4 * rho);
107    ex + ec
108}
109
110/// A 1-D Kohn–Sham self-consistent solver.
111#[derive(Debug, Clone)]
112pub struct KohnSham {
113    grid: Grid1D,
114    /// External local potential `V_ext(x)`.
115    v_ext: Vec<f64>,
116    /// Number of electrons.
117    nelect: usize,
118    /// Current spin-summed density `ρ(x)`.
119    rho: Vec<f64>,
120    /// Most recent occupied orbital coefficients (for the result surface).
121    last_orbitals: Vec<Vec<f64>>,
122}
123
124impl KohnSham {
125    /// Construct from a grid, external potential, and electron count.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`DftError::InvalidSetup`] if `nelect == 0`, or `v_ext` length
130    /// disagrees with the grid.
131    pub fn new(grid: Grid1D, v_ext: Vec<f64>, nelect: usize) -> Result<Self, DftError> {
132        if nelect == 0 {
133            return Err(DftError::InvalidSetup("need > 0 electrons".into()));
134        }
135        if v_ext.len() != grid.n {
136            return Err(DftError::InvalidSetup("v_ext length mismatch".into()));
137        }
138        let rho = vec![nelect as f64 / grid.n as f64; grid.n];
139        Ok(Self {
140            grid,
141            v_ext,
142            nelect,
143            rho,
144            last_orbitals: Vec::new(),
145        })
146    }
147
148    /// 1-D Hartree potential `V_H(x) = π ∫ |x − x'| ρ(x') dx'`.
149    ///
150    /// This is the exact 1-D Coulomb kernel (`V_H'' = 2π·ρ`, repulsive). It is
151    /// evaluated by direct summation rather than a finite-difference Poisson
152    /// solve, because a Dirichlet `V = 0` boundary at the grid edges would not
153    /// match the potential of an isolated 1-D charge distribution (which grows
154    /// linearly with distance) and would push the electrons out to the walls.
155    /// The kernel has no free additive constant, so the Hartree energy is
156    /// consistent with the eigenvalue sum in [`Self::total_energy_from`].
157    fn hartree_potential(&self, rho: &[f64]) -> Vec<f64> {
158        let dx = self.grid.dx;
159        let x = self.grid.x();
160        x.iter()
161            .map(|&xi| {
162                let sum: f64 = x
163                    .iter()
164                    .zip(rho)
165                    .map(|(&xj, &rj)| (xi - xj).abs() * rj)
166                    .sum();
167                std::f64::consts::PI * sum * dx
168            })
169            .collect()
170    }
171
172    /// XC potential `V_xc = d(ρ·e_xc)/dρ` via central finite difference.
173    fn xc_potential(&self, rho: &[f64]) -> Vec<f64> {
174        rho.iter()
175            .map(|&r| {
176                let rp = (r + 1e-6).max(0.0);
177                let rm = (r - 1e-6).max(0.0);
178                (lda_xc(rp) - lda_xc(rm)) / (2.0 * 1e-6)
179            })
180            .collect()
181    }
182
183    /// Effective potential `V_eff = V_ext + V_H + V_xc` at the current density.
184    fn effective_potential(&self) -> Vec<f64> {
185        let vh = self.hartree_potential(&self.rho);
186        let vxc = self.xc_potential(&self.rho);
187        self.v_ext
188            .iter()
189            .zip(vh.iter())
190            .zip(vxc.iter())
191            .map(|((&ve, &vh), &vxc)| ve + vh + vxc)
192            .collect()
193    }
194
195    /// Solve the Kohn–Sham equations self-consistently (simple fixed-point
196    /// mixing), up to `max_iter` outer loops. Returns the
197    /// [`KohnShamResult`] (total energy + orbitals + density).
198    ///
199    /// The Hamiltonian is built with a 3-point Laplacian
200    /// `T = −½·d²/dx²` and diagonalized via a dense symmetric eigensolver
201    /// (Jacobi, since `n` is small for 1-D demo systems).
202    pub fn solve(&mut self, max_iter: usize) -> KohnShamResult {
203        let mut total_energy = f64::INFINITY;
204        for _ in 0..max_iter {
205            let v_eff = self.effective_potential();
206            // Build Hamiltonian H = T + V_eff (tridiagonal, dense n×n).
207            let n = self.grid.n;
208            let dx = self.grid.dx;
209            let mut h = vec![vec![0.0_f64; n]; n];
210            let t = 1.0 / (2.0 * dx * dx);
211            for i in 0..n {
212                h[i][i] = 2.0 * t + v_eff[i];
213                if i + 1 < n {
214                    h[i][i + 1] = -t;
215                    h[i + 1][i] = -t;
216                }
217            }
218            // Diagonalize by Jacobi rotation (small n).
219            let (eigvals, eigvecs) = crate::eigen::jacobi(&h);
220            // Fill occupied orbitals (2 per level, spin-polarized pair).
221            let mut new_rho = vec![0.0; n];
222            let mut orbitals: Vec<Vec<f64>> = Vec::new();
223            let mut e_kin = 0.0;
224            let mut filled = 0_usize;
225            for (lv, vec) in eigvals.iter().zip(eigvecs.iter()) {
226                let occ = if filled + 2 <= self.nelect { 2 } else { 0 };
227                if occ == 0 {
228                    break;
229                }
230                filled += occ;
231                orbitals.push(vec.clone());
232                e_kin += occ as f64 * lv;
233                for (j, &c) in vec.iter().enumerate() {
234                    new_rho[j] += occ as f64 * c * c;
235                }
236            }
237            // Mix densities (simple 0.5 mixing) and renormalize to nelect.
238            let mut rho = self.rho.clone();
239            for i in 0..n {
240                rho[i] = 0.5 * rho[i] + 0.5 * new_rho[i];
241            }
242            let s: f64 = rho.iter().sum::<f64>() * dx;
243            if s > 0.0 {
244                for r in &mut rho {
245                    *r *= self.nelect as f64 / s;
246                }
247            }
248            total_energy = self.total_energy_from(e_kin, &rho);
249            self.rho = rho;
250            // Keep the last set of occupied orbitals for the result.
251            self.last_orbitals = orbitals;
252        }
253        KohnShamResult {
254            total_energy,
255            density: self.rho.clone(),
256            orbitals: self.last_orbitals.clone(),
257        }
258    }
259
260    /// Total energy from the occupied-orbital eigenvalue sum `sum_eigen = Σ f_i ε_i`.
261    ///
262    /// The eigenvalues already contain `∫ρ(V_ext + V_H + V_xc)`, so the
263    /// double-counted Hartree and XC potential terms are removed:
264    /// `E = Σ f_i ε_i − E_H + ∫ρ (e_xc − v_xc) dx`.
265    fn total_energy_from(&self, sum_eigen: f64, rho: &[f64]) -> f64 {
266        let dx = self.grid.dx;
267        let vh = self.hartree_potential(rho);
268        let vxc = self.xc_potential(rho);
269        // E_H = ½·∫ ρ·V_H.
270        let e_hartree = 0.5 * rho.iter().zip(&vh).map(|(&r, &v)| r * v).sum::<f64>() * dx;
271        let e_xc_corr: f64 = rho
272            .iter()
273            .zip(&vxc)
274            .map(|(&r, &v)| (lda_xc(r) - v) * r)
275            .sum::<f64>()
276            * dx;
277        sum_eigen - e_hartree + e_xc_corr
278    }
279}
280
281/// Result of a Kohn–Sham solve.
282#[derive(Debug, Clone)]
283pub struct KohnShamResult {
284    /// Total energy (Hartree).
285    pub total_energy: f64,
286    /// Self-consistent density `ρ(x)`.
287    pub density: Vec<f64>,
288    /// Occupied orbital coefficients (truncated to the public surface).
289    pub orbitals: Vec<Vec<f64>>,
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use approx::assert_abs_diff_eq;
296
297    #[test]
298    fn grid_spacing_correct() {
299        let g = Grid1D::new(11, -1.0, 1.0).unwrap();
300        assert_abs_diff_eq!(g.dx, 0.2, epsilon = 1e-12);
301        assert_eq!(g.n, 11);
302    }
303
304    #[test]
305    fn lda_xc_attractive() {
306        assert!(lda_xc(0.5) < 0.0);
307        assert_abs_diff_eq!(lda_xc(0.0), 0.0, epsilon = 1e-12);
308    }
309
310    #[test]
311    fn harmonic_well_solves_finite() {
312        let grid = Grid1D::new(81, -5.0, 5.0).unwrap();
313        let v_ext: Vec<f64> = grid.x().iter().map(|&x| 0.5 * x * x).collect();
314        let mut ks = KohnSham::new(grid, v_ext, 2).unwrap();
315        let res = ks.solve(60);
316        assert!(res.total_energy.is_finite());
317        // Density integrates to the electron count (2) up to mixing tolerance.
318        let int: f64 = res.density.iter().sum::<f64>() * ks.grid.dx;
319        assert!((int - 2.0).abs() < 0.2);
320    }
321
322    #[test]
323    fn jacobi_diagonalizes_diagonal() {
324        let a = vec![vec![2.0, 0.0], vec![0.0, 5.0]];
325        let (e, _v) = crate::eigen::jacobi(&a);
326        assert!((e[0] - 2.0).abs() < 1e-9 || (e[0] - 5.0).abs() < 1e-9);
327    }
328}