Skip to main content

caroli_torus/
lib.rs

1//! Tight-binding Hamiltonians on an `n × n` torus (periodic 2D supercell of a one-cell lattice):
2//! the translation-invariant part is diagonal in k and applied through 2D FFTs, local terms
3//! (disorder, potentials) are applied in real space. This is the operator of the kernel
4//! polynomial method and of split-operator time evolution.
5//!
6//! Wave functions are stored component by component, `ψ[x + n·y + n²·c]` for orbital `c`
7//! (x fastest, as the thesis Fortran arrays `psi(N, N, N_spin)`).
8//!
9//! FFT conventions (those of FFTW, used by the thesis): forward `ψ̂(k) = Σ_x e^{−ik·x} ψ(x)`,
10//! backward `Σ_k e^{+ik·x} ψ̂(k)`, both unnormalised. With these, the k-space multiplier of a
11//! model with hoppings `H_{0,n} = ⟨x| H |x+n⟩` is `M(k) = Σ_n H_{0,n} e^{+ik·n}`
12//! ([`kinetic_from_model`]). k indices are in FFT order: `k_i = 2π i/n` for `2i < n`, else
13//! `2π (i − n)/n`.
14
15use caroli_lattice::Region;
16use caroli_model::{CMat, Model, c64};
17use rayon::prelude::*;
18use rustfft::{Fft, FftPlanner};
19use std::sync::Arc;
20
21/// Grids from this size on are transformed in parallel.
22const PARALLEL_N: usize = 128;
23
24/// k value of FFT index `i` on a ring of `n` sites, in [−π, π) (the Nyquist index of an even
25/// ring is −π).
26pub fn k_value(i: usize, n: usize) -> f64 {
27    let i = if 2 * i < n { i as f64 } else { i as f64 - n as f64 };
28    2.0 * std::f64::consts::PI * i / n as f64
29}
30
31/// 2D FFTs of `n × n` arrays stored x fastest.
32#[derive(Clone)]
33pub struct Fft2 {
34    n: usize,
35    forward: Arc<dyn Fft<f64>>,
36    backward: Arc<dyn Fft<f64>>,
37}
38
39impl std::fmt::Debug for Fft2 {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        write!(f, "Fft2({0}×{0})", self.n)
42    }
43}
44
45impl Fft2 {
46    /// FFTs of `n × n` arrays (plans of length `n`, forward and backward).
47    pub fn new(n: usize) -> Self {
48        let mut planner = FftPlanner::new();
49        Self { n, forward: planner.plan_fft_forward(n), backward: planner.plan_fft_inverse(n) }
50    }
51
52    fn run(&self, plan: &Arc<dyn Fft<f64>>, data: &mut [c64]) {
53        let n = self.n;
54        if n >= PARALLEL_N {
55            // Rows in parallel, then the columns as rows of the transpose.
56            data.par_chunks_exact_mut(n).for_each(|row| plan.process(row));
57            let mut t = vec![c64::new(0.0, 0.0); n * n];
58            t.par_chunks_exact_mut(n).enumerate().for_each(|(x, col)| {
59                for y in 0..n {
60                    col[y] = data[x + n * y];
61                }
62                plan.process(col);
63            });
64            data.par_chunks_exact_mut(n).enumerate().for_each(|(y, row)| {
65                for x in 0..n {
66                    row[x] = t[y + n * x];
67                }
68            });
69            return;
70        }
71        // Along x: contiguous rows.
72        for row in data.chunks_exact_mut(n) {
73            plan.process(row);
74        }
75        // Along y: gather each column.
76        let mut col = vec![c64::new(0.0, 0.0); n];
77        for x in 0..n {
78            for y in 0..n {
79                col[y] = data[x + n * y];
80            }
81            plan.process(&mut col);
82            for y in 0..n {
83                data[x + n * y] = col[y];
84            }
85        }
86    }
87
88    /// Forward transform in place (unnormalised).
89    pub fn forward(&self, data: &mut [c64]) {
90        self.run(&self.forward, data);
91    }
92
93    /// Backward transform in place (unnormalised: forward then backward multiplies by n²).
94    pub fn backward(&self, data: &mut [c64]) {
95        self.run(&self.backward, data);
96    }
97}
98
99/// `M(k) = Σ_n H_{0,n} e^{+ik·n}` on the `n × n` k grid (index `kx + n·ky`, FFT order): the
100/// Bloch blocks of the whole unit cell, any number of sublattices. The site-dependent on-site
101/// terms of the model at the cell of the origin enter too: pass the clean model.
102pub fn kinetic_from_model(model: &Model, n: usize) -> Vec<CMat> {
103    let cell = Region::cuboid(model.lattice(), [1, 1, 0]);
104    (0..n * n)
105        .map(|k| {
106            model.bloch_hamiltonian(&cell, &[[1, 0, 0], [0, 1, 0]], &[k_value(k % n, n), k_value(k / n, n)])
107        })
108        .collect()
109}
110
111/// `H = M(k) + V(x)` on an `n × n` torus with `comps` orbitals per site.
112#[derive(Clone, Debug)]
113pub struct TorusOperator {
114    /// Number of sites along each side of the torus.
115    pub n: usize,
116    /// Orbitals per site: a wave function holds `comps` components of `n²` entries each.
117    pub comps: usize,
118    /// k-space multiplier per k index (`kx + n·ky`).
119    pub kinetic: Vec<CMat>,
120    /// Local matrices on sites `x + n·y`.
121    pub local: Vec<(usize, CMat)>,
122    fft: Fft2,
123}
124
125impl TorusOperator {
126    /// Operator from the multipliers `M(k)` of the `n²` k points (see [`kinetic_from_model`]) and
127    /// the local matrices; every matrix is `comps × comps`.
128    pub fn new(n: usize, comps: usize, kinetic: Vec<CMat>, local: Vec<(usize, CMat)>) -> Self {
129        assert_eq!(kinetic.len(), n * n);
130        Self { n, comps, kinetic, local, fft: Fft2::new(n) }
131    }
132
133    /// Number of entries of a wave function.
134    pub fn len(&self) -> usize {
135        self.n * self.n * self.comps
136    }
137
138    /// Whether a wave function has no entry.
139    pub fn is_empty(&self) -> bool {
140        self.len() == 0
141    }
142
143    /// The 2D FFTs of one component.
144    pub fn fft(&self) -> &Fft2 {
145        &self.fft
146    }
147
148    /// Forward FFT of every component.
149    pub fn to_k(&self, psi: &mut [c64]) {
150        psi.chunks_exact_mut(self.n * self.n).for_each(|c| self.fft.forward(c));
151    }
152
153    /// Backward FFT of every component, divided by n² (inverse of [`Self::to_k`]).
154    pub fn to_x(&self, psi: &mut [c64]) {
155        let norm = (self.n * self.n) as f64;
156        psi.chunks_exact_mut(self.n * self.n).for_each(|c| {
157            self.fft.backward(c);
158            c.iter_mut().for_each(|z| *z /= norm);
159        });
160    }
161
162    /// `out = H ψ`: `to_x(M(k) to_k(ψ))` plus the local terms.
163    pub fn apply(&self, psi: &[c64], out: &mut [c64]) {
164        let (nn, m) = (self.n * self.n, self.comps);
165        let mut k = psi.to_vec();
166        self.to_k(&mut k);
167        out.iter_mut().for_each(|z| *z = c64::new(0.0, 0.0));
168        for (idx, mk) in self.kinetic.iter().enumerate() {
169            for j in 0..m {
170                let mut acc = c64::new(0.0, 0.0);
171                for i in 0..m {
172                    acc += mk[(j, i)] * k[idx + nn * i];
173                }
174                out[idx + nn * j] = acc;
175            }
176        }
177        self.to_x(out);
178        for (site, v) in &self.local {
179            for j in 0..m {
180                let mut acc = c64::new(0.0, 0.0);
181                for i in 0..m {
182                    acc += v[(j, i)] * psi[site + nn * i];
183                }
184                out[site + nn * j] += acc;
185            }
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use caroli_lattice::{Lattice, Site};
194
195    /// FFTs agree with the direct sums and backward(forward(ψ)) = n² ψ.
196    #[test]
197    fn fft_conventions() {
198        let n = 6;
199        let f = Fft2::new(n);
200        let psi: Vec<c64> =
201            (0..n * n).map(|i| c64::new((i as f64 * 0.37).sin(), (i as f64 * 0.11).cos())).collect();
202        let mut a = psi.clone();
203        f.forward(&mut a);
204        let (kx, ky) = (2, 5);
205        let direct: c64 = (0..n * n)
206            .map(|i| {
207                let (x, y) = ((i % n) as f64, (i / n) as f64);
208                psi[i] * c64::from_polar(1.0, -(k_value(kx, n) * x + k_value(ky, n) * y))
209            })
210            .sum();
211        assert!((a[kx + n * ky] - direct).norm() < 1e-12);
212        f.backward(&mut a);
213        assert!(a.iter().zip(&psi).all(|(u, v)| (u / (n * n) as f64 - v).norm() < 1e-13));
214    }
215
216    /// The parallel path gives the same numbers as the serial one.
217    #[test]
218    fn parallel_fft_is_identical() {
219        let n = PARALLEL_N;
220        let psi: Vec<c64> =
221            (0..n * n).map(|i| c64::new((i as f64 * 0.37).sin(), (i as f64 * 0.11).cos())).collect();
222        let f = Fft2::new(n);
223        let mut a = psi.clone();
224        f.forward(&mut a);
225        let mut b = psi.clone();
226        for row in b.chunks_exact_mut(n) {
227            f.forward.process(row);
228        }
229        let mut col = vec![c64::new(0.0, 0.0); n];
230        for x in 0..n {
231            (0..n).for_each(|y| col[y] = b[x + n * y]);
232            f.forward.process(&mut col);
233            (0..n).for_each(|y| b[x + n * y] = col[y]);
234        }
235        assert_eq!(a, b);
236    }
237
238    /// The FFT operator equals the real-space Hamiltonian of the periodic supercell.
239    #[test]
240    fn matches_real_space_hamiltonian() {
241        let n = 4;
242        let lat = Lattice::square(1.0, 2);
243        let t = CMat::from_fn(2, 2, |i, j| c64::new(-1.0 + 0.3 * i as f64, 0.2 * j as f64 - 0.1));
244        let e = CMat::from_fn(2, 2, |i, j| {
245            if i == j { c64::new(0.5 - i as f64, 0.0) } else { c64::new(0.2, if i < j { 0.1 } else { -0.1 }) }
246        });
247        let model = Model::new(lat.clone()).onsite(0, e).hopping(0, 0, [1, 0, 0], t.clone()).hopping(
248            0,
249            0,
250            [0, 1, 0],
251            t.adjoint().to_owned(),
252        );
253        let local = vec![(5, CMat::from_fn(2, 2, |i, j| c64::new(if i == j { 0.7 } else { 0.0 }, 0.0)))];
254        let op = TorusOperator::new(n, 2, kinetic_from_model(&model, n), local.clone());
255        // Real space: the n × n supercell repeated in x and y.
256        let cells = Region::from_sites(
257            &lat,
258            (0..n as i64)
259                .flat_map(|y| (0..n as i64).map(move |x| Site { cell: [x, y, 0], sub: 0 }))
260                .collect(),
261        );
262        let mut h = model.bloch_hamiltonian(&cells, &[[n as i64, 0, 0], [0, n as i64, 0]], &[0.0, 0.0]);
263        for (s, v) in &local {
264            for i in 0..2 {
265                for j in 0..2 {
266                    h[(2 * s + i, 2 * s + j)] += v[(i, j)];
267                }
268            }
269        }
270        let psi: Vec<c64> =
271            (0..2 * n * n).map(|i| c64::new((i as f64).cos(), (0.3 * i as f64).sin())).collect();
272        let mut out = vec![c64::new(0.0, 0.0); psi.len()];
273        op.apply(&psi, &mut out);
274        // Region order: site s = x + n y, orbitals interleaved; torus order: component-major.
275        for s in 0..n * n {
276            for c in 0..2 {
277                let direct: c64 = (0..n * n)
278                    .flat_map(|s2| (0..2).map(move |c2| (s2, c2)))
279                    .map(|(s2, c2)| h[(2 * s + c, 2 * s2 + c2)] * psi[s2 + n * n * c2])
280                    .sum();
281                assert!((out[s + n * n * c] - direct).norm() < 1e-12, "site {s} comp {c}");
282            }
283        }
284    }
285}