Skip to main content

caroli_model/
lib.rs

1//! Tight-binding models on a [`Lattice`] and the matrices they produce on a [`Region`].
2//!
3//! A [`Model`] holds an on-site matrix per sublattice and a list of [`Hopping`]s
4//! `⟨(R, from)| H |(R + offset, to)⟩`. Extra on-site terms that depend on the site (disorder,
5//! potentials) are added through [`OnSite`], and a magnetic field through [`Peierls`] phases
6//! (see [`gauge`]). The model builds dense Hamiltonians of finite regions, Bloch Hamiltonians of
7//! partially periodic systems and the blocks used by transport.
8
9use caroli_lattice::{Cell, Lattice, Region, Site, Vec3};
10use faer::Mat;
11pub use faer::c64;
12
13pub mod continuum;
14pub mod gamma;
15pub mod presets;
16pub mod sparse;
17
18pub use sparse::SparseMatrix;
19
20/// Complex dense matrix (orbital blocks and Hamiltonians).
21pub type CMat = Mat<c64>;
22
23/// A matrix argument of [`Model`]: a [`CMat`], or a number for a single orbital.
24pub trait IntoMatrix {
25    /// The matrix itself, or the 1 × 1 matrix of a number.
26    fn into_matrix(self) -> CMat;
27}
28
29impl IntoMatrix for CMat {
30    fn into_matrix(self) -> CMat {
31        self
32    }
33}
34
35impl IntoMatrix for &CMat {
36    fn into_matrix(self) -> CMat {
37        self.clone()
38    }
39}
40
41impl IntoMatrix for f64 {
42    fn into_matrix(self) -> CMat {
43        CMat::from_fn(1, 1, |_, _| c64::new(self, 0.0))
44    }
45}
46
47impl IntoMatrix for c64 {
48    fn into_matrix(self) -> CMat {
49        CMat::from_fn(1, 1, |_, _| self)
50    }
51}
52
53/// Pauli matrices and Kronecker products, for spin and orbital degrees of freedom.
54pub mod pauli {
55    use crate::{CMat, c64};
56
57    fn matrix(m: [[c64; 2]; 2]) -> CMat {
58        CMat::from_fn(2, 2, |i, j| m[i][j])
59    }
60
61    const O: c64 = c64::new(0.0, 0.0);
62    const L: c64 = c64::new(1.0, 0.0);
63    const I: c64 = c64::new(0.0, 1.0);
64
65    /// The 2 × 2 identity.
66    pub fn s0() -> CMat {
67        matrix([[L, O], [O, L]])
68    }
69
70    /// The Pauli matrix `σ_x = [[0, 1], [1, 0]]`.
71    pub fn sx() -> CMat {
72        matrix([[O, L], [L, O]])
73    }
74
75    /// The Pauli matrix `σ_y = [[0, −i], [i, 0]]`.
76    pub fn sy() -> CMat {
77        matrix([[O, -I], [I, O]])
78    }
79
80    /// The Pauli matrix `σ_z = [[1, 0], [0, −1]]`.
81    pub fn sz() -> CMat {
82        matrix([[L, O], [O, -L]])
83    }
84
85    /// Kronecker product `a ⊗ b` (the index of `b` varies fastest).
86    pub fn kron(a: &CMat, b: &CMat) -> CMat {
87        let (p, q) = (b.nrows(), b.ncols());
88        CMat::from_fn(a.nrows() * p, a.ncols() * q, |i, j| a[(i / p, j / q)] * b[(i % p, j % q)])
89    }
90}
91
92/// A hopping term: `⟨(R, from)| H |(R + offset, to)⟩ = matrix`. Its Hermitian conjugate (the
93/// reverse hop) is added automatically.
94#[derive(Clone, Debug)]
95pub struct Hopping {
96    /// Sublattice of the site in cell `R`, whose orbitals are the rows of `matrix`.
97    pub from: usize,
98    /// Sublattice of the site in cell `R + offset`, whose orbitals are the columns of `matrix`.
99    pub to: usize,
100    /// Cell of the `to` site relative to the `from` site, along the primitive vectors.
101    pub offset: Cell,
102    /// The block, the same in every cell `R` (before hopping terms and Peierls phases).
103    pub matrix: CMat,
104}
105
106/// A hopping block `⟨from| H |to'⟩` of a region repeated periodically ([`Model::bonds`]):
107/// `to'` is the image of site `to` of the region that lies `images` periods away (one count per
108/// period), at `displacement = r_to' − r_from`. Hopping terms and Peierls phases are included.
109#[derive(Clone, Debug)]
110pub struct Bond {
111    /// Index of the site `from` in the region (the rows of `matrix`).
112    pub from: usize,
113    /// Index in the region of the site `to` of which `to'` is an image (the columns of `matrix`).
114    pub to: usize,
115    /// Periods from `to` to `to'`: `to' = to + Σ_l images[l] T_l` for the periods `T_l` given to
116    /// [`Model::bonds`] (empty if none). The Bloch phase of the block is `exp(i Σ_l images[l] k·T_l)`.
117    pub images: Vec<i64>,
118    /// `r_to' − r_from` (Cartesian, in the length unit of the lattice vectors).
119    pub displacement: Vec3,
120    /// The block `⟨from| H |to'⟩`, with the hopping terms and the Peierls phase, without Bloch phase.
121    pub matrix: CMat,
122}
123
124/// Site-dependent on-site term, added to the sublattice on-site matrix.
125pub trait OnSite: Send + Sync {
126    /// Extra on-site matrix of `site`, or `None` for no contribution.
127    fn matrix(&self, site: &Site) -> Option<CMat>;
128}
129
130impl<F: Fn(&Site) -> Option<CMat> + Send + Sync> OnSite for F {
131    fn matrix(&self, site: &Site) -> Option<CMat> {
132        self(site)
133    }
134}
135
136/// Site-dependent hopping term (Kwant's value functions for hoppings): the matrix
137/// `⟨(R, from)| H |(R + offset, to)⟩` of a hopping between two given sites, from the model's
138/// matrix `t`; `None` keeps `t`. The reverse hop is its conjugate, so the Hamiltonian stays
139/// Hermitian. Bond disorder, strain, spatially varying parameters.
140pub trait HoppingTerm: Send + Sync {
141    /// The block `⟨from| H |to⟩` between the two sites of a [`Hopping`] (on its `from` and `to`
142    /// sublattices), given its matrix `t` after the earlier terms; `None` keeps `t`.
143    fn matrix(&self, from: &Site, to: &Site, t: &CMat) -> Option<CMat>;
144}
145
146impl<F: Fn(&Site, &Site, &CMat) -> Option<CMat> + Send + Sync> HoppingTerm for F {
147    fn matrix(&self, from: &Site, to: &Site, t: &CMat) -> Option<CMat> {
148        self(from, to, t)
149    }
150}
151
152/// Peierls phase of the hopping `⟨i| H |j⟩`: `φ(r_i, r_j) = ∫ A · dl` from `r_j` to `r_i`, in
153/// radians (charge and ħ absorbed in `A`). It must be antisymmetric: `φ(a, b) = −φ(b, a)`.
154pub trait Peierls: Send + Sync {
155    /// The phase `φ(r_i, r_j)` (radians) of the block `⟨i| H |j⟩`, with `to = r_i` and `from = r_j`
156    /// (Cartesian positions).
157    fn phase(&self, to: Vec3, from: Vec3) -> f64;
158}
159
160impl<F: Fn(Vec3, Vec3) -> f64 + Send + Sync> Peierls for F {
161    fn phase(&self, to: Vec3, from: Vec3) -> f64 {
162        self(to, from)
163    }
164}
165
166/// Uniform magnetic fields `B ẑ` as [`Peierls`] phases, for [`Model::with_peierls`].
167///
168/// `b` is the field in units of `ħ/(e a²)`, `a` being the length unit of the lattice: the phase
169/// around a loop is `b` times the area it encloses (counterclockwise), and the flux quantum is
170/// `2π`. On the square lattice of constant 1, `b` is the flux per plaquette and the Landau levels
171/// near the band bottom sit at `E_n ≈ −4t + (2n + 1) t b`.
172///
173/// The leads must see a gauge that is invariant along their axis (the transport constructors
174/// check it): [`gauge::landau_x`] for leads along x, [`gauge::landau_y`] for leads along y.
175pub mod gauge {
176    use caroli_lattice::Vec3;
177
178    /// `A = (−b y, 0, 0)`: invariant along x.
179    pub fn landau_x(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
180        move |ri, rj| -b * 0.5 * (ri[1] + rj[1]) * (ri[0] - rj[0])
181    }
182
183    /// `A = (0, b x, 0)`: invariant along y.
184    pub fn landau_y(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
185        move |ri, rj| b * 0.5 * (ri[0] + rj[0]) * (ri[1] - rj[1])
186    }
187
188    /// `A = b (−y, x, 0) / 2`.
189    pub fn symmetric(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
190        move |ri, rj| {
191            let (xm, ym) = (0.5 * (ri[0] + rj[0]), 0.5 * (ri[1] + rj[1]));
192            0.5 * b * (-ym * (ri[0] - rj[0]) + xm * (ri[1] - rj[1]))
193        }
194    }
195
196    /// The gauge function `χ` that takes [`landau_x`] to the Landau gauge invariant along the
197    /// in-plane direction `d`, `A_d = −b (r·n) d` with `n = ẑ × d`: `A_d = A_x + ∇χ`. In the new
198    /// gauge, the hopping `⟨i| H |j⟩` picks up `exp(i (χ(r_i) − χ(r_j)))`. A direction along z,
199    /// the field's, needs no change (`χ = 0`): [`landau_x`] does not depend on z.
200    pub fn landau_x_to_along(b: f64, d: Vec3) -> impl Fn(Vec3) -> f64 + Send + Sync + Clone {
201        let norm = d[0].hypot(d[1]);
202        // Along z, (dx, dy) = (1, 0) makes χ vanish: the gauge along x is kept.
203        let (dx, dy) = if norm > 0.0 { (d[0] / norm, d[1] / norm) } else { (1.0, 0.0) };
204        // ∇χ = M r with M = b [[dx dy, dy²], [dy², −dx dy]] (symmetric: A_d − A_x is a gradient).
205        move |r| 0.5 * b * (dx * dy * r[0] * r[0] + 2.0 * dy * dy * r[0] * r[1] - dx * dy * r[1] * r[1])
206    }
207}
208
209/// Tight-binding model on a lattice.
210pub struct Model {
211    lattice: Lattice,
212    onsite: Vec<CMat>,
213    hoppings: Vec<Hopping>,
214    extra: Vec<Box<dyn OnSite>>,
215    hopping_terms: Vec<Box<dyn HoppingTerm>>,
216    peierls: Option<Box<dyn Peierls>>,
217    /// Uniform field set by [`Model::with_field`].
218    field: Option<f64>,
219}
220
221impl Model {
222    /// Model with zero on-site matrices and no hopping.
223    pub fn new(lattice: Lattice) -> Self {
224        let onsite = lattice.sublattices().iter().map(|s| CMat::zeros(s.orbitals, s.orbitals)).collect();
225        Self {
226            lattice,
227            onsite,
228            hoppings: Vec::new(),
229            extra: Vec::new(),
230            hopping_terms: Vec::new(),
231            peierls: None,
232            field: None,
233        }
234    }
235
236    /// The lattice of the model.
237    pub fn lattice(&self) -> &Lattice {
238        &self.lattice
239    }
240
241    /// The hoppings in the order they were added, one direction each (the reverse hops are
242    /// implied), before hopping terms and Peierls phases.
243    pub fn hoppings(&self) -> &[Hopping] {
244        &self.hoppings
245    }
246
247    /// Sets the on-site matrix of a sublattice (a number for one orbital).
248    pub fn onsite(mut self, sub: usize, matrix: impl IntoMatrix) -> Self {
249        let matrix = matrix.into_matrix();
250        let n = self.lattice.sublattices()[sub].orbitals;
251        assert_eq!((matrix.nrows(), matrix.ncols()), (n, n), "on-site matrix of sublattice {sub}");
252        self.onsite[sub] = matrix;
253        self
254    }
255
256    /// Adds a hopping `⟨(R, from)| H |(R + offset, to)⟩ = matrix` (and its conjugate); a number
257    /// for one orbital.
258    pub fn hopping(mut self, from: usize, to: usize, offset: Cell, matrix: impl IntoMatrix) -> Self {
259        let matrix = matrix.into_matrix();
260        let subs = self.lattice.sublattices();
261        assert_eq!((matrix.nrows(), matrix.ncols()), (subs[from].orbitals, subs[to].orbitals));
262        assert!(offset != [0; 3] || from != to, "an on-site term is not a hopping");
263        self.hoppings.push(Hopping { from, to, offset, matrix });
264        self
265    }
266
267    /// Adds a site-dependent on-site term (disorder, external potential...).
268    pub fn with_onsite_term(mut self, term: impl OnSite + 'static) -> Self {
269        self.extra.push(Box::new(term));
270        self
271    }
272
273    /// Adds a site-dependent hopping term (see [`HoppingTerm`]); terms apply in the order they
274    /// were added, each to the result of the previous ones.
275    pub fn with_hopping_term(mut self, term: impl HoppingTerm + 'static) -> Self {
276        self.hopping_terms.push(Box::new(term));
277        self
278    }
279
280    /// The matrix of `hop` between the sites `from` (its `from` sublattice) and `to`, after the
281    /// hopping terms.
282    fn hopping_matrix<'a>(&self, hop: &'a Hopping, from: &Site, to: &Site) -> std::borrow::Cow<'a, CMat> {
283        let mut m = std::borrow::Cow::Borrowed(&hop.matrix);
284        for term in &self.hopping_terms {
285            if let Some(v) = term.matrix(from, to, &m) {
286                assert_eq!(
287                    (v.nrows(), v.ncols()),
288                    (hop.matrix.nrows(), hop.matrix.ncols()),
289                    "hopping term of the wrong size"
290                );
291                m = std::borrow::Cow::Owned(v);
292            }
293        }
294        m
295    }
296
297    /// Multiplies every hopping `⟨i| H |j⟩` by `exp(i φ(r_i, r_j))`: a vector potential through
298    /// the Peierls substitution (see [`gauge`] for uniform fields). Replaces any previous phase.
299    pub fn with_peierls(mut self, phase: impl Peierls + 'static) -> Self {
300        self.peierls = Some(Box::new(phase));
301        self.field = None;
302        self
303    }
304
305    /// A uniform field `b ẑ` (see [`gauge`] for the units), in the gauge [`gauge::landau_x`].
306    /// The transport constructors change the gauge of each lead so that it is invariant along
307    /// the lead, whatever its direction (as Kwant's `magnetic_gauge`).
308    pub fn with_field(mut self, b: f64) -> Self {
309        self.peierls = Some(Box::new(gauge::landau_x(b)));
310        self.field = Some(b);
311        self
312    }
313
314    /// The uniform field set by [`Self::with_field`], if any.
315    pub fn field(&self) -> Option<f64> {
316        self.field
317    }
318
319    /// The on-site matrix of a sublattice, without the site-dependent terms.
320    pub fn sublattice_onsite(&self, sub: usize) -> &CMat {
321        &self.onsite[sub]
322    }
323
324    /// The sum of the site-dependent on-site terms of a site (disorder, potentials), or `None`
325    /// if none applies.
326    pub fn onsite_terms(&self, site: &Site) -> Option<CMat> {
327        let mut sum: Option<CMat> = None;
328        for term in &self.extra {
329            if let Some(v) = term.matrix(site) {
330                match &mut sum {
331                    Some(s) => *s += v,
332                    None => sum = Some(v),
333                }
334            }
335        }
336        sum
337    }
338
339    /// Whether every hopping is the same in every cell: no site-dependent hopping term and no
340    /// Peierls phase. The on-site terms may still depend on the site.
341    pub fn has_uniform_hoppings(&self) -> bool {
342        self.hopping_terms.is_empty() && self.peierls.is_none()
343    }
344
345    /// Every hopping block of a region, repeated along `periods` (open if empty), with the
346    /// displacement of its bond: the blocks of [`Self::bloch_hamiltonian`] other than the on-site
347    /// ones, before the Bloch phases. Each bond appears in both directions. With them, a uniform
348    /// vector potential `A` enters as the Peierls factor `exp(−i A·d)` of each block.
349    pub fn bonds(&self, region: &Region, periods: &[Cell]) -> Vec<Bond> {
350        let images = (!periods.is_empty()).then(|| Images::new(region, periods));
351        let mut out = Vec::new();
352        for (i, site) in region.sites().iter().enumerate() {
353            let ri = self.lattice.position(*site);
354            for hop in &self.hoppings {
355                let ends =
356                    [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
357                for (applies, sign, sub, adjoint) in ends {
358                    if !applies {
359                        continue;
360                    }
361                    let partner = shifted(site, hop.offset, sign, sub);
362                    let (j, n) = match &images {
363                        None => match region.index_of(&partner) {
364                            Some(j) => (j, Vec::new()),
365                            None => continue,
366                        },
367                        Some(images) => match images.locate(&partner) {
368                            Some(found) => found,
369                            None => continue,
370                        },
371                    };
372                    let rj = self.lattice.position(partner);
373                    let m = if adjoint {
374                        self.hopping_matrix(hop, &partner, site).adjoint().to_owned()
375                    } else {
376                        self.hopping_matrix(hop, site, &partner).into_owned()
377                    };
378                    let factor = self.phased(c64::new(1.0, 0.0), site, &partner);
379                    out.push(Bond {
380                        from: i,
381                        to: j,
382                        images: n,
383                        displacement: [rj[0] - ri[0], rj[1] - ri[1], rj[2] - ri[2]],
384                        matrix: CMat::from_fn(m.nrows(), m.ncols(), |a, b| factor * m[(a, b)]),
385                    });
386                }
387            }
388        }
389        out
390    }
391
392    /// `factor · exp(i φ(r_i, r_j))` for the block `⟨i| H |j⟩`.
393    fn phased(&self, factor: c64, i: &Site, j: &Site) -> c64 {
394        match &self.peierls {
395            None => factor,
396            Some(p) => {
397                let (s, c) = p.phase(self.lattice.position(*i), self.lattice.position(*j)).sin_cos();
398                factor * c64::new(c, s)
399            }
400        }
401    }
402
403    /// Full on-site matrix of a site (sublattice term plus site-dependent terms).
404    pub fn onsite_matrix(&self, site: &Site) -> CMat {
405        let mut m = self.onsite[site.sub].clone();
406        for term in &self.extra {
407            if let Some(v) = term.matrix(site) {
408                m += v;
409            }
410        }
411        m
412    }
413
414    /// Dense Hamiltonian of a finite region (open boundaries).
415    pub fn hamiltonian(&self, region: &Region) -> CMat {
416        let mut h = CMat::zeros(region.orbitals(), region.orbitals());
417        self.build(&mut h, region, &[], &[]);
418        h
419    }
420
421    /// Bloch Hamiltonian of a region repeated periodically: `periods` are translations (in
422    /// cells) and `phases` the matching Bloch phases `k·T` in radians. Hoppings that leave the
423    /// region by `n` periods pick up `exp(i Σ n·phase)`.
424    pub fn bloch_hamiltonian(&self, region: &Region, periods: &[Cell], phases: &[f64]) -> CMat {
425        let mut h = CMat::zeros(region.orbitals(), region.orbitals());
426        self.build(&mut h, region, periods, phases);
427        h
428    }
429
430    /// Sparse Hamiltonian of a finite region (open boundaries), for regions too large for
431    /// dense matrices (KPM, time evolution).
432    pub fn sparse_hamiltonian(&self, region: &Region) -> SparseMatrix {
433        self.sparse_bloch_hamiltonian(region, &[], &[])
434    }
435
436    /// Sparse version of [`Self::bloch_hamiltonian`] (twisted periodic boundaries).
437    pub fn sparse_bloch_hamiltonian(
438        &self,
439        region: &Region,
440        periods: &[Cell],
441        phases: &[f64],
442    ) -> SparseMatrix {
443        let mut t = Triplets(Vec::new());
444        self.build(&mut t, region, periods, phases);
445        SparseMatrix::from_triplets(region.orbitals(), t.0)
446    }
447
448    /// On-site terms and couplings, each hopping partner reduced into the region modulo the
449    /// period lattice: a partner `p = q + Σ n_i T_i` with `q` in the region couples with the
450    /// Bloch phase `exp(i Σ n_i phase_i)`. Partners with no image in the region (open
451    /// directions) are dropped. Hoppings of any range and sheared periods are handled.
452    fn build(&self, h: &mut impl Sink, region: &Region, periods: &[Cell], phases: &[f64]) {
453        assert_eq!(periods.len(), phases.len());
454        for i in 0..region.len() {
455            h.block(
456                region.offset(i),
457                region.offset(i),
458                &self.onsite_matrix(&region.sites()[i]),
459                c64::new(1.0, 0.0),
460                false,
461            );
462        }
463        if periods.is_empty() {
464            self.add_couplings_one_way(h, region, region, c64::new(1.0, 0.0));
465            return;
466        }
467        let images = Images::new(region, periods);
468        for (i, site) in region.sites().iter().enumerate() {
469            for hop in &self.hoppings {
470                // Forward: site is `from`, partner is `to` at +offset; backward: site is `to`,
471                // partner is `from` at −offset, block matrix†.
472                let ends =
473                    [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
474                for (applies, sign, sub, adjoint) in ends {
475                    if !applies {
476                        continue;
477                    }
478                    let partner = shifted(site, hop.offset, sign, sub);
479                    if let Some((j, n)) = images.locate(&partner) {
480                        let phase: f64 = n.iter().zip(phases).map(|(n, k)| *n as f64 * k).sum();
481                        let (s, cs) = phase.sin_cos();
482                        let factor = self.phased(c64::new(cs, s), site, &partner);
483                        let m = if adjoint {
484                            self.hopping_matrix(hop, &partner, site)
485                        } else {
486                            self.hopping_matrix(hop, site, &partner)
487                        };
488                        h.block(region.offset(i), region.offset(j), &m, factor, adjoint);
489                    }
490                }
491            }
492        }
493    }
494
495    /// Velocity operator `v = i[H, r·d]` (ħ = 1) along `direction`, as a sparse matrix, on a
496    /// region with periodic directions as [`Self::sparse_bloch_hamiltonian`]:
497    /// `v_ij = i H_ij (r_j − r_i)·d`. The displacement is that of the hopping itself, not
498    /// reduced into the region, so it is also the velocity of a torus. On-site terms do not
499    /// contribute.
500    pub fn sparse_velocity(
501        &self,
502        region: &Region,
503        periods: &[Cell],
504        phases: &[f64],
505        direction: Vec3,
506    ) -> SparseMatrix {
507        assert_eq!(periods.len(), phases.len());
508        let mut t = Triplets(Vec::new());
509        let images = (!periods.is_empty()).then(|| Images::new(region, periods));
510        for (i, site) in region.sites().iter().enumerate() {
511            let ri = self.lattice.position(*site);
512            for hop in &self.hoppings {
513                let ends =
514                    [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
515                for (applies, sign, sub, adjoint) in ends {
516                    if !applies {
517                        continue;
518                    }
519                    let partner = shifted(site, hop.offset, sign, sub);
520                    let (j, phase) = match &images {
521                        None => match region.index_of(&partner) {
522                            Some(j) => (j, 0.0),
523                            None => continue,
524                        },
525                        Some(images) => match images.locate(&partner) {
526                            Some((j, n)) => (j, n.iter().zip(phases).map(|(n, k)| *n as f64 * k).sum()),
527                            None => continue,
528                        },
529                    };
530                    let rj = self.lattice.position(partner);
531                    let along: f64 = (0..3).map(|c| (rj[c] - ri[c]) * direction[c]).sum();
532                    let (s, cs) = phase.sin_cos();
533                    let factor = self.phased(c64::new(cs, s), site, &partner) * c64::new(0.0, along);
534                    let m = if adjoint {
535                        self.hopping_matrix(hop, &partner, site)
536                    } else {
537                        self.hopping_matrix(hop, site, &partner)
538                    };
539                    t.block(region.offset(i), region.offset(j), &m, factor, adjoint);
540                }
541            }
542        }
543        SparseMatrix::from_triplets(region.orbitals(), t.0)
544    }
545
546    /// Coupling matrix `⟨a| H |b⟩` between two disjoint regions (rows: `a`, columns: `b`).
547    pub fn coupling(&self, a: &Region, b: &Region) -> CMat {
548        let mut h = CMat::zeros(a.orbitals(), b.orbitals());
549        self.add_couplings_one_way(&mut h, a, b, c64::new(1.0, 0.0));
550        h
551    }
552
553    /// Adds `⟨a| H |b⟩` (hoppings from a site of `a` to a site of `b`, in either direction of
554    /// the stored hoppings) times `factor` into `h`, rows indexed by `a` and columns by `b`.
555    fn add_couplings_one_way(&self, h: &mut impl Sink, a: &Region, b: &Region, factor: c64) {
556        for (i, site) in a.sites().iter().enumerate() {
557            for hop in &self.hoppings {
558                // Forward: site is `from`, partner is `to` at +offset.
559                if hop.from == site.sub {
560                    let partner = shifted(site, hop.offset, 1, hop.to);
561                    if let Some(j) = b.index_of(&partner) {
562                        let m = self.hopping_matrix(hop, site, &partner);
563                        h.block(a.offset(i), b.offset(j), &m, self.phased(factor, site, &partner), false);
564                    }
565                }
566                // Backward: site is `to`, partner is `from` at -offset; block is matrix†.
567                if hop.to == site.sub {
568                    let partner = shifted(site, hop.offset, -1, hop.from);
569                    if let Some(j) = b.index_of(&partner) {
570                        let m = self.hopping_matrix(hop, &partner, site);
571                        h.block(a.offset(i), b.offset(j), &m, self.phased(factor, site, &partner), true);
572                    }
573                }
574            }
575        }
576    }
577
578    /// Transport blocks of a region cut into slices along primitive vector `axis`: the on-slice
579    /// Hamiltonians `H_nn` and the couplings `V_n = ⟨n| H |n+1⟩`. Panics if a hopping skips a
580    /// slice (range longer than one slice).
581    pub fn slice_blocks(&self, region: &Region, axis: usize) -> (Vec<Region>, Vec<CMat>, Vec<CMat>) {
582        let slices = region.slices(axis);
583        let diag = slices.iter().map(|s| self.hamiltonian(s)).collect();
584        let off = slices.windows(2).map(|w| self.coupling(&w[0], &w[1])).collect();
585        for hop in &self.hoppings {
586            assert!(hop.offset[axis].abs() <= 1, "hopping range exceeds one slice along axis {axis}");
587        }
588        (slices, diag, off)
589    }
590}
591
592fn shifted(site: &Site, offset: Cell, sign: i64, sub: usize) -> Site {
593    Site {
594        cell: [
595            site.cell[0] + sign * offset[0],
596            site.cell[1] + sign * offset[1],
597            site.cell[2] + sign * offset[2],
598        ],
599        sub,
600    }
601}
602
603/// Exact reduction of sites into a region modulo the lattice of the periods.
604///
605/// The periods (rows) are brought to row-echelon (Hermite) form `H = W P` by unimodular integer
606/// row operations. Reducing a cell along the pivots of `H` gives a canonical representative, so
607/// every site of the region is filed under its class, and a hopping partner is found by its
608/// class with the exact number of periods it lies away.
609struct Images {
610    /// Echelon rows and their pivot columns.
611    rows: Vec<[i64; 3]>,
612    pivots: Vec<usize>,
613    /// `H = W P`.
614    w: Vec<Vec<i64>>,
615    /// Class `(representative cell, sublattice)` → (index in the region, echelon coefficients).
616    classes: std::collections::HashMap<([i64; 3], usize), (usize, Vec<i64>)>,
617}
618
619impl Images {
620    fn new(region: &Region, periods: &[Cell]) -> Self {
621        let m = periods.len();
622        let mut rows: Vec<[i64; 3]> = periods.to_vec();
623        let mut w: Vec<Vec<i64>> = (0..m).map(|i| (0..m).map(|j| (i == j) as i64).collect()).collect();
624        let mut pivots = Vec::new();
625        let mut top = 0;
626        for col in 0..3 {
627            if top == m {
628                break;
629            }
630            // Euclid on the rows top.. in this column.
631            while let Some(p) = (top..m).filter(|&i| rows[i][col] != 0).min_by_key(|&i| rows[i][col].abs()) {
632                rows.swap(top, p);
633                w.swap(top, p);
634                let (pivot_row, pivot_w) = (rows[top], w[top].clone());
635                let mut done = true;
636                for i in top + 1..m {
637                    let f = rows[i][col] / pivot_row[col];
638                    if f != 0 {
639                        rows[i].iter_mut().zip(&pivot_row).for_each(|(x, y)| *x -= f * y);
640                        w[i].iter_mut().zip(&pivot_w).for_each(|(x, y)| *x -= f * y);
641                    }
642                    done &= rows[i][col] == 0;
643                }
644                if done {
645                    break;
646                }
647            }
648            if rows[top][col] != 0 {
649                if rows[top][col] < 0 {
650                    rows[top].iter_mut().for_each(|x| *x = -*x);
651                    w[top].iter_mut().for_each(|x| *x = -*x);
652                }
653                pivots.push(col);
654                top += 1;
655            }
656        }
657        assert_eq!(top, m, "periods must be linearly independent");
658        let mut images = Self { rows, pivots, w, classes: Default::default() };
659        for (i, site) in region.sites().iter().enumerate() {
660            let (rep, k) = images.reduce(site.cell);
661            let previous = images.classes.insert((rep, site.sub), (i, k));
662            assert!(previous.is_none(), "the region holds two sites a whole number of periods apart");
663        }
664        images
665    }
666
667    /// Canonical representative of a cell and its echelon coefficients `k`: `cell = rep + Σ k_i H_i`.
668    fn reduce(&self, cell: [i64; 3]) -> ([i64; 3], Vec<i64>) {
669        let mut x = cell;
670        let mut k = vec![0; self.rows.len()];
671        for (i, (&c, row)) in self.pivots.iter().zip(&self.rows).enumerate() {
672            let q = x[c].div_euclid(row[c]);
673            for a in 0..3 {
674                x[a] -= q * row[a];
675            }
676            k[i] = q;
677        }
678        (x, k)
679    }
680
681    /// `(index in the region, period counts n)` with `site = region[index] + Σ n_l T_l`, or `None`
682    /// if the class of the site is not in the region (open directions).
683    fn locate(&self, site: &Site) -> Option<(usize, Vec<i64>)> {
684        let (rep, k) = self.reduce(site.cell);
685        let (j, kq) = self.classes.get(&(rep, site.sub))?;
686        let m = self.rows.len();
687        let n = (0..m).map(|l| (0..m).map(|i| (k[i] - kq[i]) * self.w[i][l]).sum()).collect();
688        Some((*j, n))
689    }
690}
691
692/// Destination of Hamiltonian blocks: a dense matrix or a list of sparse entries.
693trait Sink {
694    /// Adds `factor · m` (or `factor · m†`) with its top-left corner at `(r0, c0)`.
695    fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool);
696}
697
698impl Sink for CMat {
699    fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool) {
700        let (rows, cols) = if adjoint { (m.ncols(), m.nrows()) } else { (m.nrows(), m.ncols()) };
701        for j in 0..cols {
702            for i in 0..rows {
703                let v = if adjoint { m[(j, i)].conj() } else { m[(i, j)] };
704                self[(r0 + i, c0 + j)] += factor * v;
705            }
706        }
707    }
708}
709
710struct Triplets(Vec<(usize, usize, c64)>);
711
712impl Sink for Triplets {
713    fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool) {
714        let (rows, cols) = if adjoint { (m.ncols(), m.nrows()) } else { (m.nrows(), m.ncols()) };
715        for j in 0..cols {
716            for i in 0..rows {
717                let v = if adjoint { m[(j, i)].conj() } else { m[(i, j)] };
718                if v != c64::new(0.0, 0.0) {
719                    self.0.push((r0 + i, c0 + j, factor * v));
720                }
721            }
722        }
723    }
724}
725
726/// `Σ_i c_i M_i` for small matrices of the same shape, with real or complex coefficients:
727/// `combine(&[(4.0 * t, &s0()), (e_z, &sz())])`.
728pub fn combine<C: Into<c64> + Copy>(terms: &[(C, &CMat)]) -> CMat {
729    let (n, m) = (terms[0].1.nrows(), terms[0].1.ncols());
730    CMat::from_fn(n, m, |i, j| terms.iter().map(|(c, mat)| (*c).into() * mat[(i, j)]).sum())
731}