1use crate::gauge::Gauge;
26use crate::modes::{ModeSolver, sigma_left, sigma_right};
27use crate::{GreenError, Lead, broadening, caroli_trace};
28use crate::{Precision, PrecisionOptions, PrecisionReport};
29use caroli_dense::{Accum, Field, Lu, Mat, Op, c32, matmul, product};
30use caroli_lattice::{Region, Site};
31use caroli_model::{CMat, Model, SparseMatrix, c64};
32use std::sync::Arc;
33
34const LEAF_ORBITALS: usize = 16;
36const SMALL_FRONT: usize = 64;
39
40#[derive(Clone, Debug)]
42struct Node {
43 eliminate: Vec<usize>,
45 boundary: Vec<usize>,
47 children: Vec<usize>,
48}
49
50#[derive(Clone, Debug)]
53pub(crate) struct SiteTree {
54 nodes: Vec<(Vec<usize>, Vec<usize>)>,
56 top: Vec<usize>,
58}
59
60impl SiteTree {
61 pub(crate) fn new(device: &Model, region: &Region, interior: Vec<usize>) -> Self {
63 let mut range = [1i64; 3];
64 for hop in device.hoppings() {
65 for (d, r) in range.iter_mut().enumerate() {
66 *r = (*r).max(hop.offset[d].abs());
67 }
68 }
69 let mut nodes = Vec::new();
70 let top = split(region, interior, &range, &mut nodes).into_iter().collect();
71 Self { nodes, top }
72 }
73
74 pub(crate) fn tree(&self, region: &Region, h: &SparseMatrix, mine: impl Fn(usize) -> bool) -> Tree {
76 let block_orbitals = |sites: &[usize]| -> Vec<usize> {
77 let mut v: Vec<usize> = sites
78 .iter()
79 .flat_map(|&i| region.offset(i)..region.offset(i) + region.site_orbitals(i))
80 .filter(|&o| mine(o))
81 .collect();
82 v.sort_unstable();
83 v
84 };
85 let mut nodes: Vec<Node> = self
86 .nodes
87 .iter()
88 .map(|(sites, children)| Node {
89 eliminate: block_orbitals(sites),
90 boundary: Vec::new(),
91 children: children.clone(),
92 })
93 .collect();
94 symbolic(h, &mut nodes);
95 let plans = (0..nodes.len()).map(|k| Plan::new(h, &nodes, k)).collect();
96 Tree { nodes, top: self.top.clone(), plans }
97 }
98}
99
100#[derive(Clone, Debug)]
102pub(crate) struct Tree {
103 nodes: Vec<Node>,
104 top: Vec<usize>,
106 plans: Vec<Plan>,
108}
109
110#[derive(Clone, Debug)]
114struct Plan {
115 vars: Vec<usize>,
117 ne: usize,
119 diagonal: Vec<usize>,
121 entries: Vec<(usize, usize, c64)>,
123 children: Vec<Vec<(usize, usize, usize)>>,
125}
126
127impl Plan {
128 fn new(h: &SparseMatrix, nodes: &[Node], k: usize) -> Self {
129 let node = &nodes[k];
130 let children: Vec<&[usize]> = node.children.iter().map(|&c| nodes[c].boundary.as_slice()).collect();
131 let (vars, ne) = front_vars(node, &children);
132 let pos = Positions::new(&vars);
133 let mut entries = Vec::new();
134 separator_entries(h, node, &pos, |a, b, v| entries.push((a, b, v)));
135 Self {
136 diagonal: node.eliminate.iter().map(|&i| pos.get(i).unwrap()).collect(),
137 entries,
138 children: children.iter().map(|vars| runs(vars, &pos)).collect(),
139 vars,
140 ne,
141 }
142 }
143}
144
145fn front_vars(node: &Node, children: &[&[usize]]) -> (Vec<usize>, usize) {
149 let in_boundary = |o: usize| node.boundary.binary_search(&o).is_ok();
150 let mut elim: Vec<usize> = node.eliminate.clone();
151 for vars in children {
152 elim.extend(vars.iter().copied().filter(|&o| !in_boundary(o)));
153 }
154 elim.sort_unstable();
155 elim.dedup();
156 let ne = elim.len();
157 elim.extend_from_slice(&node.boundary);
158 (elim, ne)
159}
160
161fn separator_entries(h: &SparseMatrix, node: &Node, pos: &Positions, mut add: impl FnMut(usize, usize, c64)) {
165 let in_boundary = |o: usize| node.boundary.binary_search(&o).is_ok();
166 for &i in &node.eliminate {
167 let pi = pos.get(i).unwrap();
168 for (j, hij) in h.row(i) {
169 if j == i {
170 add(pi, pi, hij);
171 } else if let Some(pj) = pos.get(j) {
172 let later = if node.eliminate.binary_search(&j).is_ok() { j > i } else { in_boundary(j) };
173 if later {
174 add(pi, pj, hij);
175 add(pj, pi, hij.conj());
176 }
177 }
178 }
179 }
180}
181
182struct Front<T> {
186 vars: Vec<usize>,
187 s: Mat<T>,
188 factor: Option<Factor>,
189}
190
191pub(crate) struct Factor {
195 pub(crate) elim: Vec<usize>,
196 pub(crate) boundary: Vec<usize>,
197 pub(crate) x: CMat,
198 pub(crate) children: Vec<Factor>,
199}
200
201impl Factor {
202 pub(crate) fn back_substitute(&self, psi: &mut CMat) {
205 if !self.elim.is_empty() {
206 let cols = psi.ncols();
207 let b = CMat::from_fn(self.boundary.len(), cols, |a, c| psi[(self.boundary[a], c)]);
208 let mut e = CMat::zeros(self.elim.len(), cols);
209 matmul(
210 e.as_mut(),
211 Accum::Replace,
212 self.x.as_ref(),
213 Op::Plain,
214 b.as_ref(),
215 Op::Plain,
216 c64::new(-1.0, 0.0),
217 );
218 for (a, &o) in self.elim.iter().enumerate() {
219 for c in 0..cols {
220 psi[(o, c)] = e[(a, c)];
221 }
222 }
223 }
224 for child in &self.children {
225 child.back_substitute(psi);
226 }
227 }
228}
229
230pub(crate) struct Root {
232 pub(crate) delayed: Vec<usize>,
234 pub(crate) f: CMat,
235 pub(crate) factors: Vec<Factor>,
237}
238
239impl Tree {
240 pub(crate) fn root(
248 &self,
249 h: &SparseMatrix,
250 z: c64,
251 kept: &[usize],
252 keep: bool,
253 precision: Precision,
254 ) -> Result<Root, GreenError> {
255 let kids = match precision {
256 Precision::Double => self.fronts::<c64>(h, &self.top, z, keep)?,
257 Precision::Single => self
258 .fronts::<c32>(h, &self.top, z, keep)?
259 .into_iter()
260 .map(|kid| Front { vars: kid.vars, s: c32::into_c64(kid.s), factor: kid.factor })
261 .collect(),
262 };
263 let in_kept = Positions::new(kept);
264 let mut delayed: Vec<usize> =
265 kids.iter().flat_map(|k| k.vars.iter().copied()).filter(|&o| in_kept.get(o).is_none()).collect();
266 delayed.sort_unstable();
267 delayed.dedup();
268 let vars: Vec<usize> = delayed.iter().chain(kept).copied().collect();
269 let pos = Positions::new(&vars);
270 let mut f = CMat::zeros(vars.len(), vars.len());
271 for &i in kept {
272 let pi = pos.get(i).unwrap();
273 f[(pi, pi)] += z;
274 for (j, hij) in h.row(i) {
275 if in_kept.get(j).is_some() {
276 f[(pi, pos.get(j).unwrap())] -= hij;
277 }
278 }
279 }
280 let factors = extend_add(&mut f, &pos, kids);
281 Ok(Root { delayed, f, factors })
282 }
283
284 fn fronts<T: Field>(
286 &self,
287 h: &SparseMatrix,
288 nodes: &[usize],
289 z: c64,
290 keep: bool,
291 ) -> Result<Vec<Front<T>>, GreenError> {
292 match nodes {
293 [] => Ok(Vec::new()),
294 [a] => Ok(vec![self.front(h, *a, z, keep)?]),
295 [a, b] => {
296 let (x, y) = rayon::join(|| self.front(h, *a, z, keep), || self.front(h, *b, z, keep));
297 Ok(vec![x?, y?])
298 }
299 _ => nodes.iter().map(|&k| self.front(h, k, z, keep)).collect(),
300 }
301 }
302
303 fn front<T: Field>(
306 &self,
307 h: &SparseMatrix,
308 k: usize,
309 z: c64,
310 keep: bool,
311 ) -> Result<Front<T>, GreenError> {
312 let node = &self.nodes[k];
313 let kids = self.fronts::<T>(h, &node.children, z, keep)?;
314 let plan = &self.plans[k];
315 let planned = kids.iter().zip(&node.children).all(|(kid, &c)| kid.vars == self.nodes[c].boundary);
316 let zt = T::from_c64(z);
317 let (vars, ne, f, children) = if planned {
318 let n = plan.vars.len();
319 let mut f = Mat::<T>::zeros(n, n);
320 for &(a, b, v) in &plan.entries {
321 f[(a, b)] -= T::from_c64(v);
322 }
323 for &a in &plan.diagonal {
324 f[(a, a)] += zt;
325 }
326 let mut factors = Vec::new();
327 for (kid, runs) in kids.into_iter().zip(&plan.children) {
328 add_runs(&mut f, runs, &kid.s);
329 factors.extend(kid.factor);
330 }
331 (None, plan.ne, f, factors)
332 } else {
333 let handed: Vec<&[usize]> = kids.iter().map(|kid| kid.vars.as_slice()).collect();
335 let (vars, ne) = front_vars(node, &handed);
336 let pos = Positions::new(&vars);
337 let mut f = Mat::<T>::zeros(vars.len(), vars.len());
338 separator_entries(h, node, &pos, |a, b, v| f[(a, b)] -= T::from_c64(v));
339 for &i in &node.eliminate {
340 let pi = pos.get(i).unwrap();
341 f[(pi, pi)] += zt;
342 }
343 let children = extend_add(&mut f, &pos, kids);
344 (Some(vars), ne, f, children)
345 };
346 let owned = |vars: Option<Vec<usize>>| vars.unwrap_or_else(|| plan.vars.clone());
349 let delayed = |vars: Vec<usize>, f: Mat<T>, children: Vec<Factor>| Front {
350 factor: keep.then(|| Factor {
351 elim: Vec::new(),
352 boundary: Vec::new(),
353 x: CMat::zeros(0, 0),
354 children,
355 }),
356 vars,
357 s: f,
358 };
359 if ne == 0 {
360 return Ok(delayed(owned(vars), f, children));
361 }
362 let eliminated = if f.nrows() < SMALL_FRONT { small_schur(&f, ne, keep) } else { schur(&f, ne) };
363 match eliminated {
364 Some((s, x)) => Ok(Front {
365 vars: node.boundary.clone(),
366 s,
367 factor: keep.then(|| Factor {
368 elim: vars.as_deref().unwrap_or(&plan.vars)[..ne].to_vec(),
369 boundary: node.boundary.clone(),
370 x: T::into_c64(x),
371 children,
372 }),
373 }),
374 None => Ok(delayed(owned(vars), f, children)),
376 }
377 }
378}
379
380pub(crate) struct Components(Vec<usize>);
382
383impl Components {
384 pub(crate) fn new(n: usize) -> Self {
385 Self((0..n).collect())
386 }
387
388 fn find(&mut self, mut i: usize) -> usize {
389 while self.0[i] != i {
390 self.0[i] = self.0[self.0[i]];
391 i = self.0[i];
392 }
393 i
394 }
395
396 pub(crate) fn join(&mut self, a: usize, b: usize) {
397 let (ra, rb) = (self.find(a), self.find(b));
398 if ra != rb {
399 self.0[ra.max(rb)] = ra.min(rb);
400 }
401 }
402
403 pub(crate) fn join_matrix(&mut self, m: &CMat, rows: &[usize], cols: &[usize]) {
405 for b in 0..m.ncols() {
406 for a in 0..m.nrows() {
407 if m[(a, b)] != c64::new(0.0, 0.0) {
408 self.join(rows[a], cols[b]);
409 }
410 }
411 }
412 }
413
414 pub(crate) fn labels(mut self) -> (Vec<usize>, Vec<usize>) {
416 let n = self.0.len();
417 let roots: Vec<usize> = (0..n).map(|i| self.find(i)).collect();
418 let mut labels = roots.clone();
419 labels.sort_unstable();
420 labels.dedup();
421 (roots, labels)
422 }
423}
424
425#[derive(Clone, Debug)]
430struct Block {
431 tree: Tree,
432 left: Arc<Lead>,
433 right: Arc<Lead>,
434 left_modes: ModeSolver,
436 right_modes: ModeSolver,
437 left_orbitals: Arc<[usize]>,
439 right_orbitals: Arc<[usize]>,
440}
441
442#[derive(Clone, Debug)]
445pub struct LeadSelfEnergies {
446 energy: f64,
447 blocks: Vec<BlockSelfEnergies>,
448}
449
450impl LeadSelfEnergies {
451 pub fn energy(&self) -> f64 {
453 self.energy
454 }
455}
456
457#[derive(Clone, Debug)]
460struct BlockSelfEnergies {
461 left: Arc<Lead>,
462 right: Arc<Lead>,
463 left_orbitals: Arc<[usize]>,
464 right_orbitals: Arc<[usize]>,
465 sigma_l: CMat,
466 sigma_r: CMat,
467}
468
469fn same_lead(a: &Lead, b: &Lead) -> bool {
470 a.h00 == b.h00 && a.h01 == b.h01
471}
472
473fn same_shared_lead(a: &Arc<Lead>, b: &Arc<Lead>) -> bool {
475 Arc::ptr_eq(a, b) || same_lead(a, b)
476}
477
478#[derive(Clone, Debug)]
480pub struct NestedTwoTerminal {
481 h: SparseMatrix,
482 region: Region,
483 blocks: Vec<Block>,
484}
485
486#[derive(Clone, Debug)]
489pub struct ScatteringStates {
490 pub energy: f64,
492 pub leads: Vec<CMat>,
497}
498
499impl ScatteringStates {
500 pub fn occupation(&self, f: &[f64]) -> Vec<f64> {
504 assert_eq!(f.len(), self.leads.len(), "one occupation per lead");
505 let n = self.leads.first().map_or(0, |m| m.nrows());
506 (0..n)
507 .map(|a| {
508 let weight = |m: &CMat| (0..m.ncols()).map(|c| m[(a, c)].norm_sqr()).sum::<f64>();
509 self.leads.iter().zip(f).map(|(m, fp)| fp * weight(m)).sum::<f64>()
510 / (2.0 * std::f64::consts::PI)
511 })
512 .collect()
513 }
514}
515
516#[derive(Clone, Copy, Debug, PartialEq)]
519pub struct BondCurrent {
520 pub from: Site,
522 pub to: Site,
524 pub current: f64,
527}
528
529pub(crate) struct Positions(Vec<(usize, usize)>);
531
532impl Positions {
533 pub(crate) fn new(vars: &[usize]) -> Self {
534 let mut v: Vec<(usize, usize)> = vars.iter().enumerate().map(|(k, &x)| (x, k)).collect();
535 v.sort_unstable();
536 Self(v)
537 }
538
539 pub(crate) fn get(&self, x: usize) -> Option<usize> {
540 self.0.binary_search_by_key(&x, |&(y, _)| y).ok().map(|k| self.0[k].1)
541 }
542}
543
544impl NestedTwoTerminal {
545 pub fn from_model(device: &Model, lead: &Model, region: &Region, axis: usize) -> Self {
549 for hop in lead.hoppings() {
550 assert!(hop.offset[axis].abs() <= 1, "a lead hopping skips a cell along axis {axis}");
551 }
552 crate::gauge::assert_same_field(device, lead);
553 let slices = region.slices(axis);
554 let mut step = [0i64; 3];
555 step[axis] = 1;
556 let mut h = device.sparse_hamiltonian(region);
558 Gauge::along(device, step).transform_sparse(&mut h, region);
559 let lead_gauge = Gauge::along(lead, step);
560 let (first, last) = (&slices[0], &slices[slices.len() - 1]);
561 let (h00, h01) = lead_gauge.lead(first, step, [-step[0], -step[1], -step[2]]);
562 let left = Lead { h00, h01 };
563 let (h00, h01) = lead_gauge.lead(last, step, step);
564 let right = Lead { h00, h01 };
565 let orbitals_of = |s: &Region| -> Vec<usize> {
566 s.sites()
567 .iter()
568 .flat_map(|site| {
569 let i = region.index_of(site).expect("slice site in the region");
570 let o = region.offset(i);
571 o..o + region.site_orbitals(i)
572 })
573 .collect()
574 };
575 let (left_orbitals, right_orbitals) = (orbitals_of(first), orbitals_of(last));
576
577 let ends = [first.sites()[0].cell[axis], last.sites()[0].cell[axis]];
579 let interior: Vec<usize> =
580 (0..region.len()).filter(|&i| !ends.contains(®ion.sites()[i].cell[axis])).collect();
581 let sites = SiteTree::new(device, region, interior);
582
583 let mut components = Components::new(h.n);
585 for r in 0..h.n {
586 for (c, v) in h.row(r) {
587 if v != c64::new(0.0, 0.0) {
588 components.join(r, c);
589 }
590 }
591 }
592 for (lead, orbs) in [(&left, &left_orbitals), (&right, &right_orbitals)] {
593 components.join_matrix(&lead.h00, orbs, orbs);
594 components.join_matrix(&lead.h01, orbs, orbs);
595 }
596 let (roots, labels) = components.labels();
597
598 let blocks = labels
599 .iter()
600 .map(|&label| {
601 let mine = |o: usize| roots[o] == label;
602 let pick =
603 |orbs: &[usize]| -> Vec<usize> { (0..orbs.len()).filter(|&k| mine(orbs[k])).collect() };
604 let (kl, kr) = (pick(&left_orbitals), pick(&right_orbitals));
605 let restrict =
606 |m: &CMat, k: &[usize]| CMat::from_fn(k.len(), k.len(), |a, b| m[(k[a], k[b])]);
607 let block_left = Lead { h00: restrict(&left.h00, &kl), h01: restrict(&left.h01, &kl) };
608 let block_right = Lead { h00: restrict(&right.h00, &kr), h01: restrict(&right.h01, &kr) };
609 let left_modes = ModeSolver::new(&block_left.h00, &block_left.h01);
610 let right_modes = if same_lead(&block_left, &block_right) {
611 left_modes.clone()
612 } else {
613 ModeSolver::new(&block_right.h00, &block_right.h01)
614 };
615 Block {
616 tree: sites.tree(region, &h, mine),
617 left: Arc::new(block_left),
618 right: Arc::new(block_right),
619 left_modes,
620 right_modes,
621 left_orbitals: kl.iter().map(|&k| left_orbitals[k]).collect(),
622 right_orbitals: kr.iter().map(|&k| right_orbitals[k]).collect(),
623 }
624 })
625 .filter(|b: &Block| !b.left_orbitals.is_empty() && !b.right_orbitals.is_empty())
626 .collect();
627 Self { h, region: region.clone(), blocks }
628 }
629
630 pub fn block_count(&self) -> usize {
632 self.blocks.len()
633 }
634
635 pub fn transmission(&self, energy: f64) -> Result<f64, GreenError> {
637 self.transmission_with(&self.self_energies(energy)?)
638 }
639
640 pub fn transmissions(&self, energies: &[f64]) -> Vec<Result<f64, GreenError>> {
642 use rayon::prelude::*;
643 energies.par_iter().map(|&e| self.transmission(e)).collect()
644 }
645
646 pub fn transmissions_checked(
649 &self,
650 energies: &[f64],
651 options: &PrecisionOptions,
652 ) -> (Vec<Result<f64, GreenError>>, PrecisionReport) {
653 crate::checked(
654 energies,
655 options,
656 |&e, p| self.transmission_with_precision(&self.self_energies(e)?, p),
657 |a, b| (a - b).abs(),
658 )
659 }
660
661 pub fn self_energies(&self, energy: f64) -> Result<LeadSelfEnergies, GreenError> {
671 use rayon::prelude::*;
672 let z = c64::new(energy, 0.0);
673 let blocks = self
674 .blocks
675 .par_iter()
676 .map(|block| {
677 let ml = block.left_modes.modes_at(z)?;
679 let own = if same_lead(&block.left, &block.right) {
680 None
681 } else {
682 Some(block.right_modes.modes_at(z)?)
683 };
684 let mr = own.as_ref().unwrap_or(&ml);
685 Ok(BlockSelfEnergies {
686 left: Arc::clone(&block.left),
687 right: Arc::clone(&block.right),
688 left_orbitals: Arc::clone(&block.left_orbitals),
689 right_orbitals: Arc::clone(&block.right_orbitals),
690 sigma_l: sigma_left(&block.left.h01, &ml),
691 sigma_r: sigma_right(&block.right.h01, mr),
692 })
693 })
694 .collect::<Result<Vec<_>, GreenError>>()?;
695 Ok(LeadSelfEnergies { energy, blocks })
696 }
697
698 pub fn transmission_with(&self, sigma: &LeadSelfEnergies) -> Result<f64, GreenError> {
703 self.transmission_with_precision(sigma, Precision::Double)
704 }
705
706 pub fn transmission_with_precision(
709 &self,
710 sigma: &LeadSelfEnergies,
711 precision: Precision,
712 ) -> Result<f64, GreenError> {
713 use rayon::prelude::*;
714 assert_eq!(sigma.blocks.len(), self.blocks.len(), "self-energies of a system with other blocks");
715 let z = c64::new(sigma.energy, 0.0);
716 let parts: Vec<Result<f64, GreenError>> = self
717 .blocks
718 .par_iter()
719 .zip(&sigma.blocks)
720 .map(|(block, s)| {
721 assert!(
722 same_shared_lead(&block.left, &s.left)
723 && same_shared_lead(&block.right, &s.right)
724 && block.left_orbitals == s.left_orbitals
725 && block.right_orbitals == s.right_orbitals,
726 "self-energies of a system with other leads"
727 );
728 let g_lr = self.lead_green(block, z, &s.sigma_l, &s.sigma_r, precision)?;
729 Ok(caroli_trace(&broadening(&s.sigma_l), &g_lr, &broadening(&s.sigma_r)))
730 })
731 .collect();
732 parts.into_iter().sum()
733 }
734
735 pub fn smatrix(&self, energy: f64) -> Result<crate::SMatrix, GreenError> {
738 use crate::smatrix::{BlockScattering, LeadSolution, ScatteringLead, scattering_blocks};
739 use std::rc::Rc;
740 let z = c64::new(energy, 0.0);
741 let mut parts: Vec<BlockScattering> = Vec::with_capacity(self.blocks.len());
742 for block in &self.blocks {
743 let left_out = block.left.h01.adjoint().to_owned();
745 let left = Rc::new(LeadSolution::new(&block.left.h00, &left_out, z)?);
746 let right = Rc::new(LeadSolution::new(&block.right.h00, &block.right.h01, z)?);
747 let (sigma_l, sigma_r) = (left.self_energy(&left_out), right.self_energy(&block.right.h01));
748 let root = self.root_with_leads(block, z, &sigma_l, &sigma_r, false, Precision::Double)?;
749 let k = root.s.nrows();
750 let green = Lu::new(root.s.as_ref()).solve(CMat::identity(k, k).as_ref());
751 if !green.norm_max().is_finite() {
752 return Err(GreenError::Singular(energy));
753 }
754 let (nl, nr) = (block.left_orbitals.len(), block.right_orbitals.len());
755 let leads = [
756 Some(ScatteringLead {
757 at: (0..nl).collect(),
758 coupling: &left_out,
759 h01: &left_out,
760 solution: left,
761 }),
762 Some(ScatteringLead {
763 at: (root.right..root.right + nr).collect(),
764 coupling: &block.right.h01,
765 h01: &block.right.h01,
766 solution: right,
767 }),
768 ];
769 parts.push(scattering_blocks(&green, &leads));
770 }
771 Ok(crate::SMatrix::assemble(energy, parts))
772 }
773
774 pub fn transmission_eigenvalues(&self, energy: f64) -> Result<Vec<f64>, GreenError> {
778 let sigma = self.self_energies(energy)?;
779 let z = c64::new(energy, 0.0);
780 let mut taus = Vec::new();
781 for (block, s) in self.blocks.iter().zip(&sigma.blocks) {
782 let g_lr = self.lead_green(block, z, &s.sigma_l, &s.sigma_r, Precision::Double)?;
783 let (wl, wr) = (gamma_root(&s.sigma_l)?, gamma_root(&s.sigma_r)?);
784 let gw = product(g_lr.as_ref(), Op::Plain, wr.as_ref(), Op::Plain);
785 let t = product(wl.as_ref(), Op::Adjoint, gw.as_ref(), Op::Plain);
786 let svd = caroli_dense::svd(t.as_ref()).map_err(|_| GreenError::Eigen)?;
787 taus.extend(svd.s.iter().map(|x| x * x));
788 }
789 taus.sort_by(|a, b| b.total_cmp(a));
790 Ok(taus)
791 }
792
793 pub fn fano_factor(&self, energy: f64) -> Result<f64, GreenError> {
797 let taus = self.transmission_eigenvalues(energy)?;
798 let total: f64 = taus.iter().sum();
799 Ok(taus.iter().map(|t| t * (1.0 - t)).sum::<f64>() / total)
800 }
801
802 fn lead_green(
804 &self,
805 block: &Block,
806 z: c64,
807 sigma_l: &CMat,
808 sigma_r: &CMat,
809 precision: Precision,
810 ) -> Result<CMat, GreenError> {
811 let root = self.root_with_leads(block, z, sigma_l, sigma_r, false, precision)?;
812 let (nl, nr) = (block.left_orbitals.len(), block.right_orbitals.len());
813 let rhs = CMat::from_fn(root.s.nrows(), nr, |i, j| {
815 if i == root.right + j { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) }
816 });
817 let x = Lu::new(root.s.as_ref()).solve(rhs.as_ref());
818 if !x.norm_max().is_finite() {
819 return Err(GreenError::Singular(z.re));
820 }
821 Ok(CMat::from_fn(nl, nr, |i, j| x[(i, j)]))
822 }
823
824 fn root_with_leads(
827 &self,
828 block: &Block,
829 z: c64,
830 sigma_l: &CMat,
831 sigma_r: &CMat,
832 keep: bool,
833 precision: Precision,
834 ) -> Result<LeadRoot, GreenError> {
835 let same = block.left_orbitals == block.right_orbitals;
836 let mut kept: Vec<usize> = block.left_orbitals.to_vec();
837 if !same {
838 kept.extend_from_slice(&block.right_orbitals);
839 }
840 let Root { delayed, mut f, factors } = block.tree.root(&self.h, z, &kept, keep, precision)?;
841 let nd = delayed.len();
842 let (nl, nr) = (block.left_orbitals.len(), block.right_orbitals.len());
843 let right = if same { 0 } else { nl };
844 for a in 0..nl {
845 for c in 0..nl {
846 f[(nd + a, nd + c)] -= sigma_l[(a, c)];
847 }
848 }
849 for a in 0..nr {
850 for c in 0..nr {
851 f[(nd + right + a, nd + right + c)] -= sigma_r[(a, c)];
852 }
853 }
854 let (s, x) = if nd > 0 {
855 schur(&f, nd).ok_or(GreenError::Singular(z.re))?
856 } else {
857 (f, CMat::zeros(0, kept.len()))
858 };
859 Ok(LeadRoot {
860 kept,
861 right,
862 s,
863 delayed: Factor { elim: delayed, boundary: Vec::new(), x, children: factors },
864 })
865 }
866
867 pub fn scattering_states(&self, energy: f64) -> Result<ScatteringStates, GreenError> {
872 let sigma = self.self_energies(energy)?;
873 let z = c64::new(energy, 0.0);
874 let n = self.h.n;
875 let (mut left, mut right): (Vec<CMat>, Vec<CMat>) = (Vec::new(), Vec::new());
876 for (block, s) in self.blocks.iter().zip(&sigma.blocks) {
877 let (wl, wr) = (gamma_root(&s.sigma_l)?, gamma_root(&s.sigma_r)?);
878 let (cl, cr) = (wl.ncols(), wr.ncols());
879 let root = self.root_with_leads(block, z, &s.sigma_l, &s.sigma_r, true, Precision::Double)?;
880 let mut rhs = CMat::zeros(root.kept.len(), cl + cr);
882 for a in 0..wl.nrows() {
883 for c in 0..cl {
884 rhs[(a, c)] = wl[(a, c)];
885 }
886 }
887 for a in 0..wr.nrows() {
888 for c in 0..cr {
889 rhs[(root.right + a, cl + c)] = wr[(a, c)];
890 }
891 }
892 let x = Lu::new(root.s.as_ref()).solve(rhs.as_ref());
893 if !x.norm_max().is_finite() {
894 return Err(GreenError::Singular(energy));
895 }
896 let mut psi = CMat::zeros(n, cl + cr);
897 for (a, &o) in root.kept.iter().enumerate() {
898 for c in 0..cl + cr {
899 psi[(o, c)] = x[(a, c)];
900 }
901 }
902 let LeadRoot { kept, delayed, .. } = root;
903 let delayed = Factor { boundary: kept, ..delayed };
904 delayed.back_substitute(&mut psi);
905 left.push(psi.as_ref().subcols(0, cl).to_owned());
906 right.push(psi.as_ref().subcols(cl, cr).to_owned());
907 }
908 let concat = |parts: Vec<CMat>| {
909 let cols: usize = parts.iter().map(|m| m.ncols()).sum();
910 let mut out = CMat::zeros(n, cols);
911 let mut c0 = 0;
912 for m in parts {
913 out.as_mut().subcols_mut(c0, m.ncols()).copy_from(&m);
914 c0 += m.ncols();
915 }
916 out
917 };
918 Ok(ScatteringStates { energy, leads: vec![concat(left), concat(right)] })
919 }
920
921 pub fn bond_currents(&self, states: &ScatteringStates, f: &[f64]) -> Vec<BondCurrent> {
925 bond_currents(&self.h, &self.region, states, f, None)
926 }
927
928 pub fn operator_currents(&self, states: &ScatteringStates, f: &[f64], op: &CMat) -> Vec<BondCurrent> {
931 bond_currents(&self.h, &self.region, states, f, Some(op))
932 }
933
934 pub fn site_densities(&self, states: &ScatteringStates, f: &[f64], op: Option<&CMat>) -> Vec<f64> {
937 site_densities(&self.region, states, f, op)
938 }
939
940 pub fn region(&self) -> &Region {
942 &self.region
943 }
944}
945
946pub(crate) fn bond_currents(
951 h: &SparseMatrix,
952 region: &Region,
953 states: &ScatteringStates,
954 f: &[f64],
955 op: Option<&CMat>,
956) -> Vec<BondCurrent> {
957 assert_eq!(f.len(), states.leads.len(), "one occupation per lead");
958 let rows: Vec<CMat> = states.leads.iter().map(|m| m.transpose().to_owned()).collect();
960 let lesser = |b: usize, a: usize| -> c64 {
961 let mut acc = c64::new(0.0, 0.0);
962 for (t, fp) in rows.iter().zip(f) {
963 acc += (0..t.nrows()).map(|k| t[(k, b)] * t[(k, a)].conj()).sum::<c64>() * *fp;
964 }
965 c64::new(0.0, 1.0) * acc
966 };
967 let mut owner = vec![0usize; h.n];
968 for i in 0..region.len() {
969 owner[region.offset(i)..region.offset(i) + region.site_orbitals(i)].fill(i);
970 }
971 let mut currents: std::collections::BTreeMap<(usize, usize), c64> = Default::default();
972 match op {
973 None => {
974 for a in 0..h.n {
975 for (b, hab) in h.row(a) {
976 let (i, j) = (owner[a], owner[b]);
977 if i < j {
978 *currents.entry((i, j)).or_default() += hab * lesser(b, a) * 2.0;
979 }
980 }
981 }
982 }
983 Some(o) => {
984 let mut blocks: std::collections::BTreeMap<(usize, usize), CMat> = Default::default();
986 for a in 0..h.n {
987 for (b, hab) in h.row(a) {
988 let (i, j) = (owner[a], owner[b]);
989 if i < j {
990 let (ni, nj) = (region.site_orbitals(i), region.site_orbitals(j));
991 assert!(
992 o.nrows() == ni && o.nrows() == nj,
993 "the operator acts on the orbitals of a site"
994 );
995 let block = blocks.entry((i, j)).or_insert_with(|| CMat::zeros(ni, nj));
996 block[(a - region.offset(i), b - region.offset(j))] += hab;
997 }
998 }
999 }
1000 for ((i, j), hij) in blocks {
1001 let (oi, oj) = (region.offset(i), region.offset(j));
1002 let g = CMat::from_fn(hij.ncols(), hij.nrows(), |b, a| lesser(oj + b, oi + a)); let weighted = o * &hij + &hij * o;
1004 let acc: c64 = (0..weighted.nrows())
1005 .flat_map(|a| (0..weighted.ncols()).map(move |b| (a, b)))
1006 .map(|(a, b)| weighted[(a, b)] * g[(b, a)])
1007 .sum();
1008 currents.insert((i, j), acc);
1009 }
1010 }
1011 }
1012 currents
1013 .into_iter()
1014 .map(|((i, j), acc)| BondCurrent { from: region.sites()[i], to: region.sites()[j], current: acc.re })
1015 .collect()
1016}
1017
1018pub(crate) fn site_densities(
1021 region: &Region,
1022 states: &ScatteringStates,
1023 f: &[f64],
1024 op: Option<&CMat>,
1025) -> Vec<f64> {
1026 assert_eq!(f.len(), states.leads.len(), "one occupation per lead");
1027 (0..region.len())
1028 .map(|i| {
1029 let (o0, n) = (region.offset(i), region.site_orbitals(i));
1030 let mut acc = c64::new(0.0, 0.0);
1031 for (m, fp) in states.leads.iter().zip(f) {
1032 for k in 0..m.ncols() {
1033 for a in 0..n {
1034 let left = m[(o0 + a, k)].conj();
1035 acc += match op {
1036 None => left * m[(o0 + a, k)] * *fp,
1037 Some(o) => (0..n).map(|b| left * o[(a, b)] * m[(o0 + b, k)]).sum::<c64>() * *fp,
1038 };
1039 }
1040 }
1041 }
1042 acc.re / (2.0 * std::f64::consts::PI)
1043 })
1044 .collect()
1045}
1046
1047struct LeadRoot {
1050 kept: Vec<usize>,
1051 right: usize,
1052 s: CMat,
1053 delayed: Factor,
1054}
1055
1056pub(crate) fn gamma_root(sigma: &CMat) -> Result<CMat, GreenError> {
1059 let g = broadening(sigma);
1060 let n = g.nrows();
1061 let g = CMat::from_fn(n, n, |i, j| (g[(i, j)] + g[(j, i)].conj()) * 0.5);
1062 let evd = g.self_adjoint_eigen(faer::Side::Lower).map_err(|_| GreenError::Eigen)?;
1063 let (values, vectors) = (evd.S(), evd.U());
1064 let top = (0..n).map(|k| values[k].re.abs()).fold(0.0, f64::max);
1065 let channels: Vec<usize> = (0..n).filter(|&k| values[k].re > 1e-12 * top).collect();
1066 Ok(CMat::from_fn(n, channels.len(), |i, c| vectors[(i, channels[c])] * values[channels[c]].re.sqrt()))
1067}
1068
1069fn split(
1072 region: &Region,
1073 sites: Vec<usize>,
1074 range: &[i64; 3],
1075 nodes: &mut Vec<(Vec<usize>, Vec<usize>)>,
1076) -> Option<usize> {
1077 if sites.is_empty() {
1078 return None;
1079 }
1080 let orbitals: usize = sites.iter().map(|&i| region.site_orbitals(i)).sum();
1081 let dim = region.lattice().dim();
1082 let extent = |d: usize| {
1083 let (lo, hi) = sites.iter().fold((i64::MAX, i64::MIN), |(lo, hi), &i| {
1084 let c = region.sites()[i].cell[d];
1085 (lo.min(c), hi.max(c))
1086 });
1087 (lo, hi)
1088 };
1089 let (d, (lo, hi)) = (0..dim)
1090 .map(|d| (d, extent(d)))
1091 .max_by_key(|&(d, (lo, hi))| (hi - lo, std::cmp::Reverse(d)))
1092 .unwrap();
1093 if orbitals <= LEAF_ORBITALS || hi - lo < range[d] {
1094 nodes.push((sites, Vec::new()));
1095 return Some(nodes.len() - 1);
1096 }
1097 let mid = lo + (hi - lo + 1 - range[d]) / 2;
1098 let (mut a, mut sep, mut b) = (Vec::new(), Vec::new(), Vec::new());
1099 for i in sites {
1100 let c = region.sites()[i].cell[d];
1101 if c < mid {
1102 a.push(i);
1103 } else if c < mid + range[d] {
1104 sep.push(i);
1105 } else {
1106 b.push(i);
1107 }
1108 }
1109 let children: Vec<usize> =
1110 [split(region, a, range, nodes), split(region, b, range, nodes)].into_iter().flatten().collect();
1111 nodes.push((sep, children));
1112 Some(nodes.len() - 1)
1113}
1114
1115fn symbolic(h: &SparseMatrix, nodes: &mut [Node]) {
1118 const NEVER: usize = usize::MAX;
1119 let mut rank = vec![NEVER; h.n];
1120 let mut next = 0;
1121 let mut last_rank = vec![0usize; nodes.len()];
1122 for (k, node) in nodes.iter().enumerate() {
1123 for &o in &node.eliminate {
1124 rank[o] = next;
1125 next += 1;
1126 }
1127 last_rank[k] = next;
1128 }
1129 for k in 0..nodes.len() {
1130 let mut bnd: Vec<usize> = Vec::new();
1131 for &o in &nodes[k].eliminate {
1132 bnd.extend(h.row(o).map(|(j, _)| j));
1133 }
1134 for &c in &nodes[k].children {
1135 bnd.extend(nodes[c].boundary.iter().copied());
1136 }
1137 bnd.retain(|&o| rank[o] == NEVER || rank[o] >= last_rank[k]);
1138 bnd.sort_unstable();
1139 bnd.dedup();
1140 nodes[k].boundary = bnd;
1141 }
1142}
1143
1144fn extend_add<T: Field>(f: &mut Mat<T>, pos: &Positions, kids: Vec<Front<T>>) -> Vec<Factor> {
1147 let mut factors = Vec::new();
1148 for kid in kids {
1149 add_runs(f, &runs(&kid.vars, pos), &kid.s);
1150 factors.extend(kid.factor);
1151 }
1152 factors
1153}
1154
1155fn runs(vars: &[usize], pos: &Positions) -> Vec<(usize, usize, usize)> {
1159 let mut runs: Vec<(usize, usize, usize)> = Vec::new();
1160 for (a, &o) in vars.iter().enumerate() {
1161 let pa = pos.get(o).expect("child variable in the parent front");
1162 match runs.last_mut() {
1163 Some((a0, p0, len)) if *a0 + *len == a && *p0 + *len == pa => *len += 1,
1164 _ => runs.push((a, pa, 1)),
1165 }
1166 }
1167 runs
1168}
1169
1170fn add_runs<T: Field>(f: &mut Mat<T>, runs: &[(usize, usize, usize)], s: &Mat<T>) {
1172 for &(b0, q0, width) in runs {
1173 for b in 0..width {
1174 let (src, dst) = (s.col_as_slice(b0 + b), f.col_as_slice_mut(q0 + b));
1175 for &(a0, p0, len) in runs {
1176 for (d, x) in dst[p0..p0 + len].iter_mut().zip(&src[a0..a0 + len]) {
1177 *d += *x;
1178 }
1179 }
1180 }
1181 }
1182}
1183
1184pub(crate) fn small_schur<T: Field>(f: &Mat<T>, ne: usize, want_x: bool) -> Option<(Mat<T>, Mat<T>)> {
1188 let n = f.nrows();
1189 let nb = n - ne;
1190 let scale = (0..ne)
1191 .map(|j| f.col_as_slice(j)[..ne].iter().map(|x| x.modulus()).fold(0.0, f64::max))
1192 .fold(0.0, f64::max);
1193 let mut w = f.clone();
1194 let mut lk: Vec<T> = Vec::with_capacity(n);
1195 for k in 0..ne {
1196 let (p, big) =
1197 (k..ne).map(|i| (i, w[(i, k)].modulus())).fold((k, -1.0), |a, b| if b.1 > a.1 { b } else { a });
1198 let stable = big > T::PIVOT_TOL * scale; if !stable {
1200 return None;
1201 }
1202 if p != k {
1203 for j in 0..n {
1204 w.col_as_slice_mut(j).swap(p, k);
1205 }
1206 }
1207 let inv = T::ONE / w[(k, k)];
1208 for v in &mut w.col_as_slice_mut(k)[k + 1..] {
1209 *v *= inv;
1210 }
1211 lk.clear();
1213 lk.extend_from_slice(&w.col_as_slice(k)[k + 1..]);
1214 for j in k + 1..n {
1215 let col = w.col_as_slice_mut(j);
1216 let ukj = col[k];
1217 if ukj != T::ZERO {
1218 for (c, &l) in col[k + 1..].iter_mut().zip(&lk) {
1219 *c -= l * ukj;
1220 }
1221 }
1222 }
1223 }
1224 let s = Mat::<T>::from_fn(nb, nb, |i, j| w[(ne + i, ne + j)]);
1225 let x = if want_x {
1226 let mut x = Mat::<T>::from_fn(ne, nb, |i, j| w[(i, ne + j)]);
1228 for j in 0..nb {
1229 let col = x.col_as_slice_mut(j);
1230 for i in (0..ne).rev() {
1231 let v = col[i] / w[(i, i)];
1232 col[i] = v;
1233 for (l, c) in col[..i].iter_mut().enumerate() {
1234 *c -= w[(l, i)] * v;
1235 }
1236 }
1237 }
1238 x
1239 } else {
1240 Mat::<T>::zeros(ne, 0)
1241 };
1242 Some((s, x))
1243}
1244
1245pub(crate) fn schur<T: Field>(f: &Mat<T>, ne: usize) -> Option<(Mat<T>, Mat<T>)> {
1248 T::schur(f.as_ref(), ne)
1249}