Skip to main content

caroli_green/
nested.rs

1//! Two-terminal transport by geometric nested dissection.
2//!
3//! The device is cut recursively by separator layers into a binary tree of domains. Each node
4//! eliminates its separator from a dense frontal matrix and passes the Schur complement on its
5//! boundary to its parent (the multifrontal method). The two lead slices are never eliminated.
6//! The root therefore holds the Schur complement `S` of `z − H − Σ` on them, and
7//! `G_LR = (S⁻¹)_LR` gives the Caroli transmission.
8//!
9//! Compared with the recursive Green's function ([`crate::TwoTerminal`]):
10//! - the cost of an n × n sample is O(n³) instead of O(n⁴), and that of a long strip
11//!   O(L W²) instead of O(L W³);
12//! - only the pending Schur complements are stored, no factors;
13//! - the tree is built once, and each energy redoes the numeric phase, in parallel over
14//!   independent branches.
15//!
16//! If a separator block cannot be eliminated stably, its variables are delayed: they join the
17//! separator of the parent node. This happens for an exactly singular interior block, such as a
18//! piece of a clean lattice at one of its eigenvalues.
19//!
20//! Independent blocks (orbitals that neither the device nor the leads couple, e.g. the two
21//! spin blocks of BHZ) are solved separately on the same tree.
22//!
23//! The elimination itself (`SiteTree`, `Tree`) also serves [`crate::NestedMultiTerminal`].
24
25use 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
34/// Domains with at most this many orbitals are not split further.
35const LEAF_ORBITALS: usize = 16;
36// A pivot below `Field::PIVOT_TOL` times the largest entry of a separator block delays the block.
37/// Fronts with fewer variables than this are eliminated by [`small_schur`].
38const SMALL_FRONT: usize = 64;
39
40/// One node of the elimination tree, for one block of orbitals.
41#[derive(Clone, Debug)]
42struct Node {
43    /// Orbitals eliminated at this node (sorted).
44    eliminate: Vec<usize>,
45    /// Orbitals of the front that are eliminated later or never (sorted).
46    boundary: Vec<usize>,
47    children: Vec<usize>,
48}
49
50/// Geometric tree over the sites of a region: separator layers as thick as the hopping range,
51/// down to leaves of `LEAF_ORBITALS` orbitals. Shared by the independent blocks of orbitals.
52#[derive(Clone, Debug)]
53pub(crate) struct SiteTree {
54    /// `(sites eliminated, children)` of each node, in post-order.
55    nodes: Vec<(Vec<usize>, Vec<usize>)>,
56    /// Children of the root.
57    top: Vec<usize>,
58}
59
60impl SiteTree {
61    /// Tree over the `interior` sites (indices in `region`); the other sites stay at the root.
62    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    /// Elimination tree of the orbitals for which `mine` holds.
75    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/// Elimination tree of one block of orbitals.
101#[derive(Clone, Debug)]
102pub(crate) struct Tree {
103    nodes: Vec<Node>,
104    /// Children of the root.
105    top: Vec<usize>,
106    /// The assembly of each front when nothing below it was delayed.
107    plans: Vec<Plan>,
108}
109
110/// How a front is assembled when its children hand over exactly their boundaries (no delayed
111/// variable): computed once with the tree, instead of sorting and searching the variables at
112/// every energy.
113#[derive(Clone, Debug)]
114struct Plan {
115    /// Variables of the front: those eliminated here (sorted), then the boundary.
116    vars: Vec<usize>,
117    /// Number of variables eliminated here.
118    ne: usize,
119    /// Positions of the own separator (they get `z` on the diagonal).
120    diagonal: Vec<usize>,
121    /// Entries of `H` in the front: `(row, column, value)`.
122    entries: Vec<(usize, usize, c64)>,
123    /// For each child, where its Schur complement goes (runs, see [`runs`]).
124    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
145/// Variables of the front of `node` whose children hand over `children`: the own separator and
146/// what the children could not eliminate (sorted), then the boundary; and how many are
147/// eliminated here.
148fn 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
161/// Entries of `H` that the separator of `node` brings to its front: with every later variable
162/// (the rest of the separator after it, and the boundary); the earlier ones were assembled where
163/// those were eliminated, and a child's delayed variables already carry theirs.
164fn 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
182/// What a front passes to its parent: its remaining variables and their Schur complement (in the
183/// precision of the elimination), and, when the factors are kept, what the back-substitution
184/// needs.
185struct Front<T> {
186    vars: Vec<usize>,
187    s: Mat<T>,
188    factor: Option<Factor>,
189}
190
191/// Back-substitution data of a front: with a right-hand side that vanishes on the eliminated
192/// variables, `ψ_elim = −X ψ_boundary`. A delayed front eliminates nothing and only holds its
193/// children.
194pub(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    /// Fills the rows of the eliminated variables of `psi` (rows: orbitals) from those of their
203    /// boundaries, from this front down to the leaves.
204    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
230/// The root front of a [`Tree`] (see [`Tree::root`]).
231pub(crate) struct Root {
232    /// Variables delayed up to the root (first in `f`), then the kept orbitals.
233    pub(crate) delayed: Vec<usize>,
234    pub(crate) f: CMat,
235    /// Back-substitution data of the top fronts, when kept.
236    pub(crate) factors: Vec<Factor>,
237}
238
239impl Tree {
240    /// Front of the root on the `kept` orbitals, which are never eliminated: `f` holds the
241    /// variables delayed up to the root, then `kept` in order. The entries of `z − H` between
242    /// kept orbitals are included; the caller adds the leads. With `keep`, the fronts also keep
243    /// their back-substitution data.
244    ///
245    /// The fronts below the root run in `precision`; the root itself is assembled in complex f64,
246    /// so the leads, the delayed variables and the final solve stay in double precision.
247    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    /// Fronts of the given nodes, in parallel.
285    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    /// Eliminates node `k` (after its children) and returns the variables left in its front and
304    /// their Schur complement.
305    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            // Variables delayed below: assemble from the actual variables.
334            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        // The front's variables: those assembled above when some were delayed below, else the
347        // plan's (copied only when the front hands them on).
348        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            // Singular separator block: hand the whole front to the parent.
375            None => Ok(delayed(owned(vars), f, children)),
376        }
377    }
378}
379
380/// Independent sets of indices (union-find).
381pub(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    /// Joins `orbitals[a]` and `orbitals[b]` for every nonzero `m[(a, b)]`.
404    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    /// The label of every index (its smallest member), and the sorted labels.
415    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/// One independent block of orbitals with its elimination tree and its leads.
426///
427/// The leads and their orbitals are shared ([`Arc`]) with the self-energies computed from them,
428/// which keep them to check that they serve a system with the same leads.
429#[derive(Clone, Debug)]
430struct Block {
431    tree: Tree,
432    left: Arc<Lead>,
433    right: Arc<Lead>,
434    /// The energy-independent part of the leads' mode problems.
435    left_modes: ModeSolver,
436    right_modes: ModeSolver,
437    /// Device orbitals of the first and last slices, in the order of the lead cells.
438    left_orbitals: Arc<[usize]>,
439    right_orbitals: Arc<[usize]>,
440}
441
442/// Lead self-energies of a [`NestedTwoTerminal`] at one energy, block by block (see
443/// [`NestedTwoTerminal::self_energies`]).
444#[derive(Clone, Debug)]
445pub struct LeadSelfEnergies {
446    energy: f64,
447    blocks: Vec<BlockSelfEnergies>,
448}
449
450impl LeadSelfEnergies {
451    /// Energy of the self-energies.
452    pub fn energy(&self) -> f64 {
453        self.energy
454    }
455}
456
457/// The self-energies of one block, with the block's leads and lead orbitals (shared, not copied)
458/// to check the system they are used on.
459#[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
473/// The same lead: the same one shared, or an equal one (another system built alike).
474fn same_shared_lead(a: &Arc<Lead>, b: &Arc<Lead>) -> bool {
475    Arc::ptr_eq(a, b) || same_lead(a, b)
476}
477
478/// A two-terminal device solved by nested dissection (see the module documentation).
479#[derive(Clone, Debug)]
480pub struct NestedTwoTerminal {
481    h: SparseMatrix,
482    region: Region,
483    blocks: Vec<Block>,
484}
485
486/// Scattering states at one energy (see [`NestedTwoTerminal::scattering_states`] and
487/// [`crate::NestedMultiTerminal::scattering_states`]).
488#[derive(Clone, Debug)]
489pub struct ScatteringStates {
490    /// Energy `E` of the states.
491    pub energy: f64,
492    /// `ψ_p = G W_p` for each lead `p`, on every device orbital (rows, in the order of the
493    /// region), one column per channel of the lead: `W_p W_p† = Γ_p`, so `ψ_p ψ_p† = G Γ_p G†`
494    /// is the spectral function of the electrons lead `p` injects. Two-terminal devices list the
495    /// left lead, then the right one.
496    pub leads: Vec<CMat>,
497}
498
499impl ScatteringStates {
500    /// Occupied spectral density `Im G^<_aa / 2π = Σ_p f_p |ψ_p,a|² / 2π` of every orbital, for
501    /// the lead occupations `f` (`G^< = i Σ_p f_p ψ_p ψ_p†`). With every `f_p = 1` it is the local
502    /// density of states of the scattering states (bound states of the device are not included).
503    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/// Spectral particle current through a bond, `j_{i→j}(E) = 2 Re Tr[H_ij G^<_ji(E)]`: summed over
517/// a cross-section, it equals `T(E) [f_L(E) − f_R(E)]`.
518#[derive(Clone, Copy, Debug, PartialEq)]
519pub struct BondCurrent {
520    /// Site `i`, which the current is counted from.
521    pub from: Site,
522    /// Site `j`, which the current is counted into.
523    pub to: Site,
524    /// `j_{i→j}(E)`, or the current of an on-site operator; negative when the flow goes from `j`
525    /// to `i`.
526    pub current: f64,
527}
528
529/// Position of each item of `vars` (any order): a sorted index for binary search.
530pub(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    /// Two-terminal system built from a model on a region cut along primitive vector `axis`,
546    /// as [`crate::TwoTerminal::from_model`]: both leads continue the first and last slices of
547    /// the region with the clean `lead` model.
548    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        // In a uniform field, everything in the gauge invariant along the axis.
557        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        // Geometric tree over the interior sites (all but the two lead slices).
578        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(&region.sites()[i].cell[axis])).collect();
581        let sites = SiteTree::new(device, region, interior);
582
583        // Independent blocks of orbitals: connected through the device or the leads.
584        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    /// Number of independent blocks solved separately.
631    pub fn block_count(&self) -> usize {
632        self.blocks.len()
633    }
634
635    /// Caroli transmission `T(E) = Tr[Γ_L G_LR Γ_R G_LR†]`, with mode-matching self-energies.
636    pub fn transmission(&self, energy: f64) -> Result<f64, GreenError> {
637        self.transmission_with(&self.self_energies(energy)?)
638    }
639
640    /// Transmissions at many energies, in parallel.
641    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    /// Transmissions at many energies in the precision of `options`, checked against double
647    /// precision on a sample of the energies (see [`crate::checked`]).
648    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    /// Lead self-energies at `energy`, for each independent block. They serve every system with
662    /// the same leads and blocks: in a disorder average, the leads are solved once per energy
663    /// instead of once per configuration.
664    ///
665    /// ```ignore
666    /// let sigma = reference.self_energies(e)?;
667    /// let mean = configurations.iter().map(|sys| sys.transmission_with(&sigma)).sum::<Result<f64, _>>()?
668    ///     / configurations.len() as f64;
669    /// ```
670    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                // Identical leads share one set of modes.
678                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    /// Transmission at the energy of `sigma`, with its lead self-energies, computed by
699    /// [`Self::self_energies`] on this system or on one with the same leads and blocks.
700    ///
701    /// Panics if the leads or the blocks differ.
702    pub fn transmission_with(&self, sigma: &LeadSelfEnergies) -> Result<f64, GreenError> {
703        self.transmission_with_precision(sigma, Precision::Double)
704    }
705
706    /// [`Self::transmission_with`] with the fronts in `precision` (see [`Precision`]), unchecked:
707    /// [`Self::transmissions_checked`] or [`crate::checked`] measure the error.
708    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    /// Scattering matrix at `energy` in the basis of the propagating lead modes (lead 0 on the
736    /// left, lead 1 on the right), as `kwant.smatrix` (see [`crate::SMatrix`]).
737    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            // Each lead seen from the device: cells going away from it, coupled to the end slice.
744            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    /// Transmission eigenvalues `τ_n` at `energy`, in decreasing order: the squared singular
775    /// values of `t = W_L† G_LR W_R` (`W_p W_p† = Γ_p`), the same as those of the transmission
776    /// block of the scattering matrix. Their sum is the transmission.
777    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    /// Fano factor `F = Σ τ (1 − τ) / Σ τ` at `energy`: the shot noise over the Poisson value, at
794    /// zero temperature and small bias (0 for perfect channels, 1 for a tunnel barrier, 1/3 for
795    /// a diffusive wire).
796    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    /// `G_LR`, the block of `(z − H − Σ)⁻¹` between the first and last slices.
803    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        // Columns of the right slice of S⁻¹, rows of the left slice.
814        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    /// The Schur complement `S` of `z − H − Σ` on the lead slices of a block (left slice first,
825    /// then the right one unless they coincide), with the delayed variables eliminated.
826    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    /// Scattering states at `energy`: `ψ_p = G W_p` on every device orbital for each lead `p`,
868    /// with `W_p W_p† = Γ_p` (one column per channel). The elimination keeps its factors, and a
869    /// back-substitution from the lead slices gives the states everywhere: memory grows with the
870    /// factors (O(N log N) for a 2D sample of N orbitals) and with N times the channels.
871    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            // Sources on the lead slices: W_L on the left slice, W_R on the right one.
881            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    /// Spectral bond currents `2 Re Tr[H_ij G^<_ji]` between every pair of coupled sites, from
922    /// the scattering states and the lead occupations `f` (`G^< = i Σ_p f_p ψ_p ψ_p†`). Each bond
923    /// appears once, from the site of lower index in the region.
924    pub fn bond_currents(&self, states: &ScatteringStates, f: &[f64]) -> Vec<BondCurrent> {
925        bond_currents(&self.h, &self.region, states, f, None)
926    }
927
928    /// Bond currents of an on-site operator `O` (a spin current for `O = s_z`):
929    /// `Re Tr[(O H_ij + H_ij O) G^<_ji]`, `2 Re Tr[H_ij G^<_ji]` for `O = 1`.
930    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    /// Spectral density `Σ_p f_p ψ_p† O ψ_p / 2π` of every site (`O = 1` for `None`): the occupied
935    /// density, or a spin density.
936    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    /// The device region (orbital layout of the scattering states).
941    pub fn region(&self) -> &Region {
942        &self.region
943    }
944}
945
946/// Spectral bond currents between every pair of coupled sites of `region`, with
947/// `G^< = i Σ_p f_p ψ_p ψ_p†` from the scattering states: `2 Re Tr[H_ij G^<_ji]`, or with an
948/// on-site operator `O` (spin...), `Re Tr[(O H_ij + H_ij O) G^<_ji]`. Each bond appears once,
949/// from the site of lower index in the region.
950pub(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    // Rows of ψ_p as contiguous vectors: (ψ_p ψ_p†)_ba = Σ_k ψ_bk ψ_ak*.
959    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            // Blocks H_ij, then Tr[(O H_ij + H_ij O) G^<_ji].
985            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)); // G^<_ji
1003                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
1018/// Spectral densities of every site of `region`, `Σ_p f_p ψ_p† O ψ_p / 2π` on its orbitals (`O = 1`
1019/// without an operator): the occupied density, or a spin density.
1020pub(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
1047/// The root of a two-terminal block: `S` on the kept lead orbitals (`right` is the position of
1048/// the right slice), and the delayed variables with their back-substitution data.
1049struct LeadRoot {
1050    kept: Vec<usize>,
1051    right: usize,
1052    s: CMat,
1053    delayed: Factor,
1054}
1055
1056/// `W` with `W W† = Γ = i(Σ − Σ†)`: the eigenvectors of `Γ` with positive eigenvalues, scaled by
1057/// their square roots (one column per channel).
1058pub(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
1069/// Builds the elimination tree over `sites` (indices in `region`) in post-order: each node is
1070/// `(sites eliminated, children)`. Returns the root of the subtree, if any.
1071fn 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
1115/// Fills the boundaries of the nodes (in post-order): the variables of the front that are
1116/// eliminated later, from the sparsity of `h` and the children's boundaries.
1117fn 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
1144/// Adds the children's Schur complements into the front `f` (variables at `pos`), and returns
1145/// their back-substitution data (when kept).
1146fn 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
1155/// Where the variables `vars` sit in a front with positions `pos`, as runs of consecutive
1156/// positions `(first in vars, first in the front, length)`: both sides are sorted, so a few runs
1157/// cover a column.
1158fn 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
1170/// `f[p, q] += s[a, b]` for the positions `p`, `q` of `a`, `b` given by `runs`.
1171fn 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
1184/// [`schur`] for a small front: Gaussian elimination in a copy of `f`, without calls to the
1185/// dense library or other allocations; `X` only when `want_x`. Partial pivoting within the
1186/// separator rows, with the same stability test.
1187pub(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; // false for NaN
1199        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        // Rank-one update of the trailing columns.
1212        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        // X = U⁻¹ U12, with U12 = L⁻¹ P f12 in the top right block.
1227        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
1245/// Schur complement `S = f22 − f21 X` of the leading `ne × ne` block of `f`, with
1246/// `X = f11⁻¹ f12`; `None` if that block is numerically singular (see [`Field::schur`]).
1247pub(crate) fn schur<T: Field>(f: &Mat<T>, ne: usize) -> Option<(Mat<T>, Mat<T>)> {
1248    T::schur(f.as_ref(), ne)
1249}