Skip to main content

caroli_dynamics/
lib.rs

1//! Time evolution on periodic 2D supercells by the split-operator method:
2//! `ψ(t + dt) = U_V U_K(t) U_V ψ(t)` with `U_V = exp(−i V dt/2)` local in real space and
3//! `U_K(k, t) = exp(−i H_K(k, t) dt)` diagonal in k (FFTs from [`caroli_torus`]).
4//!
5//! The k-space step is supplied per time step, so time-dependent fields (vector potentials,
6//! `k → k − A(t)`) only change `U_K`. [`exp_i`] builds the exponentials of Hermitian blocks.
7//!
8//! [`Chebyshev`] propagates with any Hamiltonian given as a product `H̃ψ` (sparse matrices of
9//! any geometry, GPU operators): `exp(−iH dt)` expanded in Chebyshev polynomials of the
10//! rescaled `H̃ = (H − centre)/half_width`, exact to the requested tolerance for any `dt`.
11
12pub mod accelerated;
13pub mod driven;
14pub mod torus;
15
16pub use driven::{Driven, VectorPotential, constant_force};
17pub use torus::{Evolution, Record, Torus};
18
19use caroli_model::{CMat, c64};
20use caroli_torus::Fft2;
21use faer::Side;
22
23/// `exp(−i h τ)` for a Hermitian block `h` (by diagonalisation).
24pub fn exp_i(h: &CMat, tau: f64) -> CMat {
25    let evd = h.self_adjoint_eigen(Side::Lower).expect("Hermitian eigenproblem");
26    let (s, u) = (evd.S(), evd.U());
27    let n = h.nrows();
28    let phases: Vec<c64> = (0..n).map(|k| c64::from_polar(1.0, -s[k].re * tau)).collect();
29    CMat::from_fn(n, n, |i, j| (0..n).map(|k| u[(i, k)] * phases[k] * u[(j, k)].conj()).sum())
30}
31
32/// Bessel functions `J_0(x) … J_{count−1}(x)` (Miller's backward recurrence, normalised by
33/// `J_0 + 2 Σ J_2k = 1`).
34pub fn bessel_j(x: f64, count: usize) -> Vec<f64> {
35    if x == 0.0 {
36        return (0..count).map(|n| if n == 0 { 1.0 } else { 0.0 }).collect();
37    }
38    let ax = x.abs();
39    if ax < 1e-30 {
40        // Leading term (x/2)^n / n!; the next one is smaller by (x/2)² < 1e-60.
41        let mut term = 1.0;
42        return (0..count)
43            .map(|n| {
44                if n > 0 {
45                    term *= x / 2.0 / n as f64;
46                }
47                term
48            })
49            .collect();
50    }
51    let top = count.max(ax as usize) + 30 + (10.0 * ax.cbrt()) as usize;
52    let mut j = vec![0.0; top + 2];
53    j[top] = 1e-300;
54    for n in (1..=top).rev() {
55        j[n - 1] = 2.0 * n as f64 / ax * j[n] - j[n + 1];
56        if j[n - 1].abs() > 1e250 {
57            j.iter_mut().for_each(|v| *v *= 1e-250);
58        }
59    }
60    let norm = j[0] + 2.0 * j.iter().skip(2).step_by(2).sum::<f64>();
61    j.truncate(count);
62    j.iter_mut().enumerate().for_each(|(n, v)| {
63        *v /= norm;
64        // J_n(−x) = (−1)^n J_n(x).
65        if x < 0.0 && n % 2 == 1 {
66            *v = -*v;
67        }
68    });
69    j
70}
71
72/// Propagator `ψ ← exp(−iH dt) ψ` by the Chebyshev expansion
73/// `exp(−iH dt) = e^{−i·centre·dt} Σ_n (2 − δ_n0) (−i)^n J_n(half_width·dt) T_n(H̃)`.
74#[derive(Clone, Debug)]
75pub struct Chebyshev {
76    /// Expansion coefficients, the global phase included.
77    pub coefficients: Vec<c64>,
78}
79
80impl Chebyshev {
81    /// Terms up to `|J_n| < tol` (the spectrum of `H̃` must lie in [−1, 1]).
82    pub fn new(dt: f64, centre: f64, half_width: f64, tol: f64) -> Self {
83        let tau = half_width * dt;
84        let guess = (1.3 * tau.abs()) as usize + 40 + (8.0 * tau.abs().cbrt()) as usize;
85        let j = bessel_j(tau, guess);
86        let last = j.iter().rposition(|v| v.abs() > tol).unwrap_or(0);
87        let phase = c64::from_polar(1.0, -centre * dt);
88        let coefficients = (0..=last.max(1))
89            .map(|n| {
90                let minus_i_n =
91                    [c64::new(1.0, 0.0), c64::new(0.0, -1.0), c64::new(-1.0, 0.0), c64::new(0.0, 1.0)][n % 4];
92                phase * minus_i_n * if n == 0 { j[0] } else { 2.0 * j[n] }
93            })
94            .collect();
95        Self { coefficients }
96    }
97
98    /// One step: `ψ ← Σ_n c_n T_n(H̃) ψ` with `apply(x, y)` setting `y = H̃ x`. `ψ` may hold a
99    /// block of wave functions if `apply` acts on the block (e.g. `SparseMatrix::apply_block`).
100    pub fn step(&self, apply: impl Fn(&[c64], &mut [c64]), psi: &mut [c64]) {
101        use rayon::prelude::*;
102        const CHUNK: usize = 1 << 14;
103        let c = &self.coefficients;
104        let n = psi.len();
105        let mut t0 = psi.to_vec();
106        let mut t1 = vec![c64::new(0.0, 0.0); n];
107        apply(&t0, &mut t1);
108        psi.par_chunks_mut(CHUNK).zip(t0.par_chunks(CHUNK)).zip(t1.par_chunks(CHUNK)).for_each(
109            |((p, a), b)| {
110                for ((p, a), b) in p.iter_mut().zip(a).zip(b) {
111                    *p = c[0] * a + c[1] * b;
112                }
113            },
114        );
115        let mut t2 = vec![c64::new(0.0, 0.0); n];
116        for &ck in &c[2..] {
117            apply(&t1, &mut t2);
118            psi.par_chunks_mut(CHUNK).zip(t2.par_chunks_mut(CHUNK)).zip(t0.par_chunks(CHUNK)).for_each(
119                |((p, next), prev)| {
120                    for ((p, x), q) in p.iter_mut().zip(next.iter_mut()).zip(prev) {
121                        *x = 2.0 * *x - q;
122                        *p += ck * *x;
123                    }
124                },
125            );
126            // (T_{n−1}, T_n) ← (T_n, T_{n+1}).
127            std::mem::swap(&mut t0, &mut t1);
128            std::mem::swap(&mut t1, &mut t2);
129        }
130    }
131}
132
133/// A time-dependent Hamiltonian for [`magnus4_step`].
134pub trait TimeDependent {
135    /// `y = Σ_i w_i H(t_i) x` for `stages = [(t_i, w_i)]`.
136    fn apply(&self, stages: &[(f64, f64)], x: &[c64], y: &mut [c64]);
137    /// Bounds `(lower, upper)` on the spectrum of `H(t)` at every `t`.
138    fn bounds(&self) -> (f64, f64);
139}
140
141/// One step of the fourth-order commutator-free Magnus integrator (Blanes & Moan, 2006):
142/// `U(t + dt, t) ≈ exp(−i dt B₂) exp(−i dt B₁)`, `B₁ = α₂ H(t₁) + α₁ H(t₂)`,
143/// `B₂ = α₁ H(t₁) + α₂ H(t₂)`, `t₁,₂ = t + (1/2 ∓ √3/6) dt`, `α₁,₂ = (3 ∓ 2√3)/12`.
144/// Each exponential is a [`Chebyshev`] expansion to `tol`: the global error is O(dt⁴), with no
145/// splitting error between kinetic and potential terms.
146pub fn magnus4_step(h: &impl TimeDependent, psi: &mut [c64], t: f64, dt: f64, tol: f64) {
147    let s3 = 3f64.sqrt();
148    let (t1, t2) = (t + (0.5 - s3 / 6.0) * dt, t + (0.5 + s3 / 6.0) * dt);
149    let (a1, a2) = ((3.0 - 2.0 * s3) / 12.0, (3.0 + 2.0 * s3) / 12.0);
150    let (lo, hi) = h.bounds();
151    for stages in [[(t1, a2), (t2, a1)], [(t1, a1), (t2, a2)]] {
152        // Spectrum of Σ w_i H(t_i) (a weight is negative).
153        let (blo, bhi) = stages
154            .iter()
155            .fold((0.0, 0.0), |(l, u), &(_, w)| (l + (w * lo).min(w * hi), u + (w * lo).max(w * hi)));
156        let (centre, half) = ((bhi + blo) / 2.0, ((bhi - blo) / 2.0 * 1.01).max(1e-300));
157        let cheb = Chebyshev::new(dt, centre, half, tol);
158        cheb.step(
159            |x, y| {
160                h.apply(&stages, x, y);
161                y.iter_mut().zip(x).for_each(|(y, x)| *y = (*y - centre * x) / half);
162            },
163            psi,
164        );
165    }
166}
167
168/// Multiplies the wave function (`ψ[site + n²·c]`) by a block on each listed site.
169pub fn apply_local(psi: &mut [c64], nn: usize, comps: usize, blocks: &[(usize, CMat)]) {
170    let mut tmp = vec![c64::new(0.0, 0.0); comps];
171    for (site, b) in blocks {
172        for (j, t) in tmp.iter_mut().enumerate() {
173            *t = (0..comps).map(|i| b[(j, i)] * psi[site + nn * i]).sum();
174        }
175        for (j, t) in tmp.iter().enumerate() {
176            psi[site + nn * j] = *t;
177        }
178    }
179}
180
181/// Multiplies a k-space wave function by one block per k.
182pub fn apply_k(psi_k: &mut [c64], comps: usize, blocks: &[CMat]) {
183    let nn = blocks.len();
184    let mut tmp = vec![c64::new(0.0, 0.0); comps];
185    for (k, b) in blocks.iter().enumerate() {
186        for (j, t) in tmp.iter_mut().enumerate() {
187            *t = (0..comps).map(|i| b[(j, i)] * psi_k[k + nn * i]).sum();
188        }
189        for (j, t) in tmp.iter().enumerate() {
190            psi_k[k + nn * j] = *t;
191        }
192    }
193}
194
195/// Split-operator propagator on an `n × n` torus with `comps` orbitals per site.
196#[derive(Clone, Debug)]
197pub struct SplitOperator {
198    /// Side of the torus (`n × n` sites).
199    pub n: usize,
200    /// Orbitals per site; the wave function is stored orbital by orbital, `ψ[site + n²·c]`.
201    pub comps: usize,
202    /// `exp(−i V dt/2)` on the sites carrying a potential (identity elsewhere).
203    pub half_potential: Vec<(usize, CMat)>,
204    fft: Fft2,
205}
206
207impl SplitOperator {
208    /// Propagator with the local potential `v` (site, Hermitian block) and time step `dt`.
209    /// Blocks listed for the same site are summed before exponentiation.
210    pub fn new(n: usize, comps: usize, v: &[(usize, CMat)], dt: f64) -> Self {
211        let mut summed: std::collections::BTreeMap<usize, CMat> = std::collections::BTreeMap::new();
212        for (s, b) in v {
213            summed.entry(*s).and_modify(|m| *m += b).or_insert_with(|| b.clone());
214        }
215        let half_potential = summed.into_iter().map(|(s, b)| (s, exp_i(&b, dt / 2.0))).collect();
216        Self { n, comps, half_potential, fft: Fft2::new(n) }
217    }
218
219    /// Same, with the half-step blocks given directly.
220    pub fn with_half_steps(n: usize, comps: usize, half_potential: Vec<(usize, CMat)>) -> Self {
221        Self { n, comps, half_potential, fft: Fft2::new(n) }
222    }
223
224    /// Forward FFT of every component (k space, unnormalised).
225    pub fn to_k(&self, psi: &mut [c64]) {
226        psi.chunks_exact_mut(self.n * self.n).for_each(|c| self.fft.forward(c));
227    }
228
229    /// Backward FFT of every component divided by n².
230    pub fn to_x(&self, psi: &mut [c64]) {
231        let norm = (self.n * self.n) as f64;
232        psi.chunks_exact_mut(self.n * self.n).for_each(|c| {
233            self.fft.backward(c);
234            c.iter_mut().for_each(|z| *z /= norm);
235        });
236    }
237
238    /// One step on a real-space wave function: `U_V`, FFT, `U_K`, inverse FFT, `U_V`.
239    pub fn step(&self, psi_x: &mut [c64], kinetic_step: &[CMat]) {
240        let nn = self.n * self.n;
241        apply_local(psi_x, nn, self.comps, &self.half_potential);
242        self.to_k(psi_x);
243        apply_k(psi_x, self.comps, kinetic_step);
244        self.to_x(psi_x);
245        apply_local(psi_x, nn, self.comps, &self.half_potential);
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    /// Fourth order: halving dt divides the error by about 16 (dense driven 6-level system,
254    /// reference with dt/16).
255    #[test]
256    fn magnus4_is_fourth_order() {
257        struct Driven(CMat, CMat);
258        #[allow(clippy::needless_range_loop)] // dense products, indices read best
259        impl TimeDependent for Driven {
260            fn apply(&self, stages: &[(f64, f64)], x: &[c64], y: &mut [c64]) {
261                let n = x.len();
262                y.iter_mut().for_each(|v| *v = c64::new(0.0, 0.0));
263                for &(t, w) in stages {
264                    let f = (1.3 * t).cos();
265                    for i in 0..n {
266                        for j in 0..n {
267                            y[i] += w * (self.0[(i, j)] + f * self.1[(i, j)]) * x[j];
268                        }
269                    }
270                }
271            }
272            fn bounds(&self) -> (f64, f64) {
273                let r = |m: &CMat| {
274                    (0..m.nrows())
275                        .map(|i| (0..m.ncols()).map(|j| m[(i, j)].norm()).sum::<f64>())
276                        .fold(0.0, f64::max)
277                };
278                let b = r(&self.0) + r(&self.1);
279                (-b, b)
280            }
281        }
282        let n = 6;
283        let herm = |seed: f64| {
284            let a = CMat::from_fn(n, n, |i, j| {
285                c64::new((seed * (i * 7 + j) as f64).sin(), (seed * (i + 3 * j) as f64).cos())
286            });
287            CMat::from_fn(n, n, |i, j| (a[(i, j)] + a[(j, i)].conj()) * 0.5)
288        };
289        let h = Driven(herm(0.37), herm(1.11));
290        let psi0: Vec<c64> =
291            (0..n).map(|i| c64::new(1.0 / (n as f64).sqrt(), 0.0) * c64::from_polar(1.0, i as f64)).collect();
292        let evolve = |dt: f64| {
293            let mut psi = psi0.clone();
294            let steps = (2.0 / dt).round() as usize;
295            for k in 0..steps {
296                magnus4_step(&h, &mut psi, k as f64 * dt, dt, 1e-15);
297            }
298            psi
299        };
300        let reference = evolve(0.0125);
301        let err =
302            |dt: f64| evolve(dt).iter().zip(&reference).map(|(a, b)| (a - b).norm_sqr()).sum::<f64>().sqrt();
303        let (e1, e2) = (err(0.2), err(0.1));
304        assert!(e1 / e2 > 12.0 && e1 / e2 < 20.0, "errors {e1:e}, {e2:e}");
305        let norm: f64 = reference.iter().map(|z| z.norm_sqr()).sum();
306        assert!((norm - 1.0).abs() < 1e-13);
307    }
308
309    /// Blocks listed twice for a site act as their sum.
310    #[test]
311    fn split_operator_sums_duplicate_sites() {
312        let m = |a: f64, b: f64| {
313            CMat::from_fn(2, 2, |i, j| {
314                c64::new(if i == j { a * if i == 0 { 1.0 } else { -1.0 } } else { b }, 0.0)
315            })
316        };
317        let twice = SplitOperator::new(4, 2, &[(5, m(0.0, 0.8)), (5, m(0.6, 0.0))], 0.1);
318        let once = SplitOperator::new(4, 2, &[(5, m(0.6, 0.8))], 0.1);
319        assert_eq!(twice.half_potential.len(), 1);
320        assert!((&twice.half_potential[0].1 - &once.half_potential[0].1).norm_max() < 1e-15);
321    }
322
323    #[test]
324    fn bessel_values() {
325        // J_0(1), J_1(1), J_5(1) and J_0(10), J_12(10) (Abramowitz & Stegun).
326        let j = bessel_j(1.0, 6);
327        assert!((j[0] - 0.765_197_686_557_966_6).abs() < 1e-15);
328        assert!((j[1] - 0.440_050_585_744_933_5).abs() < 1e-15);
329        assert!((j[5] - 2.497_577_302_112_344e-4).abs() < 1e-17);
330        let tiny = bessel_j(1e-60, 3);
331        assert!(
332            (tiny[0] - 1.0).abs() < 1e-15
333                && (tiny[1] - 5e-61).abs() < 1e-75
334                && (tiny[2] - 1.25e-121).abs() < 1e-135
335        );
336        let j = bessel_j(10.0, 13);
337        assert!((j[0] + 0.245_935_764_451_348_3).abs() < 1e-14);
338        assert!((j[12] - 6.337_025_497_015_6e-2).abs() < 1e-13);
339    }
340
341    /// Chebyshev propagation of a BHZ flake against exact exponentiation, for a short and a
342    /// long time step.
343    #[test]
344    fn chebyshev_matches_exact_exponential() {
345        use caroli_lattice::Region;
346        use caroli_model::presets::{BhzParams, bhz};
347        let model = bhz(BhzParams { lambda: 0.2, ..BhzParams::default() });
348        let region = Region::cuboid(model.lattice(), [5, 4, 0]);
349        let h = model.sparse_hamiltonian(&region);
350        let (lo, hi) = h.spectral_bounds();
351        let (centre, half) = ((hi + lo) / 2.0, (hi - lo) / 2.0 * 1.01);
352        let scaled = h.rescaled(centre, half);
353        let dense = h.to_dense();
354        let psi0: Vec<c64> =
355            (0..h.n).map(|i| c64::new((0.7 * i as f64).cos(), (0.2 * i as f64).sin())).collect();
356        for dt in [0.05, 7.5] {
357            let mut psi = psi0.clone();
358            Chebyshev::new(dt, centre, half, 1e-15).step(|x, y| scaled.apply(x, y), &mut psi);
359            let u = exp_i(&dense, dt);
360            let exact: Vec<c64> = (0..h.n).map(|r| (0..h.n).map(|c| u[(r, c)] * psi0[c]).sum()).collect();
361            let err = psi.iter().zip(&exact).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
362            assert!(err < 1e-12, "dt {dt}: {err:e}");
363        }
364    }
365
366    /// exp(−i σ_x τ) = cos τ − i σ_x sin τ.
367    #[test]
368    fn exponential_of_pauli() {
369        let sx = CMat::from_fn(2, 2, |i, j| if i != j { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) });
370        let u = exp_i(&sx, 0.7);
371        assert!((u[(0, 0)] - c64::new(0.7f64.cos(), 0.0)).norm() < 1e-14);
372        assert!((u[(0, 1)] - c64::new(0.0, -0.7f64.sin())).norm() < 1e-14);
373    }
374
375    /// A free particle: without potential, a step is exact and conserves the norm, and the
376    /// k-space phases accumulate as exp(−i ε_k t).
377    #[test]
378    fn unitary_steps() {
379        let n = 8;
380        let prop = SplitOperator::new(n, 1, &[(3, CMat::from_fn(1, 1, |_, _| c64::new(0.4, 0.0)))], 0.05);
381        let kin: Vec<CMat> = (0..n * n)
382            .map(|k| exp_i(&CMat::from_fn(1, 1, |_, _| c64::new((k as f64 * 0.1).cos(), 0.0)), 0.05))
383            .collect();
384        let mut psi: Vec<c64> =
385            (0..n * n).map(|i| c64::new((i as f64).sin(), (0.5 * i as f64).cos())).collect();
386        let norm0: f64 = psi.iter().map(|z| z.norm_sqr()).sum();
387        for _ in 0..50 {
388            prop.step(&mut psi, &kin);
389        }
390        let norm: f64 = psi.iter().map(|z| z.norm_sqr()).sum();
391        assert!((norm - norm0).abs() < 1e-11 * norm0);
392    }
393}