Skip to main content

caroli_born/
lib.rs

1//! Disorder-averaged Green's functions in the self-consistent Born approximation (SCBA).
2//!
3//! For a periodic model `H(k)` with a random on-site potential `V`, the averaged Green's
4//! function `⟨G⟩(z) = (1/N_k) Σ_k [z − H(k) − Σ(z)]⁻¹` is built with the self-energy
5//!
6//! ```text
7//! Σ = Σ_MF + Σ₂,   Σ_MF = ⟨V⟩,   Σ₂ = Σ_t w_t V_t ⟨G⟩ V_t,
8//! ```
9//!
10//! where the vertices `(w_t, V_t)` decompose the second cumulant `⟨V⊗V⟩ − ⟨V⟩⊗⟨V⟩` of the
11//! disorder. [`Scba::update`] is the map `Σ₂ ↦ Σ_t w_t V_t ⟨G⟩ V_t`; [`Scba::solve`] iterates it.
12//! [`anderson`] and [`magnetic`] build the vertices of the two thesis disorders.
13//!
14//! From a [`Model`]: [`Scba::from_model`] samples `H(k)` on a uniform grid, a [`Disorder`]
15//! describes the impurities, and [`Scba::self_energy`], [`Scba::sweep`] and [`Scba::dos`] give
16//! the self-energy and the averaged density of states.
17//!
18//! ```
19//! use caroli_born::{Disorder, Scba};
20//! use caroli_model::presets::{BhzParams, bhz};
21//!
22//! // BHZ with Anderson disorder W = 1 on a 64 × 64 k grid, at E = 0.05 + 0.001 i.
23//! let model = bhz(BhzParams::default());
24//! let scba = Scba::from_model(&model, &[64, 64], Disorder::anderson(1.0, 4));
25//! let sol = scba.self_energy(0.05, 1e-3);
26//! assert!(sol.residual < 1e-10);
27//! // The renormalised mass M̄ = M + Re(Σ_E − Σ_H)/2 moves further to the topological side
28//! // (M̄/B > M/B), as in the topological Anderson insulator.
29//! let shift = 0.5 * (sol.sigma[(0, 0)].re - sol.sigma[(1, 1)].re);
30//! assert!(shift / BhzParams::default().b > 0.0);
31//! ```
32
33use caroli_disorder::Moments;
34use caroli_lattice::Region;
35use caroli_model::{CMat, Model, c64};
36use faer::linalg::solvers::DenseSolveCore;
37use rayon::prelude::*;
38
39/// Uniform k grid of `m × n` points `2π (i/m, j/n)` in the first Brillouin zone, listed as the
40/// thesis `k_FBZ` (negative values first: `−π, …, −δ, 0, …, π − δ` for even sizes,
41/// `−π + δ/2 … π − δ/2` symmetric for odd ones); returned as `(kx, ky)` with `kx` varying
42/// fastest.
43pub fn k_grid(m: usize, n: usize) -> Vec<[f64; 2]> {
44    let axis = |len: usize| -> Vec<f64> {
45        let k0 = 2.0 * std::f64::consts::PI / len as f64;
46        // k_FBZ lists (i − len) k0 for the upper indices, then i k0 for i = 0, 1, …; the
47        // positive half has ⌈len/2⌉ values so that odd sizes stay inside (−π, π).
48        let half = len.div_ceil(2);
49        (half..len).map(|i| (i as f64 - len as f64) * k0).chain((0..half).map(|i| i as f64 * k0)).collect()
50    };
51    let (kx, ky) = (axis(m), axis(n));
52    ky.iter().flat_map(|&y| kx.iter().map(move |&x| [x, y])).collect()
53}
54
55/// SCBA problem: `H(k)` on a k grid, mean field `⟨V⟩` and second-order vertices.
56#[derive(Clone, Debug)]
57pub struct Scba {
58    /// `H(k)` at each point of the k grid (orbitals of a unit cell): `⟨G⟩` averages over them.
59    pub hk: Vec<CMat>,
60    /// Mean field `Σ_MF = ⟨V⟩`.
61    pub mean_field: CMat,
62    /// Vertices `(w_t, V_t)` of the second cumulant: `Σ₂ = Σ_t w_t V_t ⟨G⟩ V_t`.
63    pub vertices: Vec<(f64, CMat)>,
64}
65
66/// Result of [`Scba::solve`].
67#[derive(Clone, Debug)]
68pub struct Solution {
69    /// Second-order self-energy `Σ₂` (the mean field is not included).
70    pub sigma: CMat,
71    /// Evaluations of the SCBA map, one k sum each.
72    pub iterations: usize,
73    /// Largest element of the last change of `Σ₂`.
74    pub residual: f64,
75}
76
77fn identity_minus(z: c64, h: &CMat) -> CMat {
78    let n = h.nrows();
79    CMat::from_fn(n, n, |i, j| if i == j { z - h[(i, j)] } else { -h[(i, j)] })
80}
81
82impl Scba {
83    /// `⟨G⟩(z) = (1/N_k) Σ_k [z − H(k) − Σ_MF − Σ₂]⁻¹`. Large grids are summed in parallel, in
84    /// fixed chunks added in order, so the result does not depend on the number of threads.
85    pub fn local_green(&self, z: c64, sigma: &CMat) -> CMat {
86        let n = self.mean_field.nrows();
87        let shift = &self.mean_field + sigma;
88        let partial = |hk: &[CMat]| -> Vec<c64> {
89            let mut acc = vec![c64::new(0.0, 0.0); n * n];
90            let mut a = vec![c64::new(0.0, 0.0); n * n];
91            let mut inv = vec![c64::new(0.0, 0.0); n * n];
92            for h in hk {
93                if n <= SMALL {
94                    for j in 0..n {
95                        for i in 0..n {
96                            let d = if i == j { z } else { c64::new(0.0, 0.0) };
97                            a[i + n * j] = d - h[(i, j)] - shift[(i, j)];
98                        }
99                    }
100                    gauss_jordan_inverse(n, &mut a, &mut inv);
101                    acc.iter_mut().zip(&inv).for_each(|(s, x)| *s += x);
102                } else {
103                    let m = identity_minus(z, h) - &shift;
104                    let g = m.partial_piv_lu().inverse();
105                    for j in 0..n {
106                        for i in 0..n {
107                            acc[i + n * j] += g[(i, j)];
108                        }
109                    }
110                }
111            }
112            acc
113        };
114        let acc = if self.hk.len() >= 2 * K_CHUNK {
115            let parts: Vec<Vec<c64>> = self.hk.par_chunks(K_CHUNK).map(partial).collect();
116            let mut acc = vec![c64::new(0.0, 0.0); n * n];
117            for p in &parts {
118                acc.iter_mut().zip(p).for_each(|(s, x)| *s += x);
119            }
120            acc
121        } else {
122            partial(&self.hk)
123        };
124        let scale = 1.0 / self.hk.len() as f64;
125        CMat::from_fn(n, n, |i, j| acc[i + n * j] * scale)
126    }
127
128    /// One SCBA map: `Σ_t w_t V_t ⟨G⟩(z; Σ₂) V_t`.
129    pub fn update(&self, z: c64, sigma: &CMat) -> CMat {
130        let g = self.local_green(z, sigma);
131        let n = g.nrows();
132        let mut out = CMat::zeros(n, n);
133        for (w, v) in &self.vertices {
134            let t = v * &g * v;
135            out += CMat::from_fn(n, n, |i, j| c64::new(*w, 0.0) * t[(i, j)]);
136        }
137        out
138    }
139
140    /// Fixed-point iteration `Σ ← (1 − p) Σ + p F(Σ)` from `guess` until the largest change
141    /// of an element is below `tol` (at most `max_iter` steps). A non-finite update stops the
142    /// iteration with a NaN residual.
143    pub fn solve(&self, z: c64, guess: &CMat, mixing: f64, tol: f64, max_iter: usize) -> Solution {
144        let mut sigma = guess.clone();
145        let mut residual = f64::INFINITY;
146        let mut iterations = 0;
147        while residual > tol && iterations < max_iter {
148            let next = self.update(z, &sigma);
149            residual = max_abs_diff(&next, &sigma);
150            sigma = mix(&next, &sigma, mixing);
151            iterations += 1;
152        }
153        Solution { sigma, iterations, residual }
154    }
155}
156
157impl Scba {
158    /// Fixed point `Σ₂ = F(Σ₂)` by Anderson acceleration (Anderson mixing, also known as DIIS)
159    /// on the residual `F(Σ) − Σ` with the last `depth` iterates, from `guess`, until the
160    /// largest change of an element is below `tol`. It needs far fewer k sums than
161    /// [`Self::solve`]. When the extrapolation misbehaves (non-finite values, a residual that
162    /// grows tenfold), the history is dropped and a plain step taken.
163    pub fn solve_anderson(&self, z: c64, guess: &CMat, depth: usize, tol: f64, max_iter: usize) -> Solution {
164        let n = guess.nrows();
165        let flat = |m: &CMat| -> Vec<f64> {
166            (0..n * n).flat_map(|k| [m[(k % n, k / n)].re, m[(k % n, k / n)].im]).collect()
167        };
168        let unflat =
169            |v: &[f64]| CMat::from_fn(n, n, |i, j| c64::new(v[2 * (i + n * j)], v[2 * (i + n * j) + 1]));
170        // NaN-propagating maximum: a failed update must not look converged.
171        let residual = |f: &[f64]| {
172            f.as_chunks::<2>()
173                .0
174                .iter()
175                .map(|[re, im]| re.hypot(*im))
176                .fold(0.0, |m: f64, d| if d.is_nan() || m.is_nan() { f64::NAN } else { m.max(d) })
177        };
178        let mut x = flat(guess);
179        let mut g = flat(&self.update(z, guess));
180        let mut f: Vec<f64> = g.iter().zip(&x).map(|(a, b)| a - b).collect();
181        let (mut dfs, mut dgs): (Vec<Vec<f64>>, Vec<Vec<f64>>) = (Vec::new(), Vec::new());
182        let mut iterations = 1;
183        let mut res = residual(&f);
184        while res > tol && iterations < max_iter {
185            let mut next = g.clone();
186            if !dfs.is_empty()
187                && let Some(gamma) = least_squares(&dfs, &f)
188            {
189                for (k, gk) in gamma.iter().enumerate() {
190                    next.iter_mut().zip(&dgs[k]).for_each(|(a, d)| *a -= gk * d);
191                }
192            }
193            if next.iter().any(|v| !v.is_finite()) {
194                next.clone_from(&g);
195                dfs.clear();
196                dgs.clear();
197            }
198            let g_next = flat(&self.update(z, &unflat(&next)));
199            let f_next: Vec<f64> = g_next.iter().zip(&next).map(|(a, b)| a - b).collect();
200            let res_next = residual(&f_next);
201            iterations += 1;
202            if res_next.is_nan() || res_next >= 10.0 * res {
203                // Restart from a plain step.
204                dfs.clear();
205                dgs.clear();
206            } else {
207                dfs.push(f_next.iter().zip(&f).map(|(a, b)| a - b).collect());
208                dgs.push(g_next.iter().zip(&g).map(|(a, b)| a - b).collect());
209                if dfs.len() > depth {
210                    dfs.remove(0);
211                    dgs.remove(0);
212                }
213            }
214            (x, g, f, res) = (next, g_next, f_next, res_next);
215        }
216        let _ = x;
217        Solution { sigma: unflat(&g), iterations, residual: res }
218    }
219}
220
221/// `γ` minimising `‖f − Σ_k γ_k df_k‖` (normal equations, lightly regularised), or `None` if
222/// singular.
223fn least_squares(dfs: &[Vec<f64>], f: &[f64]) -> Option<Vec<f64>> {
224    let m = dfs.len();
225    let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| x * y).sum::<f64>();
226    let mut a = vec![0.0; m * m];
227    let mut b = vec![0.0; m];
228    for i in 0..m {
229        b[i] = dot(&dfs[i], f);
230        for j in 0..m {
231            a[i * m + j] = dot(&dfs[i], &dfs[j]);
232        }
233    }
234    let trace: f64 = (0..m).map(|i| a[i * m + i]).sum();
235    if trace.is_nan() || trace <= 0.0 {
236        return None;
237    }
238    for i in 0..m {
239        a[i * m + i] += 1e-12 * trace / m as f64;
240    }
241    // Gaussian elimination with partial pivoting.
242    for col in 0..m {
243        let piv = (col..m).max_by(|&r, &s| a[r * m + col].abs().total_cmp(&a[s * m + col].abs()))?;
244        if a[piv * m + col].abs() < 1e-300 {
245            return None;
246        }
247        for j in 0..m {
248            a.swap(col * m + j, piv * m + j);
249        }
250        b.swap(col, piv);
251        for r in col + 1..m {
252            let factor = a[r * m + col] / a[col * m + col];
253            for j in col..m {
254                a[r * m + j] -= factor * a[col * m + j];
255            }
256            b[r] -= factor * b[col];
257        }
258    }
259    let mut x = vec![0.0; m];
260    for i in (0..m).rev() {
261        let s: f64 = (i + 1..m).map(|j| a[i * m + j] * x[j]).sum();
262        x[i] = (b[i] - s) / a[i * m + i];
263    }
264    x.iter().all(|v| v.is_finite()).then_some(x)
265}
266
267/// Blocks up to this size are inverted with [`gauss_jordan_inverse`] (no allocation).
268const SMALL: usize = 16;
269
270/// k points per parallel task in [`Scba::local_green`].
271const K_CHUNK: usize = 256;
272
273/// Inverse of the column-major `n × n` matrix `a` (destroyed) into `inv`, by Gauss–Jordan
274/// elimination with partial pivoting.
275fn gauss_jordan_inverse(n: usize, a: &mut [c64], inv: &mut [c64]) {
276    inv.iter_mut()
277        .enumerate()
278        .for_each(|(k, x)| *x = if k % (n + 1) == 0 { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) });
279    for col in 0..n {
280        let pivot =
281            (col..n).max_by(|&r, &s| a[r + n * col].norm().total_cmp(&a[s + n * col].norm())).unwrap();
282        if pivot != col {
283            for j in 0..n {
284                a.swap(pivot + n * j, col + n * j);
285                inv.swap(pivot + n * j, col + n * j);
286            }
287        }
288        let d = c64::new(1.0, 0.0) / a[col + n * col];
289        for j in 0..n {
290            a[col + n * j] *= d;
291            inv[col + n * j] *= d;
292        }
293        for r in 0..n {
294            if r != col {
295                let f = a[r + n * col];
296                if f != c64::new(0.0, 0.0) {
297                    for j in 0..n {
298                        let (ac, ic) = (a[col + n * j], inv[col + n * j]);
299                        a[r + n * j] -= f * ac;
300                        inv[r + n * j] -= f * ic;
301                    }
302                }
303            }
304        }
305    }
306}
307
308/// Disorder seen by the SCBA: the mean field `⟨V⟩` and the vertices `(w_t, V_t)` of the second
309/// cumulant (see the crate documentation).
310#[derive(Clone, Debug)]
311pub struct Disorder {
312    /// Mean field `⟨V⟩` on the orbitals of a unit cell.
313    pub mean_field: CMat,
314    /// Vertices `(w_t, V_t)`: the second cumulant is `⟨V⊗V⟩ − ⟨V⟩⊗⟨V⟩ = Σ_t w_t V_t ⊗ V_t`.
315    pub vertices: Vec<(f64, CMat)>,
316}
317
318impl Disorder {
319    /// Anderson disorder: on-site energies uniform in `[−w/2, w/2]` on every site, the same on
320    /// all `orbitals` of a site.
321    pub fn anderson(w: f64, orbitals: usize) -> Self {
322        let (mean_field, vertices) = anderson(w, orbitals);
323        Self { mean_field, vertices }
324    }
325
326    /// Classical magnetic impurities on a fraction `conc` of the sites, of exchange `j`, with unit
327    /// moments drawn from `moments` (as [`caroli_disorder::MagneticImpurities`]) and coupled
328    /// through the spin matrices `s = (S_x, S_y, S_z)` of the model (e.g.
329    /// [`caroli_model::presets::bhz_spin`]).
330    pub fn magnetic(conc: f64, j: f64, moments: Moments, s: &[CMat; 3]) -> Self {
331        // Every distribution of `Moments` draws n_z uniformly in [a, 1] and a uniform azimuth.
332        let a = match moments {
333            Moments::Isotropic => -1.0,
334            Moments::Cone { theta0 } => theta0.cos(),
335            Moments::Polarized { mz } => 2.0 * mz - 1.0,
336        };
337        let (mz, nz2) = ((1.0 + a) / 2.0, (1.0 + a + a * a) / 3.0);
338        let (mean_field, vertices) = magnetic(conc, j, mz, nz2, s);
339        Self { mean_field, vertices }
340    }
341
342    /// Two independent disorders together: the mean fields add up, and so do the cumulants.
343    pub fn and(mut self, other: Disorder) -> Self {
344        self.mean_field += &other.mean_field;
345        self.vertices.extend(other.vertices);
346        self
347    }
348}
349
350impl Scba {
351    /// The SCBA of `model` with `disorder`, `H(k)` sampled on a uniform grid of the Brillouin
352    /// zone with `grid[a]` points along reciprocal direction `a` (one size per lattice
353    /// direction; the 2D grid is [`k_grid`]). The unit cell holds every sublattice, so the
354    /// matrices of `disorder` act on all the orbitals of a cell.
355    pub fn from_model(model: &Model, grid: &[usize], disorder: Disorder) -> Self {
356        let dim = model.lattice().dim();
357        assert_eq!(grid.len(), dim, "one grid size per lattice direction");
358        let cell = Region::cuboid(model.lattice(), [1, 1, 1]);
359        assert_eq!(
360            disorder.mean_field.nrows(),
361            cell.orbitals(),
362            "disorder matrices of size {} for a cell of {} orbitals",
363            disorder.mean_field.nrows(),
364            cell.orbitals()
365        );
366        let periods: Vec<[i64; 3]> = (0..dim).map(|a| std::array::from_fn(|c| (a == c) as i64)).collect();
367        let points: Vec<Vec<f64>> = match dim {
368            1 => k_grid(grid[0], 1).into_iter().map(|k| vec![k[0]]).collect(),
369            2 => k_grid(grid[0], grid[1]).into_iter().map(|k| k.to_vec()).collect(),
370            _ => {
371                let plane = k_grid(grid[0], grid[1]);
372                k_grid(grid[2], 1)
373                    .into_iter()
374                    .flat_map(|kz| plane.iter().map(move |k| vec![k[0], k[1], kz[0]]))
375                    .collect()
376            }
377        };
378        let hk = points.par_iter().map(|k| model.bloch_hamiltonian(&cell, &periods, k)).collect();
379        Self { hk, mean_field: disorder.mean_field, vertices: disorder.vertices }
380    }
381
382    /// Second-order self-energy `Σ₂` at `energy + iη`, from zero, by Anderson acceleration to a
383    /// largest change of 1e-11 (at most 500 k sums).
384    pub fn self_energy(&self, energy: f64, eta: f64) -> Solution {
385        let n = self.mean_field.nrows();
386        self.solve_anderson(c64::new(energy, eta), &CMat::zeros(n, n), 8, 1e-11, 500)
387    }
388
389    /// [`Self::self_energy`] at each energy, each solution starting from the previous one.
390    pub fn sweep(&self, energies: &[f64], eta: f64) -> Vec<Solution> {
391        let n = self.mean_field.nrows();
392        let mut guess = CMat::zeros(n, n);
393        energies
394            .iter()
395            .map(|&e| {
396                let mut sol = self.solve_anderson(c64::new(e, eta), &guess, 8, 1e-11, 500);
397                if sol.residual.is_nan() || sol.residual > 1e-11 {
398                    // The previous point can lead astray across a band edge: start again from zero.
399                    let fresh = self.self_energy(e, eta);
400                    if fresh.residual < sol.residual || sol.residual.is_nan() {
401                        sol = fresh;
402                    }
403                }
404                if sol.residual.is_finite() {
405                    guess = sol.sigma.clone();
406                }
407                sol
408            })
409            .collect()
410    }
411
412    /// The whole self-energy `Σ_MF + Σ₂`.
413    pub fn total_self_energy(&self, sigma: &CMat) -> CMat {
414        &self.mean_field + sigma
415    }
416
417    /// Averaged density of states per unit cell, `−Im Tr ⟨G⟩(E + iη) / π`, with the self-energy
418    /// `Σ₂ = sigma` (zero for the clean model).
419    pub fn dos(&self, energy: f64, eta: f64, sigma: &CMat) -> f64 {
420        let g = self.local_green(c64::new(energy, eta), sigma);
421        -(0..g.nrows()).map(|i| g[(i, i)].im).sum::<f64>() / std::f64::consts::PI
422    }
423}
424
425/// `p a + (1 − p) b`.
426pub fn mix(a: &CMat, b: &CMat, p: f64) -> CMat {
427    CMat::from_fn(a.nrows(), a.ncols(), |i, j| {
428        c64::new(p, 0.0) * a[(i, j)] + c64::new(1.0 - p, 0.0) * b[(i, j)]
429    })
430}
431
432/// Largest `|a_ij − b_ij|`; NaN if any difference is NaN (a failed update must not look
433/// converged).
434pub fn max_abs_diff(a: &CMat, b: &CMat) -> f64 {
435    let mut m: f64 = 0.0;
436    for j in 0..a.ncols() {
437        for i in 0..a.nrows() {
438            let d = (a[(i, j)] - b[(i, j)]).norm();
439            if d.is_nan() {
440                return f64::NAN;
441            }
442            m = m.max(d);
443        }
444    }
445    m
446}
447
448/// Anderson disorder: uniform on-site energies in `[−w/2, w/2]` on every site, variance `w²/12`,
449/// no mean field.
450pub fn anderson(w: f64, orbitals: usize) -> (CMat, Vec<(f64, CMat)>) {
451    let id = CMat::from_fn(
452        orbitals,
453        orbitals,
454        |i, j| if i == j { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) },
455    );
456    (CMat::zeros(orbitals, orbitals), vec![(w * w / 12.0, id)])
457}
458
459/// Classical magnetic impurities of exchange `j` on a fraction `conc` of the sites, with moments
460/// of mean `⟨n_z⟩ = mz` and second moments `⟨n_z²⟩ = nz2`, `⟨n_x²⟩ = ⟨n_y²⟩ = (1 − nz2)/2`
461/// (axisymmetric about z), coupled through the spin matrices `s = (S_x, S_y, S_z)`.
462///
463/// Second cumulant of `V = p J n·S` with a Bernoulli occupation `p` of mean `conc`:
464/// `conc J² [⟨n_a n_b⟩ − conc ⟨n_a⟩⟨n_b⟩] S_a ⊗ S_b`. For moments uniform in `n_z ∈ [2 mz − 1, 1]`
465/// (the thesis distribution), `nz2 = mz² + (1 − mz)²/3`.
466pub fn magnetic(conc: f64, j: f64, mz: f64, nz2: f64, s: &[CMat; 3]) -> (CMat, Vec<(f64, CMat)>) {
467    let n = s[2].nrows();
468    let mf = CMat::from_fn(n, n, |a, b| c64::new(conc * j * mz, 0.0) * s[2][(a, b)]);
469    let w = conc * j * j;
470    let perp = (1.0 - nz2) / 2.0;
471    let vertices =
472        vec![(w * (nz2 - conc * mz * mz), s[2].clone()), (w * perp, s[0].clone()), (w * perp, s[1].clone())];
473    (mf, vertices)
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479
480    #[test]
481    fn small_inverse() {
482        let n = 4;
483        let m = CMat::from_fn(n, n, |i, j| {
484            c64::new(
485                ((i * 7 + j * 3) % 5) as f64 + if i == j { 3.0 } else { 0.0 },
486                ((i + 2 * j) % 3) as f64 - 1.0,
487            )
488        });
489        let mut a: Vec<c64> = (0..n * n).map(|k| m[(k % n, k / n)]).collect();
490        let mut inv = vec![c64::new(0.0, 0.0); n * n];
491        gauss_jordan_inverse(n, &mut a, &mut inv);
492        let g = CMat::from_fn(n, n, |i, j| inv[i + n * j]);
493        let id = &m * &g;
494        for i in 0..n {
495            for j in 0..n {
496                let e = if i == j { 1.0 } else { 0.0 };
497                assert!((id[(i, j)] - c64::new(e, 0.0)).norm() < 1e-13);
498            }
499        }
500    }
501
502    #[test]
503    fn grid_order_and_extent() {
504        let g = k_grid(4, 2);
505        assert_eq!(g.len(), 8);
506        let pi = std::f64::consts::PI;
507        assert_eq!(g[0], [-pi, -pi]);
508        assert_eq!(g[2][0], 0.0);
509        assert!((g[3][0] - pi / 2.0).abs() < 1e-15);
510        assert_eq!(g[4][1], 0.0);
511        // Odd sizes: symmetric inside (−π, π); a single point is k = 0.
512        let odd: Vec<f64> = k_grid(5, 1).iter().map(|k| k[0] / pi).collect();
513        assert!(odd.iter().zip([-0.8, -0.4, 0.0, 0.4, 0.8]).all(|(a, b)| (a - b).abs() < 1e-15));
514        assert_eq!(k_grid(1, 1), vec![[0.0, 0.0]]);
515    }
516
517    /// Anderson acceleration reaches the fixed point of plain mixing in far fewer steps
518    /// (BHZ with magnetic disorder, a matrix problem).
519    #[test]
520    fn anderson_matches_mixing() {
521        use caroli_model::presets::{BhzParams, GFactors, bhz, bhz_spin};
522        let model = bhz(BhzParams::default());
523        let cell = caroli_lattice::Region::cuboid(model.lattice(), [1, 1, 0]);
524        let hk = k_grid(32, 16)
525            .iter()
526            .map(|k| model.bloch_hamiltonian(&cell, &[[1, 0, 0], [0, 1, 0]], k))
527            .collect();
528        let (mz, conc, j) = (0.8, 0.3, 0.9);
529        let (mean_field, vertices) =
530            magnetic(conc, j, mz, mz * mz + (1.0 - mz).powi(2) / 3.0, &bhz_spin(GFactors::Opposite));
531        let scba = Scba { hk, mean_field, vertices };
532        let z = c64::new(0.05, 1e-3);
533        let zero = CMat::zeros(4, 4);
534        let slow = scba.solve(z, &zero, 0.3, 1e-12, 20000);
535        let fast = scba.solve_anderson(z, &zero, 6, 1e-12, 200);
536        assert!(fast.residual < 1e-12 && slow.residual < 1e-12);
537        assert!(max_abs_diff(&slow.sigma, &fast.sigma) < 1e-10);
538        assert!(fast.iterations * 5 < slow.iterations, "{} vs {}", fast.iterations, slow.iterations);
539    }
540
541    /// A singular local Green's function (real z on an eigenvalue) gives a NaN residual, not a
542    /// converged solution.
543    #[test]
544    fn nan_is_not_convergence() {
545        let one = |x: c64| CMat::from_fn(1, 1, |_, _| x);
546        let scba = Scba {
547            hk: vec![one(c64::new(0.0, 0.0)); 4],
548            mean_field: one(c64::new(0.0, 0.0)),
549            vertices: vec![(0.3, one(c64::new(1.0, 0.0)))],
550        };
551        let zero = one(c64::new(0.0, 0.0));
552        assert!(scba.solve(c64::new(0.0, 0.0), &zero, 0.5, 1e-12, 50).residual.is_nan());
553        assert!(scba.solve_anderson(c64::new(0.0, 0.0), &zero, 4, 1e-12, 50).residual.is_nan());
554    }
555
556    /// Single band, constant H(k) = 0: ⟨G⟩ = 1/(z − Σ) and the SCBA equation
557    /// Σ = w/(z − Σ) has the closed form Σ = (z − sqrt(z² − 4w))/2 (retarded branch).
558    #[test]
559    fn scalar_fixed_point() {
560        let one = |x: c64| CMat::from_fn(1, 1, |_, _| x);
561        let w = 0.3;
562        let scba = Scba {
563            hk: vec![one(c64::new(0.0, 0.0)); 3],
564            mean_field: one(c64::new(0.0, 0.0)),
565            vertices: vec![(w, one(c64::new(1.0, 0.0)))],
566        };
567        let z = c64::new(0.4, 1e-3);
568        let sol = scba.solve(z, &one(c64::new(0.0, -0.1)), 0.5, 1e-13, 2000);
569        let exact = (z - (z * z - c64::new(4.0 * w, 0.0)).sqrt()) / 2.0;
570        assert!((sol.sigma[(0, 0)] - exact).norm() < 1e-10, "{} vs {exact}", sol.sigma[(0, 0)]);
571        assert!(sol.sigma[(0, 0)].im < 0.0);
572    }
573}