Skip to main content

caroli_green/
modes.rs

1//! Lead modes and mode-matching self-energies.
2//!
3//! A lead has a cell Hamiltonian `H0` and a coupling `H1 = ⟨j| H |j+1⟩`. Its Bloch solutions
4//! `ψ_{j+1} = λ ψ_j` are found from the compact SVD `H1 = u v†` (`u = U√S`, `v = V√S`, rank
5//! `r`). The vectors `x_j = (α_j, γ_j) = (u† ψ_{j−1}, v† ψ_j)` obey a regular `2r × 2r` pencil
6//! `R x = λ L x`. This is the formulation of Wimmer and Kwant, stabilised by `i(uu† + vv†)` so that
7//! it holds even when `H0 − E` is singular. Couplings of low rank (graphene ribbons cut along a
8//! slanted direction, ...) therefore give small, well-conditioned problems.
9//!
10//! Right-going modes (`|λ| < 1`, or `|λ| = 1` with a positive velocity) span a subspace with
11//! orthonormal basis `X`, left-going ones a subspace with basis `Y`, and
12//!
13//! ```text
14//! Σ_R = u X_γ X_α⁻¹ u†   (lead towards +∞, on the slice it touches),
15//! Σ_L = v Y_α Y_γ⁻¹ v†   (lead towards −∞).
16//! ```
17//!
18//! Degenerate propagating modes are separated by diagonalising their current. Two cases have no
19//! self-energy:
20//! - a subband edge (a propagating mode with vanishing velocity);
21//! - a bound state of the lead surface (singular `X_α` or `Y_γ`, e.g. graphene zigzag ends at
22//!   E = 0).
23//!
24//! The modes are then computed at `E + δ`, with `δ` from 1e-9 to 1e-6 of the bandwidth (the limit
25//! from above), and [`LeadModes::energy`] records the energy used.
26
27use crate::{GreenError, sandwich, solve_right};
28use caroli_dense::{Accum, Lu, Op, matmul, norm_1, product};
29use caroli_model::{CMat, c64};
30use faer::Side;
31
32/// Singular values of `H1` below this fraction of the largest are dropped.
33const RANK_TOL: f64 = 1e-12;
34/// `|λ|` within this of 1: a propagating candidate.
35const UNIT_TOL: f64 = 1e-6;
36/// Propagating `λ` closer than this form one degenerate group.
37const DEGENERATE_TOL: f64 = 1e-7;
38/// Velocities (of unit cell vectors) below this fraction of the bandwidth scale: a subband edge.
39const VELOCITY_TOL: f64 = 1e-8;
40/// Propagating modes of one group whose `(α, γ)` vectors are closer to parallel than this
41/// (angle): a Jordan block, i.e. a subband edge.
42const DEFECTIVE_TOL: f64 = 1e-7;
43/// `X_α` or `Y_γ` with an inverse condition number (1-norm estimate) below this: a bound state
44/// of the lead surface.
45const SINGULAR_TOL: f64 = 1e-11;
46/// The stabilisation of a real problem (any real number works but those that make the resolvent
47/// singular at the energy; an irrational one makes it unlikely).
48const REAL_STABILISATION: f64 = 0.618_033_988_749_894_8;
49/// Energy shifts tried in turn, in units of the bandwidth scale.
50const SHIFTS: [f64; 5] = [0.0, 1e-9, 1e-8, 1e-7, 1e-6];
51
52/// Modes of a lead at one energy, as subspaces of the reduced coordinates `(α, γ)`.
53#[derive(Clone, Debug)]
54pub struct LeadModes {
55    /// Compact factors of the coupling, `H1 = u v†` (`n × r`).
56    pub u: CMat,
57    /// The second factor `v` (`n × r`): its columns span the range of `H1†`, where `Σ_L` acts.
58    pub v: CMat,
59    /// Orthonormal basis of the right-going modes in `(α, γ)` coordinates (`2r × r`).
60    pub right: CMat,
61    /// Orthonormal basis of the left-going modes (`2r × r`).
62    pub left: CMat,
63    /// Velocities of the propagating modes: right-going (> 0) and left-going (< 0).
64    pub right_velocities: Vec<f64>,
65    /// Velocities `J(φ, φ) / φ†φ` of the left-going propagating modes (< 0), in the order of
66    /// [`Self::left_modes`].
67    pub left_velocities: Vec<f64>,
68    /// The propagating modes `ψ_n = φ λ^n` on a cell (`φ` in columns, in the order of the
69    /// velocities), normalised to unit current: `J(φ, φ) = ±1` with the current
70    /// `J(a, b) = i(a_n† H1 b_{n+1} − a_{n+1}† H1† b_n)`.
71    pub right_modes: CMat,
72    /// The left-going propagating modes (`φ` in columns, in the order of
73    /// [`Self::left_velocities`]), with `J(φ, φ) = −1`.
74    pub left_modes: CMat,
75    /// Their Bloch factors `λ` (`|λ| = 1`).
76    pub right_lambdas: Vec<c64>,
77    /// Bloch factors `λ` of the left-going propagating modes (`|λ| = 1`).
78    pub left_lambdas: Vec<c64>,
79    /// Energy at which the modes were computed (shifted off a band edge or a surface state).
80    pub energy: c64,
81}
82
83/// `∞`-norm, a bound on the spectral radius.
84fn row_norm(m: &CMat) -> f64 {
85    (0..m.nrows()).map(|i| (0..m.ncols()).map(|j| m[(i, j)].norm()).sum::<f64>()).fold(0.0, f64::max)
86}
87
88fn rows(m: &CMat, range: std::ops::Range<usize>) -> CMat {
89    CMat::from_fn(range.len(), m.ncols(), |i, j| m[(range.start + i, j)])
90}
91
92/// Stable partition of the Schur form `(t, q)` and of its keys: selected keys first.
93fn partition_by(t: &mut CMat, q: &mut CMat, keys: &mut Vec<usize>, select: impl Fn(usize) -> bool) {
94    let flags: Vec<bool> = keys.iter().map(|&k| select(k)).collect();
95    caroli_dense::partition(t, q, &flags);
96    let (mut first, rest): (Vec<usize>, Vec<usize>) = keys.iter().copied().partition(|&k| select(k));
97    first.extend(rest);
98    *keys = first;
99}
100
101/// Smallest over largest singular value (0 for an empty or zero matrix).
102fn inverse_condition(m: &CMat) -> f64 {
103    if m.nrows() == 0 {
104        return 1.0;
105    }
106    match m.singular_values() {
107        Ok(s) => {
108            let (lo, hi) = s.iter().fold((f64::INFINITY, 0.0f64), |(l, h), &x| (l.min(x), h.max(x)));
109            if hi > 0.0 { lo / hi } else { 0.0 }
110        }
111        Err(_) => 0.0,
112    }
113}
114
115impl LeadModes {
116    /// Modes of the lead `(h0, h1)` at the real energy `energy`.
117    pub fn new(h0: &CMat, h1: &CMat, energy: f64) -> Result<Self, GreenError> {
118        Self::at(h0, h1, c64::new(energy, 0.0))
119    }
120
121    /// Modes at a complex energy `z`. With `Im z > 0` no mode propagates (`|λ| ≠ 1`).
122    ///
123    /// At a real energy, a Hermitian definite coupling (`H1 = ±P`, `P > 0`) takes a fast path: one
124    /// Hermitian eigenproblem of size n. Everything else takes the general algorithm.
125    pub fn at(h0: &CMat, h1: &CMat, z: c64) -> Result<Self, GreenError> {
126        ModeSolver::new(h0, h1).modes_at(z)
127    }
128
129    /// Modes at `z` by the general algorithm (the `2r` Schur decomposition), whatever the
130    /// coupling: a cross-check of the fast path.
131    pub fn at_general(h0: &CMat, h1: &CMat, z: c64) -> Result<Self, GreenError> {
132        Self::shifted(h0, h1, z, |e, scale| Self::solve(h0, h1, e, scale))
133    }
134
135    /// `solve` at `z`, then at `z + δ` for the shifts δ of [`SHIFTS`] until it succeeds.
136    fn shifted(
137        h0: &CMat,
138        h1: &CMat,
139        z: c64,
140        solve: impl Fn(c64, f64) -> Result<Self, GreenError>,
141    ) -> Result<Self, GreenError> {
142        let scale = (row_norm(h0) + 2.0 * row_norm(h1)).max(f64::MIN_POSITIVE);
143        let mut last = GreenError::Eigen;
144        for shift in SHIFTS {
145            match solve(z + shift * scale, scale) {
146                Ok(m) => return Ok(m),
147                Err(e) => last = e,
148            }
149        }
150        Err(last)
151    }
152
153    /// The general algorithm. A real problem (real `H0`, `H1` and energy) keeps the pencil real,
154    /// with a real stabilisation, and its Schur decomposition goes through the real Schur form, a
155    /// quarter of the arithmetic; if that stabilisation is ill-conditioned, the complex one takes
156    /// over.
157    fn solve(h0: &CMat, h1: &CMat, z: c64, scale: f64) -> Result<Self, GreenError> {
158        let real = z.im == 0.0 && caroli_dense::is_real(h0.as_ref()) && caroli_dense::is_real(h1.as_ref());
159        if real && let Ok(modes) = Self::solve_with(h0, h1, z, scale, true) {
160            return Ok(modes);
161        }
162        Self::solve_with(h0, h1, z, scale, false)
163    }
164
165    fn solve_with(h0: &CMat, h1: &CMat, z: c64, scale: f64, real: bool) -> Result<Self, GreenError> {
166        let n = h0.nrows();
167        let i = c64::new(0.0, 1.0);
168        // The stabilisation s(uu† + vv†): s = i in general, a real s for a real problem.
169        let s = if real { c64::new(REAL_STABILISATION, 0.0) } else { i };
170        let one = c64::new(1.0, 0.0);
171        let zero = c64::new(0.0, 0.0);
172
173        // Compact SVD of the coupling (with real vectors for a real problem).
174        let svd = if real { caroli_dense::svd_of_real(h1.as_ref()) } else { caroli_dense::svd(h1.as_ref()) };
175        let caroli_dense::Svd { u: su, s: ss, v: sv } = svd.map_err(|_| GreenError::Eigen)?;
176        let smax = ss.iter().copied().fold(0.0, f64::max);
177        let kept: Vec<usize> = (0..ss.len()).filter(|&k| ss[k] > RANK_TOL * smax).collect();
178        let r = kept.len();
179        let u = CMat::from_fn(n, r, |a, k| su[(a, kept[k])] * ss[kept[k]].sqrt());
180        let v = CMat::from_fn(n, r, |a, k| sv[(a, kept[k])] * ss[kept[k]].sqrt());
181        if r == 0 {
182            return Ok(Self {
183                u,
184                v,
185                right: CMat::zeros(0, 0),
186                left: CMat::zeros(0, 0),
187                right_velocities: Vec::new(),
188                left_velocities: Vec::new(),
189                right_modes: CMat::zeros(n, 0),
190                left_modes: CMat::zeros(n, 0),
191                right_lambdas: Vec::new(),
192                left_lambdas: Vec::new(),
193                energy: z,
194            });
195        }
196
197        // Stabilised resolvent G̃ = (H0 − z + s(uu† + vv†))⁻¹, applied to u and v.
198        let uv = CMat::from_fn(n, 2 * r, |p, k| if k < r { u[(p, k)] } else { v[(p, k - r)] });
199        let stab = product(uv.as_ref(), Op::Plain, uv.as_ref(), Op::Adjoint);
200        let a = CMat::from_fn(n, n, |p, q| h0[(p, q)] - if p == q { z } else { zero } + s * stab[(p, q)]);
201        let lu_a = Lu::new(a.as_ref());
202        if real {
203            // A real stabilisation can make the resolvent singular at some energies.
204            let (lo, hi) = lu_a.pivot_range();
205            let conditioned = lo > 1e-10 * hi; // false for NaN
206            if !conditioned {
207                return Err(GreenError::Eigen);
208            }
209        }
210        let g = lu_a.solve(uv.as_ref());
211        if g.norm_max().is_nan() {
212            return Err(GreenError::Singular(z.re));
213        }
214        let (gu, gv) = (g.as_ref().subcols(0, r), g.as_ref().subcols(r, r));
215        // [u v]† G̃ [u v], in blocks.
216        let blocks = product(uv.as_ref(), Op::Adjoint, g.as_ref(), Op::Plain);
217        let (ugu, ugv) = (blocks.as_ref().submatrix(0, 0, r, r), blocks.as_ref().submatrix(0, r, r, r));
218        let (vgu, vgv) = (blocks.as_ref().submatrix(r, 0, r, r), blocks.as_ref().submatrix(r, r, r, r));
219
220        // Pencil R x = λ L x:
221        //   L = [[1 − s u†G̃u, u†G̃u], [−s v†G̃u, v†G̃u]],  R = [[−u†G̃v, s u†G̃v], [−v†G̃v, s v†G̃v − 1]].
222        let lmat = CMat::from_fn(2 * r, 2 * r, |p, q| match (p < r, q < r) {
223            (true, true) => (if p == q { one } else { zero }) - s * ugu[(p, q)],
224            (true, false) => ugu[(p, q - r)],
225            (false, true) => -s * vgu[(p - r, q)],
226            (false, false) => vgu[(p - r, q - r)],
227        });
228        let rmat = CMat::from_fn(2 * r, 2 * r, |p, q| match (p < r, q < r) {
229            (true, true) => -ugv[(p, q)],
230            (true, false) => s * ugv[(p, q - r)],
231            (false, true) => -vgv[(p - r, q)],
232            (false, false) => s * vgv[(p - r, q - r)] - if p == q { one } else { zero },
233        });
234
235        // A standard eigenproblem with the same invariant subspaces: L⁻¹R (eigenvalue λ) or R⁻¹L
236        // (1/λ) when one of them is well conditioned, else (R − σL)⁻¹L (λ = σ + 1/μ) with σ off
237        // the unit circle.
238        let pivot_ratio = |lu: &Lu| {
239            let (lo, hi) = lu.pivot_range();
240            if hi > 0.0 { lo / hi } else { 0.0 }
241        };
242        #[derive(Clone, Copy)]
243        enum Map {
244            Direct,
245            Inverse,
246            Mobius(c64),
247        }
248        let (lu_l, lu_r) = (Lu::new(lmat.as_ref()), Lu::new(rmat.as_ref()));
249        let (pl, pr) = (pivot_ratio(&lu_l), pivot_ratio(&lu_r));
250        let (c, map) = if pl >= pr && pl > 1e-10 {
251            (lu_l.solve(rmat.as_ref()), Map::Direct)
252        } else if pr > 1e-10 {
253            (lu_r.solve(lmat.as_ref()), Map::Inverse)
254        } else {
255            let mut best: Option<(f64, c64, CMat)> = None;
256            for k in 0..8 {
257                // Off the unit circle; on the real axis for a real pencil.
258                let sigma = if real {
259                    c64::new([0.5, 2.0, -0.5, -2.0, 0.37, 2.7, -0.37, -2.7][k], 0.0)
260                } else {
261                    c64::from_polar(if k % 2 == 0 { 0.5 } else { 2.0 }, 0.3 + 0.9 * k as f64)
262                };
263                let m = &rmat - CMat::from_fn(2 * r, 2 * r, |p, q| sigma * lmat[(p, q)]);
264                let lu = Lu::new(m.as_ref());
265                let ratio = pivot_ratio(&lu);
266                if best.as_ref().is_none_or(|b| ratio > b.0) {
267                    best = Some((ratio, sigma, lu.solve(lmat.as_ref())));
268                }
269            }
270            let (ratio, sigma, c) = best.expect("candidates");
271            if ratio.is_nan() || ratio <= 1e-14 {
272                return Err(GreenError::Eigen);
273            }
274            (c, Map::Mobius(sigma))
275        };
276
277        // Schur form and classes: right-evanescent, propagating, left-evanescent (with λ = ∞).
278        let m2 = 2 * r;
279        let schur = if real && caroli_dense::is_real(c.as_ref()) {
280            caroli_dense::schur_of_real(c.as_ref())
281        } else {
282            caroli_dense::schur(c.as_ref())
283        };
284        let (q0, t0) = schur.map_err(|_| GreenError::Eigen)?;
285        let mu_max = (0..m2).map(|k| t0[(k, k)].norm()).fold(0.0, f64::max);
286        let to_lambda = |mu: c64| -> Option<c64> {
287            match map {
288                Map::Direct => Some(mu),
289                _ if mu.norm() <= 1e-13 * mu_max => None,
290                Map::Inverse => Some(one / mu),
291                Map::Mobius(sigma) => Some(sigma + one / mu),
292            }
293        };
294        let lams: Vec<Option<c64>> = (0..m2).map(|k| to_lambda(t0[(k, k)])).collect();
295        const RIGHT: usize = 0;
296        const LEFT: usize = usize::MAX;
297        let mut keys: Vec<usize> = lams
298            .iter()
299            .map(|l| match l {
300                Some(l) if l.norm() < 1.0 - UNIT_TOL => RIGHT,
301                Some(l) if l.norm() <= 1.0 + UNIT_TOL => 1, // propagating, grouped below
302                _ => LEFT,
303            })
304            .collect();
305        // Degenerate propagating groups (single linkage), numbered 1, 2, ... in order.
306        let prop: Vec<usize> = (0..m2).filter(|&k| keys[k] == 1).collect();
307        let mut group: Vec<usize> = (0..prop.len()).collect();
308        for a in 0..prop.len() {
309            for b in 0..a {
310                if (lams[prop[a]].unwrap() - lams[prop[b]].unwrap()).norm() < DEGENERATE_TOL {
311                    let (ga, gb) = (group[a], group[b]);
312                    let (lo, hi) = (ga.min(gb), ga.max(gb));
313                    group.iter_mut().for_each(|g| {
314                        if *g == hi {
315                            *g = lo
316                        }
317                    });
318                }
319            }
320        }
321        let mut ids: Vec<usize> = group.clone();
322        ids.sort_unstable();
323        ids.dedup();
324        for (a, &k) in prop.iter().enumerate() {
325            keys[k] = 1 + ids.binary_search(&group[a]).expect("group id");
326        }
327
328        // Ordering A: right-evanescent, then the propagating groups (blocked partitions, then
329        // the few swaps that make each group contiguous).
330        let (mut qa, mut ta) = (q0.clone(), t0.clone());
331        let mut keys_a = keys.clone();
332        partition_by(&mut ta, &mut qa, &mut keys_a, |k| k == RIGHT);
333        partition_by(&mut ta, &mut qa, &mut keys_a, |k| k != LEFT);
334        caroli_dense::reorder(&mut ta, &mut qa, &mut keys_a);
335        let n_re = keys_a.iter().filter(|&&k| k == RIGHT).count();
336        let (mut right, mut left): (Vec<Vec<c64>>, Vec<Vec<c64>>) =
337            ((0..n_re).map(|k| (0..m2).map(|p| qa[(p, k)]).collect()).collect(), Vec::new());
338        let (mut rv, mut lv) = (Vec::new(), Vec::new());
339
340        // Propagating modes, in groups of (nearly) equal λ. Each member keeps its own eigenvalue.
341        // A numerically scalar group block (a true degeneracy) takes the Schur basis e_k on the
342        // group; otherwise each eigenvector is back-substituted within the group too, and a Jordan
343        // block (subband edge) shows up as nearly parallel vectors.
344        let tnorm = ta.norm_max();
345        // Unit-current mode vectors and their Bloch factors, going right and going left.
346        type Modes = Vec<(Vec<c64>, c64)>;
347        let (mut right_phi, mut left_phi): (Modes, Modes) = (Vec::new(), Vec::new());
348        let mut groups: Vec<(usize, usize, bool)> = Vec::new();
349        let mut g0 = n_re;
350        while g0 < m2 && keys_a[g0] != LEFT {
351            let mut g1 = g0 + 1;
352            while g1 < m2 && keys_a[g1] == keys_a[g0] {
353                g1 += 1;
354            }
355            let off = (g0..g1)
356                .flat_map(|a| (a + 1..g1).map(move |b| (a, b)))
357                .map(|(a, b)| ta[(a, b)].norm())
358                .fold(0.0, f64::max);
359            groups.push((g0, g1, off <= 1e-8 * tnorm));
360            g0 = g1;
361        }
362        let np = g0 - n_re;
363        // Eigenvectors of the Schur form (the columns of y), by column-oriented back-substitution.
364        let mut y = CMat::zeros(m2, np);
365        let mut lams: Vec<c64> = Vec::with_capacity(np);
366        let mut acc: Vec<c64> = Vec::with_capacity(m2);
367        for &(g0, g1, scalar) in &groups {
368            for k in g0..g1 {
369                let mu = ta[(k, k)];
370                lams.push(to_lambda(mu).ok_or(GreenError::Singular(z.re))?);
371                let col = y.col_as_slice_mut(k - n_re);
372                col[k] = one;
373                let start = if scalar { g0 } else { k };
374                acc.clear();
375                acc.extend(ta.col_as_slice(k)[..start].iter().map(|t| -t));
376                for j in (0..start).rev() {
377                    let d = ta[(j, j)] - mu;
378                    if d == zero {
379                        return Err(GreenError::Singular(z.re));
380                    }
381                    let yj = acc[j] / d;
382                    col[j] = yj;
383                    for (a, t) in acc[..j].iter_mut().zip(&ta.col_as_slice(j)[..j]) {
384                        *a -= yj * t;
385                    }
386                }
387            }
388        }
389        // x = Q y, normalised, and φ = G̃(−v α + s v γ + λ(s u α − u γ)) with (α, γ) = x.
390        let mut x = product(qa.as_ref(), Op::Plain, y.as_ref(), Op::Plain);
391        for p in 0..np {
392            let col = x.col_as_slice_mut(p);
393            let norm = col.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt();
394            if !(norm.is_finite() && norm > 0.0) {
395                return Err(GreenError::Singular(z.re));
396            }
397            col.iter_mut().for_each(|z| *z /= norm);
398        }
399        let bb = CMat::from_fn(r, np, |q, p| -x[(q, p)] + s * x[(r + q, p)]);
400        let cc = CMat::from_fn(r, np, |q, p| lams[p] * (s * x[(q, p)] - x[(r + q, p)]));
401        let mut phis = CMat::zeros(n, np);
402        matmul(phis.as_mut(), Accum::Replace, gv, Op::Plain, bb.as_ref(), Op::Plain, one);
403        matmul(phis.as_mut(), Accum::Add, gu, Op::Plain, cc.as_ref(), Op::Plain, one);
404        let h1phi = product(h1.as_ref(), Op::Plain, phis.as_ref(), Op::Plain);
405        let h1dphi = product(h1.as_ref(), Op::Adjoint, phis.as_ref(), Op::Plain);
406        // Current J_ab = i(λ_b φ_a† H1 φ_b − λ_a* φ_a† H1† φ_b) of each group, in the metric of the
407        // (α, γ) vectors; its inertia gives the right- and left-going modes.
408        for &(g0, g1, _) in &groups {
409            let (p0, m) = (g0 - n_re, g1 - g0);
410            let (xg, fg) = (x.as_ref().subcols(p0, m), phis.as_ref().subcols(p0, m));
411            let gram = product(xg, Op::Adjoint, xg, Op::Plain);
412            let a = product(fg, Op::Adjoint, h1phi.as_ref().subcols(p0, m), Op::Plain);
413            let b = product(fg, Op::Adjoint, h1dphi.as_ref().subcols(p0, m), Op::Plain);
414            let cur =
415                CMat::from_fn(m, m, |p, q| i * (lams[p0 + q] * a[(p, q)] - lams[p0 + p].conj() * b[(p, q)]));
416            let llt = gram.llt(Side::Lower).map_err(|_| GreenError::Singular(z.re))?;
417            let lch = llt.L().to_owned();
418            if inverse_condition(&lch) < DEFECTIVE_TOL {
419                return Err(GreenError::Singular(z.re)); // a Jordan block: subband edge
420            }
421            let linv = crate::inverse(&lch);
422            let jp = &linv * &cur * linv.adjoint();
423            let jh = CMat::from_fn(m, m, |p, q| (jp[(p, q)] + jp[(q, p)].conj()) * 0.5);
424            let evd = jh.self_adjoint_eigen(Side::Lower).map_err(|_| GreenError::Eigen)?;
425            let (vel, w) = (evd.S(), evd.U());
426            let coeffs = linv.adjoint() * w;
427            let (phi_k, x_k) = (
428                product(fg, Op::Plain, coeffs.as_ref(), Op::Plain),
429                product(xg, Op::Plain, coeffs.as_ref(), Op::Plain),
430            );
431            // The Bloch factor of a group: the mean of its members (equal to 1e-7).
432            let mean = lams[p0..p0 + m].iter().sum::<c64>() / m as f64;
433            let lambda = mean / mean.norm();
434            for k in 0..m {
435                let vk = vel[k].re / phi_k.col_as_slice(k).iter().map(|z| z.norm_sqr()).sum::<f64>();
436                if vk.is_nan() || vk.abs() < VELOCITY_TOL * scale {
437                    return Err(GreenError::Singular(z.re)); // subband edge
438                }
439                // J(φ_k, φ_k) = vel_k: unit current.
440                let flux: Vec<c64> =
441                    phi_k.col_as_slice(k).iter().map(|z| z / vel[k].re.abs().sqrt()).collect();
442                if vk > 0.0 {
443                    right.push(x_k.col_as_slice(k).to_vec());
444                    rv.push(vk);
445                    right_phi.push((flux, lambda));
446                } else {
447                    left.push(x_k.col_as_slice(k).to_vec());
448                    lv.push(vk);
449                    left_phi.push((flux, lambda));
450                }
451            }
452        }
453
454        // Ordering B: left-evanescent first.
455        let (mut qb, mut tb) = (q0, t0);
456        let left_evanescent: Vec<bool> = keys.iter().map(|&k| k == LEFT).collect();
457        let n_le = caroli_dense::partition(&mut tb, &mut qb, &left_evanescent);
458        left.extend((0..n_le).map(|k| (0..m2).map(|p| qb[(p, k)]).collect::<Vec<c64>>()));
459
460        if right.len() != r || left.len() != r {
461            return Err(GreenError::ModeCount { right: right.len(), left: left.len(), expected: r });
462        }
463        // Orthonormal bases; columns scaled to unit norm first (Householder QR errors are
464        // relative to the whole matrix).
465        let basis = |cols: &[Vec<c64>]| -> CMat {
466            let norms: Vec<f64> =
467                cols.iter().map(|c| c.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt()).collect();
468            caroli_dense::orthonormal_columns(
469                CMat::from_fn(m2, cols.len(), |p, q| cols[q][p] / norms[q]).as_ref(),
470            )
471        };
472        let (xb, yb) = (basis(&right), basis(&left));
473        let invertible =
474            |m: CMat| Lu::new(m.as_ref()).inverse_condition_1(norm_1(m.as_ref())) >= SINGULAR_TOL;
475        if !invertible(rows(&xb, 0..r)) || !invertible(rows(&yb, r..m2)) {
476            return Err(GreenError::Singular(z.re));
477        }
478        let columns = |modes: &[(Vec<c64>, c64)]| CMat::from_fn(n, modes.len(), |i, c| modes[c].0[i]);
479        Ok(Self {
480            u,
481            v,
482            right: xb,
483            left: yb,
484            right_velocities: rv,
485            left_velocities: lv,
486            right_modes: columns(&right_phi),
487            left_modes: columns(&left_phi),
488            right_lambdas: right_phi.iter().map(|m| m.1).collect(),
489            left_lambdas: left_phi.iter().map(|m| m.1).collect(),
490            energy: z,
491        })
492    }
493
494    /// Number of propagating channels in each direction.
495    pub fn channels(&self) -> usize {
496        self.right_velocities.len()
497    }
498
499    /// `Σ_R = u X_γ X_α⁻¹ u†`.
500    fn sigma_right(&self) -> CMat {
501        let (n, r) = (self.u.nrows(), self.u.ncols());
502        if r == 0 {
503            return CMat::zeros(n, n);
504        }
505        let t = solve_right(&rows(&self.right, r..2 * r), &rows(&self.right, 0..r));
506        sandwich(&self.u, &t)
507    }
508
509    /// `Σ_L = v Y_α Y_γ⁻¹ v†`.
510    fn sigma_left(&self) -> CMat {
511        let (n, r) = (self.v.nrows(), self.v.ncols());
512        if r == 0 {
513            return CMat::zeros(n, n);
514        }
515        let t = solve_right(&rows(&self.left, 0..r), &rows(&self.left, r..2 * r));
516        sandwich(&self.v, &t)
517    }
518}
519
520/// The part of a lead's mode problem that does not depend on the energy, prepared once: whether
521/// the coupling is Hermitian definite (the fast path of [`LeadModes::at`]) and, when it is a
522/// multiple of the identity (square and cubic lattices), the eigenvectors of the cell. Solvers
523/// keep one per lead and reuse it at every energy.
524#[derive(Clone, Debug)]
525pub struct ModeSolver {
526    h0: CMat,
527    h1: CMat,
528    definite: Option<DefiniteCoupling>,
529}
530
531impl ModeSolver {
532    /// Prepares the lead `(h0, h1)`, `h1 = ⟨j| H |j+1⟩`: detects a Hermitian definite coupling
533    /// and, for `h1 = ±c·1`, diagonalises the cell `h0` once.
534    pub fn new(h0: &CMat, h1: &CMat) -> Self {
535        Self { h0: h0.clone(), h1: h1.clone(), definite: DefiniteCoupling::new(h0, h1) }
536    }
537
538    /// Modes at `z`, as [`LeadModes::at`].
539    pub fn modes_at(&self, z: c64) -> Result<LeadModes, GreenError> {
540        let definite = self.definite.as_ref().filter(|_| z.im == 0.0);
541        LeadModes::shifted(&self.h0, &self.h1, z, |e, scale| match definite {
542            Some(d) => d.modes(&self.h0, e.re, scale),
543            None => LeadModes::solve(&self.h0, &self.h1, e, scale),
544        })
545    }
546}
547
548/// A Hermitian definite coupling `H1 = s P` (`s = ±1`, `P = L L† > 0`) with a Hermitian cell
549/// `H0`: square lattices, and multi-orbital leads without spin-orbit coupling or magnetic field
550/// along the axis.
551///
552/// At a real energy `E`, with `μ = λ + 1/λ`, the Bloch equation `H1† λ⁻¹ + H0 − E + H1 λ`
553/// becomes the Hermitian problem `(H0 − E) ψ = −s μ P ψ`. With `ψ = L⁻† y` it reads
554/// `L⁻¹ (H0 − E) L⁻† y = ν y`, `μ = −s ν`: one Hermitian eigenproblem of size n instead of a
555/// Schur decomposition of size 2n.
556/// - Each transverse mode `y` gives the two roots of `λ² − μλ + 1 = 0`. If `|μ| < 2` they are
557///   on the unit circle, and the current `J = −2 s Im λ ψ†Pψ` sorts them. Otherwise they are
558///   real, `|λ| < 1` going right.
559/// - With the factors `u = s L`, `v = L` of the coupling, a mode is `(α, γ) ∝ (s y, λ y)`, so
560///   the bases of right- and left-going modes are orthonormal as they stand, and `X_α`, `Y_γ`
561///   are never singular.
562///
563/// With `P = c·1`, `L⁻¹ (H0 − E) L⁻† = (H0 − E) / c` has the eigenvectors of `H0` at every
564/// energy: they are computed once.
565#[derive(Clone, Debug)]
566struct DefiniteCoupling {
567    s: f64,
568    l: CMat,
569    /// With `P = c·1`: `c` and the eigenvalues and eigenvectors of `H0`.
570    cell: Option<(f64, Vec<f64>, CMat)>,
571}
572
573impl DefiniteCoupling {
574    /// Largest `‖m − m†‖ / ‖m‖` for a Hermitian matrix.
575    const HERMITIAN_TOL: f64 = 1e-14;
576    /// Smallest ratio of the diagonal entries of `L` (a condition number of `P` below ~1e8).
577    const DEFINITE_TOL: f64 = 1e-4;
578
579    fn new(h0: &CMat, h1: &CMat) -> Option<Self> {
580        let n = h0.nrows();
581        let hermitian = |m: &CMat| {
582            let asym = (0..n)
583                .flat_map(|i| (0..n).map(move |j| (i, j)))
584                .map(|(i, j)| (m[(i, j)] - m[(j, i)].conj()).norm())
585                .fold(0.0, f64::max);
586            asym <= Self::HERMITIAN_TOL * m.norm_max()
587        };
588        if n == 0 || h1.norm_max() == 0.0 || !hermitian(h0) || !hermitian(h1) {
589            return None;
590        }
591        [-1.0, 1.0].into_iter().find_map(|s| {
592            let p = CMat::from_fn(n, n, |i, j| (h1[(i, j)] + h1[(j, i)].conj()) * (0.5 * s));
593            let l = p.llt(Side::Lower).ok()?.L().to_owned();
594            let (lo, hi) = (0..n).fold((f64::INFINITY, 0.0f64), |(lo, hi), i| {
595                (lo.min(l[(i, i)].norm()), hi.max(l[(i, i)].norm()))
596            });
597            if lo <= Self::DEFINITE_TOL * hi {
598                return None;
599            }
600            // P = c·1: the spectrum of the cell serves every energy.
601            let c = p[(0, 0)].re;
602            let scalar = (0..n).all(|i| {
603                (0..n).all(|j| {
604                    (p[(i, j)] - if i == j { c64::new(c, 0.0) } else { c64::new(0.0, 0.0) }).norm()
605                        <= Self::HERMITIAN_TOL * c
606                })
607            });
608            let cell = scalar.then(|| {
609                let h = CMat::from_fn(n, n, |i, j| (h0[(i, j)] + h0[(j, i)].conj()) * 0.5);
610                caroli_dense::hermitian_eigen(h.as_ref()).ok().map(|(theta, y)| (c, theta, y))
611            });
612            match cell.flatten() {
613                Some(cell) => {
614                    let root = c.sqrt();
615                    let l =
616                        CMat::from_fn(
617                            n,
618                            n,
619                            |i, j| if i == j { c64::new(root, 0.0) } else { c64::new(0.0, 0.0) },
620                        );
621                    Some(Self { s, l, cell: Some(cell) })
622                }
623                None => Some(Self { s, l, cell: None }),
624            }
625        })
626    }
627
628    /// Modes at the real energy `e`.
629    fn modes(&self, h0: &CMat, e: f64, scale: f64) -> Result<LeadModes, GreenError> {
630        use faer::linalg::triangular_solve::{
631            solve_lower_triangular_in_place, solve_upper_triangular_in_place,
632        };
633        let (n, s, l) = (h0.nrows(), self.s, &self.l);
634        let par = faer::get_global_parallelism();
635        // Eigenpairs (ν, y) of M = L⁻¹ (H0 − E) L⁻†.
636        let computed;
637        let (nu, y): (Vec<f64>, &CMat) = match &self.cell {
638            Some((c, theta, y)) => (theta.iter().map(|t| (t - e) / c).collect(), y),
639            None => {
640                let mut b = CMat::from_fn(n, n, |i, j| {
641                    (h0[(i, j)] + h0[(j, i)].conj()) * 0.5
642                        - if i == j { c64::new(e, 0.0) } else { c64::new(0.0, 0.0) }
643                });
644                solve_lower_triangular_in_place(l.as_ref(), b.as_mut(), par);
645                let mut m = b.adjoint().to_owned();
646                solve_lower_triangular_in_place(l.as_ref(), m.as_mut(), par);
647                let m = CMat::from_fn(n, n, |i, j| (m[(i, j)] + m[(j, i)].conj()) * 0.5);
648                let (w, v) = caroli_dense::hermitian_eigen(m.as_ref()).map_err(|_| GreenError::Eigen)?;
649                computed = v;
650                (w, &computed)
651            }
652        };
653
654        // The right- and left-going root of each transverse mode.
655        let (mut right, mut left, mut propagating) =
656            (Vec::with_capacity(n), Vec::with_capacity(n), Vec::new());
657        for (k, &nu_k) in nu.iter().enumerate() {
658            let mu = -s * nu_k;
659            if mu.abs() < 2.0 {
660                // J ∝ −s Im λ: the root with s Im λ < 0 goes right. Roots closer than the
661                // degeneracy tolerance form a Jordan block, as in the general algorithm.
662                let root = c64::new(mu / 2.0, (4.0 - mu * mu).sqrt() / 2.0);
663                if 2.0 * root.im < DEGENERATE_TOL {
664                    return Err(GreenError::Singular(e)); // subband edge
665                }
666                let (r, lft) = if s < 0.0 { (root, root.conj()) } else { (root.conj(), root) };
667                right.push(r);
668                left.push(lft);
669                propagating.push(k);
670            } else {
671                let big = (mu + mu.signum() * (mu * mu - 4.0).sqrt()) / 2.0;
672                if big.abs() <= 1.0 + UNIT_TOL {
673                    return Err(GreenError::Singular(e)); // subband edge (λ = ±1)
674                }
675                right.push(c64::new(1.0 / big, 0.0));
676                left.push(c64::new(big, 0.0));
677            }
678        }
679        // Velocities J / ψ†ψ of the propagating modes, ψ = L⁻† y (P-normalised).
680        let mut psi = CMat::from_fn(n, propagating.len(), |i, c| y[(i, propagating[c])]);
681        match &self.cell {
682            Some((c, _, _)) => psi.col_iter_mut().for_each(|col| col.iter_mut().for_each(|z| *z /= c.sqrt())),
683            None => solve_upper_triangular_in_place(l.adjoint(), psi.as_mut(), par),
684        }
685        let (mut rv, mut lv) = (Vec::with_capacity(propagating.len()), Vec::with_capacity(propagating.len()));
686        for (c, &k) in propagating.iter().enumerate() {
687            let v = -2.0 * s * right[k].im / psi.col_as_slice(c).iter().map(|z| z.norm_sqr()).sum::<f64>();
688            let fast = v.abs() >= VELOCITY_TOL * scale; // false for NaN
689            if !fast {
690                return Err(GreenError::Singular(e)); // subband edge
691            }
692            rv.push(v);
693            lv.push(-v);
694        }
695        // ψ is P-normalised, so J(ψ, ψ) = −2 s Im λ: unit current after dividing by its root.
696        let flux = CMat::from_fn(n, propagating.len(), |i, c| {
697            psi[(i, c)] / (2.0 * right[propagating[c]].im.abs()).sqrt()
698        });
699        let basis = |lams: &[c64]| {
700            CMat::from_fn(2 * n, n, |p, k| {
701                let c = 1.0 / (1.0 + lams[k].norm_sqr()).sqrt();
702                if p < n { y[(p, k)] * (s * c) } else { y[(p - n, k)] * lams[k] * c }
703            })
704        };
705        Ok(LeadModes {
706            u: CMat::from_fn(n, n, |i, j| l[(i, j)] * s),
707            v: l.clone(),
708            right: basis(&right),
709            left: basis(&left),
710            right_velocities: rv,
711            left_velocities: lv,
712            right_modes: flux.clone(),
713            left_modes: flux,
714            right_lambdas: propagating.iter().map(|&k| right[k]).collect(),
715            left_lambdas: propagating.iter().map(|&k| left[k]).collect(),
716            energy: c64::new(e, 0.0),
717        })
718    }
719}
720
721/// Self-energy of a right lead (towards +∞) on the slice it touches. `h1` is the coupling the
722/// modes were computed with (kept for the signature; the modes hold its factors).
723pub fn sigma_right(h1: &CMat, modes: &LeadModes) -> CMat {
724    debug_assert_eq!(h1.nrows(), modes.u.nrows());
725    modes.sigma_right()
726}
727
728/// Self-energy of a left lead (towards −∞) on the slice it touches.
729pub fn sigma_left(h1: &CMat, modes: &LeadModes) -> CMat {
730    debug_assert_eq!(h1.nrows(), modes.v.nrows());
731    modes.sigma_left()
732}
733
734/// Surface Green's function of a right lead from its modes, `g = (E − H0 − Σ_R)⁻¹`.
735pub fn surface_green_right(h0: &CMat, h1: &CMat, energy: f64, modes: &LeadModes) -> CMat {
736    let n = h0.nrows();
737    let s = sigma_right(h1, modes);
738    crate::inverse(&CMat::from_fn(n, n, |i, j| {
739        (if i == j { c64::new(energy, 0.0) } else { c64::new(0.0, 0.0) }) - h0[(i, j)] - s[(i, j)]
740    }))
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746    use caroli_lattice::{Lattice, Region};
747    use caroli_model::Model;
748
749    /// Cell and coupling of a lead along the first primitive vector, `w` cells wide.
750    fn lead(model: &Model, w: usize) -> (CMat, CMat) {
751        let region = Region::cuboid(model.lattice(), [2, w, 0]);
752        let slices = region.slices(0);
753        (model.hamiltonian(&slices[0]), model.coupling(&slices[0], &slices[1]))
754    }
755
756    /// The real pencil and its real Schur form give the self-energies of the complex ones.
757    #[test]
758    fn real_pencil_matches_complex() {
759        let graphene = Model::new(Lattice::honeycomb(1.0, 1))
760            .hopping(0, 1, [0, 0, 0], -1.0)
761            .hopping(0, 1, [0, -1, 0], -1.0)
762            .hopping(0, 1, [1, -1, 0], -1.0);
763        // Square lattice with diagonal hoppings: a Hermitian coupling that is not definite.
764        let square = Model::new(Lattice::square(1.0, 1))
765            .onsite(0, 0.3)
766            .hopping(0, 0, [1, 0, 0], -1.0)
767            .hopping(0, 0, [0, 1, 0], -1.0)
768            .hopping(0, 0, [1, 1, 0], -0.45)
769            .hopping(0, 0, [1, -1, 0], 0.2);
770        for (name, model, w) in [("graphene", &graphene, 7), ("square", &square, 6)] {
771            let (h0, h1) = lead(model, w);
772            assert!(caroli_dense::is_real(h0.as_ref()) && caroli_dense::is_real(h1.as_ref()));
773            let scale = row_norm(&h0) + 2.0 * row_norm(&h1);
774            let mut compared = 0;
775            for e in [-2.3, -1.1, -0.35, 0.05, 0.42, 1.3, 2.6] {
776                let z = c64::new(e, 0.0);
777                let (Ok(re), Ok(cx)) = (
778                    LeadModes::solve_with(&h0, &h1, z, scale, true),
779                    LeadModes::solve_with(&h0, &h1, z, scale, false),
780                ) else {
781                    continue; // a subband edge for both
782                };
783                let d = |a: &CMat, b: &CMat| (a - b).norm_max();
784                assert!(d(&re.sigma_right(), &cx.sigma_right()) < 1e-10, "{name} E = {e}: Σ_R");
785                assert!(d(&re.sigma_left(), &cx.sigma_left()) < 1e-10, "{name} E = {e}: Σ_L");
786                assert_eq!(re.right_velocities.len(), cx.right_velocities.len(), "{name} E = {e}");
787                compared += 1;
788            }
789            assert!(compared >= 6, "{name}: {compared} energies compared");
790        }
791    }
792}