Skip to main content

caroli_model/
sparse.rs

1//! Compressed sparse row (CSR) matrices for Hamiltonians of large regions: the operator of the
2//! kernel polynomial method and of Chebyshev time evolution on any geometry, and the format the
3//! GPU backends upload.
4
5use crate::{CMat, c64};
6use rayon::prelude::*;
7
8/// Rows above which [`SparseMatrix::apply`] runs in parallel.
9const PARALLEL_ROWS: usize = 1 << 14;
10
11/// Square complex matrix in CSR form; column indices are `u32` (as on the GPU).
12#[derive(Clone, Debug, PartialEq)]
13pub struct SparseMatrix {
14    /// Number of rows and columns.
15    pub n: usize,
16    /// Entries of row `r` are `row_ptr[r]..row_ptr[r + 1]`.
17    pub row_ptr: Vec<usize>,
18    /// Column of each stored entry, sorted within each row.
19    pub cols: Vec<u32>,
20    /// Value of each stored entry, aligned with `cols`.
21    pub vals: Vec<c64>,
22}
23
24impl SparseMatrix {
25    /// From `(row, column, value)` entries; duplicates are summed, columns sorted in each row.
26    pub fn from_triplets(n: usize, mut entries: Vec<(usize, usize, c64)>) -> Self {
27        assert!(n <= u32::MAX as usize, "dimension {n} exceeds the u32 column index");
28        entries.sort_unstable_by_key(|&(r, c, _)| (r, c));
29        let mut row_ptr = vec![0usize; n + 1];
30        let (mut cols, mut vals) = (Vec::with_capacity(entries.len()), Vec::with_capacity(entries.len()));
31        let mut last: Option<(usize, usize)> = None;
32        for (r, c, v) in entries {
33            assert!(r < n && c < n, "entry ({r}, {c}) outside a {n}×{n} matrix");
34            if last == Some((r, c)) {
35                *vals.last_mut().unwrap() += v;
36            } else {
37                cols.push(c as u32); // c < n ≤ u32::MAX (asserted above)
38                vals.push(v);
39                row_ptr[r + 1] += 1;
40                last = Some((r, c));
41            }
42        }
43        for r in 0..n {
44            row_ptr[r + 1] += row_ptr[r];
45        }
46        Self { n, row_ptr, cols, vals }
47    }
48
49    /// Number of stored entries.
50    pub fn nnz(&self) -> usize {
51        self.vals.len()
52    }
53
54    /// Entries of row `r` as `(column, value)`.
55    pub fn row(&self, r: usize) -> impl Iterator<Item = (usize, c64)> + '_ {
56        (self.row_ptr[r]..self.row_ptr[r + 1]).map(|k| (self.cols[k] as usize, self.vals[k]))
57    }
58
59    /// `y = A x` (rows in parallel for large matrices).
60    pub fn apply(&self, x: &[c64], y: &mut [c64]) {
61        assert_eq!((x.len(), y.len()), (self.n, self.n));
62        let row = |(r, out): (usize, &mut c64)| {
63            let mut acc = c64::new(0.0, 0.0);
64            for k in self.row_ptr[r]..self.row_ptr[r + 1] {
65                acc += self.vals[k] * x[self.cols[k] as usize];
66            }
67            *out = acc;
68        };
69        if self.n >= PARALLEL_ROWS {
70            y.par_iter_mut().enumerate().with_min_len(4096).for_each(row);
71        } else {
72            y.iter_mut().enumerate().for_each(row);
73        }
74    }
75
76    /// `Y = A X` for a block of `m` vectors stored interleaved (`x[row·m + v]`): the matrix is
77    /// read once for the whole block.
78    pub fn apply_block(&self, x: &[c64], y: &mut [c64], m: usize) {
79        assert_eq!((x.len(), y.len()), (self.n * m, self.n * m));
80        let row = |(r, out): (usize, &mut [c64])| {
81            out.iter_mut().for_each(|o| *o = c64::new(0.0, 0.0));
82            for k in self.row_ptr[r]..self.row_ptr[r + 1] {
83                let (c, v) = (self.cols[k] as usize, self.vals[k]);
84                for (o, xv) in out.iter_mut().zip(&x[c * m..(c + 1) * m]) {
85                    *o += v * xv;
86                }
87            }
88        };
89        if self.n >= PARALLEL_ROWS {
90            y.par_chunks_exact_mut(m).enumerate().with_min_len(4096).for_each(row);
91        } else {
92            y.chunks_exact_mut(m).enumerate().for_each(row);
93        }
94    }
95
96    /// The same matrix in dense form.
97    pub fn to_dense(&self) -> CMat {
98        let mut m = CMat::zeros(self.n, self.n);
99        for r in 0..self.n {
100            for (c, v) in self.row(r) {
101                m[(r, c)] += v;
102            }
103        }
104        m
105    }
106
107    /// Gershgorin bounds `(lower, upper)` on the spectrum of a Hermitian matrix.
108    pub fn spectral_bounds(&self) -> (f64, f64) {
109        let mut bounds = (f64::INFINITY, f64::NEG_INFINITY);
110        for r in 0..self.n {
111            let (mut centre, mut radius) = (0.0, 0.0);
112            for (c, v) in self.row(r) {
113                if c == r { centre += v.re } else { radius += v.norm() }
114            }
115            bounds = (bounds.0.min(centre - radius), bounds.1.max(centre + radius));
116        }
117        bounds
118    }
119
120    /// `(A − centre·1) / half_width`, e.g. to map a spectrum into (−1, 1) for Chebyshev
121    /// expansions.
122    pub fn rescaled(&self, centre: f64, half_width: f64) -> Self {
123        let mut entries: Vec<(usize, usize, c64)> =
124            (0..self.n).flat_map(|r| self.row(r).map(move |(c, v)| (r, c, v / half_width))).collect();
125        entries.extend((0..self.n).map(|r| (r, r, c64::new(-centre / half_width, 0.0))));
126        Self::from_triplets(self.n, entries)
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use crate::presets::{BhzParams, bhz};
133    use caroli_lattice::Region;
134
135    /// A one-cell supercell of a chain with first- and second-neighbour hoppings:
136    /// `H(k) = 2 t1 cos k + 2 t2 cos 2k` (the second neighbour lies two periods away).
137    #[test]
138    fn long_hoppings_reach_far_images() {
139        use crate::{CMat, Model, c64};
140        use caroli_lattice::Lattice;
141        let one = |x: f64| CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0));
142        let (t1, t2, k) = (-1.0, 0.3, 0.7);
143        let model = Model::new(Lattice::square(1.0, 1)).hopping(0, 0, [1, 0, 0], one(t1)).hopping(
144            0,
145            0,
146            [2, 0, 0],
147            one(t2),
148        );
149        let cell = Region::cuboid(model.lattice(), [1, 1, 0]);
150        let h = model.bloch_hamiltonian(&cell, &[[1, 0, 0]], &[k]);
151        let exact = 2.0 * t1 * k.cos() + 2.0 * t2 * (2.0 * k).cos();
152        assert!((h[(0, 0)].re - exact).abs() < 1e-14, "{} vs {exact}", h[(0, 0)].re);
153        let s = model.sparse_bloch_hamiltonian(&cell, &[[1, 0, 0]], &[k]);
154        assert!((s.to_dense()[(0, 0)].re - exact).abs() < 1e-14);
155    }
156
157    /// Sheared periods: one cell with periods [1,0,0] and [1,1,0]; the hopping [1,−1,0] is
158    /// 2 T₁ − T₂. `H(k)` at Bloch phases (φ₁, φ₂) is `Σ_offsets t e^{i n·φ}` over both directions.
159    #[test]
160    fn sheared_periods() {
161        use crate::{CMat, Model, c64};
162        use caroli_lattice::Lattice;
163        let one = |x: f64| CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0));
164        let (t, tp) = (-1.0, 0.3);
165        let model = Model::new(Lattice::square(1.0, 1))
166            .hopping(0, 0, [1, 0, 0], one(t))
167            .hopping(0, 0, [0, 1, 0], one(t))
168            .hopping(0, 0, [1, 1, 0], one(tp))
169            .hopping(0, 0, [1, -1, 0], one(tp));
170        let cell = Region::cuboid(model.lattice(), [1, 1, 0]);
171        let (p1, p2) = (0.4, -0.9);
172        let h = model.bloch_hamiltonian(&cell, &[[1, 0, 0], [1, 1, 0]], &[p1, p2]);
173        // Offsets in the period basis: [1,0]=T1, [0,1]=T2−T1, [1,1]=T2, [1,−1]=2T1−T2.
174        let phase = |n1: f64, n2: f64| 2.0 * (n1 * p1 + n2 * p2).cos();
175        let exact = t * phase(1.0, 0.0) + t * phase(-1.0, 1.0) + tp * phase(0.0, 1.0) + tp * phase(2.0, -1.0);
176        assert!((h[(0, 0)].re - exact).abs() < 1e-14, "{} vs {exact}", h[(0, 0)].re);
177    }
178
179    /// Two fundamental domains of the same periodic system give the same spectrum: a slanted
180    /// square supercell {(j, j)} against the straight one {(0, j)}, and a graphene armchair cell
181    /// with half of its sites moved by one period; the Hamiltonians stay Hermitian.
182    #[test]
183    fn any_fundamental_domain() {
184        use crate::{CMat, Model, c64};
185        use caroli_lattice::{Lattice, Site};
186        let one = |x: f64| CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0));
187        let spectrum = |h: &CMat| h.self_adjoint_eigenvalues(faer::Side::Lower).unwrap();
188        let close = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-12);
189        let sq = Model::new(Lattice::square(1.0, 1)).hopping(0, 0, [1, 0, 0], one(-1.0)).hopping(
190            0,
191            0,
192            [0, 1, 0],
193            one(-1.0),
194        );
195        let site = |x: i64, y: i64, sub: usize| Site { cell: [x, y, 0], sub };
196        let straight = Region::from_sites(sq.lattice(), (0..6).map(|j| site(0, j, 0)).collect());
197        let slanted = Region::from_sites(sq.lattice(), (0..6).map(|j| site(j, j, 0)).collect());
198        for k in [0.0, 0.4, 2.1] {
199            let (a, b) = (
200                sq.bloch_hamiltonian(&straight, &[[1, 0, 0]], &[k]),
201                sq.bloch_hamiltonian(&slanted, &[[1, 0, 0]], &[k]),
202            );
203            assert!((&b - b.adjoint()).norm_max() < 1e-15);
204            assert!(close(&spectrum(&a), &spectrum(&b)), "square, k = {k}");
205        }
206        let g = Model::new(Lattice::honeycomb(1.0, 1))
207            .hopping(0, 1, [0, 0, 0], one(-1.0))
208            .hopping(0, 1, [0, -1, 0], one(-1.0))
209            .hopping(0, 1, [1, -1, 0], one(-1.0));
210        let w = 30;
211        let cell: Vec<Site> =
212            (0..w).flat_map(|i| (0..2).flat_map(move |j| (0..2).map(move |s| site(i, j, s)))).collect();
213        let moved: Vec<Site> =
214            cell.iter()
215                .enumerate()
216                .map(|(k, s)| {
217                    if k % 2 == 0 { Site { cell: [s.cell[0] - 1, s.cell[1] + 2, 0], sub: s.sub } } else { *s }
218                })
219                .collect();
220        let (r1, r2) = (Region::from_sites(g.lattice(), cell), Region::from_sites(g.lattice(), moved));
221        for k in [0.0, 0.7] {
222            let (a, b) = (
223                g.bloch_hamiltonian(&r1, &[[-1, 2, 0]], &[k]),
224                g.bloch_hamiltonian(&r2, &[[-1, 2, 0]], &[k]),
225            );
226            assert!((&a - a.adjoint()).norm_max() < 1e-15 && (&b - b.adjoint()).norm_max() < 1e-15);
227            assert!(close(&spectrum(&a), &spectrum(&b)), "graphene, k = {k}");
228        }
229    }
230
231    /// The sparse builders give the dense Hamiltonians, open and twisted-periodic.
232    #[test]
233    fn sparse_matches_dense() {
234        let model = bhz(BhzParams { lambda: 0.1, ..BhzParams::default() });
235        let region = Region::cuboid(model.lattice(), [5, 4, 0]);
236        let open = model.sparse_hamiltonian(&region);
237        assert!((open.to_dense() - model.hamiltonian(&region)).norm_max() < 1e-15);
238        let (periods, phases) = ([[5, 0, 0], [0, 4, 0]], [0.3, -1.1]);
239        let bloch = model.sparse_bloch_hamiltonian(&region, &periods, &phases);
240        assert!((bloch.to_dense() - model.bloch_hamiltonian(&region, &periods, &phases)).norm_max() < 1e-15);
241        // y = A x against the dense product.
242        let x: Vec<_> = (0..bloch.n).map(|i| super::c64::new((i as f64).sin(), 0.3 * i as f64)).collect();
243        let mut y = vec![super::c64::new(0.0, 0.0); bloch.n];
244        bloch.apply(&x, &mut y);
245        let dense = bloch.to_dense();
246        for (r, yr) in y.iter().enumerate() {
247            let d: super::c64 = (0..bloch.n).map(|c| dense[(r, c)] * x[c]).sum();
248            assert!((yr - d).norm() < 1e-12);
249        }
250        // Block product: two interleaved vectors.
251        let x2: Vec<_> = (0..2 * bloch.n).map(|i| super::c64::new((0.1 * i as f64).cos(), 1.0)).collect();
252        let mut y2 = vec![super::c64::new(0.0, 0.0); 2 * bloch.n];
253        bloch.apply_block(&x2, &mut y2, 2);
254        for v in 0..2 {
255            let xv: Vec<_> = x2.iter().skip(v).step_by(2).copied().collect();
256            let mut yv = vec![super::c64::new(0.0, 0.0); bloch.n];
257            bloch.apply(&xv, &mut yv);
258            assert!(yv.iter().zip(y2.iter().skip(v).step_by(2)).all(|(a, b)| (a - b).norm() < 1e-13));
259        }
260        // Gershgorin bounds contain the spectrum.
261        let (lo, hi) = bloch.spectral_bounds();
262        let e = dense.self_adjoint_eigenvalues(faer::Side::Lower).unwrap();
263        assert!(lo <= e[0] && e[e.len() - 1] <= hi);
264    }
265}