1use crate::{GreenError, sandwich, solve_right};
28use caroli_dense::{Accum, Lu, Op, matmul, norm_1, product};
29use caroli_model::{CMat, c64};
30use faer::Side;
31
32const RANK_TOL: f64 = 1e-12;
34const UNIT_TOL: f64 = 1e-6;
36const DEGENERATE_TOL: f64 = 1e-7;
38const VELOCITY_TOL: f64 = 1e-8;
40const DEFECTIVE_TOL: f64 = 1e-7;
43const SINGULAR_TOL: f64 = 1e-11;
46const REAL_STABILISATION: f64 = 0.618_033_988_749_894_8;
49const SHIFTS: [f64; 5] = [0.0, 1e-9, 1e-8, 1e-7, 1e-6];
51
52#[derive(Clone, Debug)]
54pub struct LeadModes {
55 pub u: CMat,
57 pub v: CMat,
59 pub right: CMat,
61 pub left: CMat,
63 pub right_velocities: Vec<f64>,
65 pub left_velocities: Vec<f64>,
68 pub right_modes: CMat,
72 pub left_modes: CMat,
75 pub right_lambdas: Vec<c64>,
77 pub left_lambdas: Vec<c64>,
79 pub energy: c64,
81}
82
83fn 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
92fn 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
101fn 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 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 pub fn at(h0: &CMat, h1: &CMat, z: c64) -> Result<Self, GreenError> {
126 ModeSolver::new(h0, h1).modes_at(z)
127 }
128
129 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 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 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 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 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 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 let (lo, hi) = lu_a.pivot_range();
205 let conditioned = lo > 1e-10 * hi; 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 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 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 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 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 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, _ => LEFT,
303 })
304 .collect();
305 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 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 let tnorm = ta.norm_max();
345 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 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 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 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)); }
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 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)); }
439 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 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 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 pub fn channels(&self) -> usize {
496 self.right_velocities.len()
497 }
498
499 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 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#[derive(Clone, Debug)]
525pub struct ModeSolver {
526 h0: CMat,
527 h1: CMat,
528 definite: Option<DefiniteCoupling>,
529}
530
531impl ModeSolver {
532 pub fn new(h0: &CMat, h1: &CMat) -> Self {
535 Self { h0: h0.clone(), h1: h1.clone(), definite: DefiniteCoupling::new(h0, h1) }
536 }
537
538 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#[derive(Clone, Debug)]
566struct DefiniteCoupling {
567 s: f64,
568 l: CMat,
569 cell: Option<(f64, Vec<f64>, CMat)>,
571}
572
573impl DefiniteCoupling {
574 const HERMITIAN_TOL: f64 = 1e-14;
576 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 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 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 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 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 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)); }
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)); }
675 right.push(c64::new(1.0 / big, 0.0));
676 left.push(c64::new(big, 0.0));
677 }
678 }
679 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; if !fast {
690 return Err(GreenError::Singular(e)); }
692 rv.push(v);
693 lv.push(-v);
694 }
695 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
721pub fn sigma_right(h1: &CMat, modes: &LeadModes) -> CMat {
724 debug_assert_eq!(h1.nrows(), modes.u.nrows());
725 modes.sigma_right()
726}
727
728pub fn sigma_left(h1: &CMat, modes: &LeadModes) -> CMat {
730 debug_assert_eq!(h1.nrows(), modes.v.nrows());
731 modes.sigma_left()
732}
733
734pub 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 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 #[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 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; };
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}