Skip to main content

caroli_green/
nested_multi.rs

1//! Multi-terminal transport by nested dissection: the leads and interfaces of
2//! [`crate::MultiTerminal`], with the device eliminated as in [`crate::NestedTwoTerminal`].
3//!
4//! The sites that a lead couples to stay at the root of the elimination tree. The root then
5//! holds the Schur complement `S` of `z − H − Σ` on their orbitals, and `S⁻¹` gives the Green's
6//! function `G_pq` between every pair of leads, hence `T_pq = Tr[Γ_p G_pq Γ_q G_pq†]`. The cost
7//! is that of the two-terminal elimination plus one dense inverse on the lead interfaces, where
8//! [`crate::MultiTerminal`] inverts the whole device.
9//!
10//! Independent blocks of orbitals (e.g. the spin blocks of BHZ) are solved separately, each with
11//! the part of every lead it reaches.
12
13use crate::modes::ModeSolver;
14use crate::multi::{AttachedLead, Interface, attach_leads};
15use crate::nested::{
16    BondCurrent, Components, Factor, Root, ScatteringStates, SiteTree, Tree, gamma_root, schur,
17};
18use crate::smatrix::{LeadSolution, SMatrix, ScatteringLead, scattering_blocks};
19use crate::{GreenError, Precision, broadening, caroli_trace, sandwich};
20use caroli_dense::Lu;
21use caroli_lattice::Region;
22use caroli_model::{CMat, Model, SparseMatrix, c64};
23use std::rc::Rc;
24
25/// One independent block of orbitals: its elimination tree and the part of each lead it reaches.
26#[derive(Clone, Debug)]
27struct MultiBlock {
28    tree: Tree,
29    leads: Vec<Option<AttachedLead>>,
30    /// The energy-independent part of each lead's mode problem.
31    solvers: Vec<Option<ModeSolver>>,
32    /// For each lead: the orbitals of its cell kept in the block (indices into the full cell).
33    cells: Vec<Vec<usize>>,
34}
35
36/// Transmissions between the sectors of the leads (see
37/// [`NestedMultiTerminal::sector_transmissions`]).
38#[derive(Clone, Debug)]
39pub struct SectorTransmissions {
40    /// `(lead, sector)` of each row and column.
41    pub labels: Vec<(usize, usize)>,
42    /// `t[k][l]` from `labels[l]` into `labels[k]`.
43    pub t: Vec<Vec<f64>>,
44}
45
46/// A device with any number of attached leads, solved by nested dissection (see the module
47/// documentation).
48#[derive(Clone, Debug)]
49pub struct NestedMultiTerminal {
50    h: SparseMatrix,
51    region: Region,
52    lead_count: usize,
53    /// For each lead, the index of every orbital of its cell within its site.
54    orbital_kinds: Vec<Vec<usize>>,
55    blocks: Vec<MultiBlock>,
56}
57
58impl NestedMultiTerminal {
59    /// Device from `device` on `region`, with leads of the clean `lead` model continuing each
60    /// interface outward, as [`crate::MultiTerminal::from_model`].
61    pub fn from_model(device: &Model, lead: &Model, region: &Region, interfaces: &[Interface]) -> Self {
62        crate::gauge::assert_same_field(device, lead);
63        let h = device.sparse_hamiltonian(region);
64        let leads = attach_leads(lead, region, interfaces);
65        // Sites with an orbital coupled to a lead stay at the root.
66        let mut coupled = vec![false; h.n];
67        for l in &leads {
68            for &o in &l.orbitals {
69                coupled[o] = true;
70            }
71        }
72        let interior: Vec<usize> = (0..region.len())
73            .filter(|&i| {
74                let o = region.offset(i);
75                !(o..o + region.site_orbitals(i)).any(|k| coupled[k])
76            })
77            .collect();
78        let sites = SiteTree::new(device, region, interior);
79
80        // Independent blocks over the device orbitals, then the orbitals of each lead cell.
81        let mut offsets = Vec::with_capacity(leads.len());
82        let mut total = h.n;
83        for l in &leads {
84            offsets.push(total);
85            total += l.h00.nrows();
86        }
87        let mut components = Components::new(total);
88        for r in 0..h.n {
89            for (c, v) in h.row(r) {
90                if v != c64::new(0.0, 0.0) {
91                    components.join(r, c);
92                }
93            }
94        }
95        for (l, &off) in leads.iter().zip(&offsets) {
96            let cell: Vec<usize> = (off..off + l.h00.nrows()).collect();
97            components.join_matrix(&l.h00, &cell, &cell);
98            components.join_matrix(&l.h01, &cell, &cell);
99            components.join_matrix(&l.coupling, &l.orbitals, &cell);
100        }
101        let (roots, labels) = components.labels();
102        let blocks = labels
103            .iter()
104            .filter_map(|&label| {
105                let mine = |o: usize| roots[o] == label;
106                let block_leads: Vec<Option<AttachedLead>> = leads
107                    .iter()
108                    .zip(&offsets)
109                    .map(|(l, &off)| {
110                        let kc: Vec<usize> = (0..l.h00.nrows()).filter(|&k| mine(off + k)).collect();
111                        let kd: Vec<usize> = (0..l.orbitals.len()).filter(|&k| mine(l.orbitals[k])).collect();
112                        if kc.is_empty() || kd.is_empty() {
113                            return None;
114                        }
115                        let cell = |m: &CMat| CMat::from_fn(kc.len(), kc.len(), |a, b| m[(kc[a], kc[b])]);
116                        Some(AttachedLead {
117                            h00: cell(&l.h00),
118                            h01: cell(&l.h01),
119                            orbitals: kd.iter().map(|&k| l.orbitals[k]).collect(),
120                            coupling: CMat::from_fn(kd.len(), kc.len(), |a, b| l.coupling[(kd[a], kc[b])]),
121                        })
122                    })
123                    .collect();
124                if block_leads.iter().all(Option::is_none) {
125                    return None;
126                }
127                let cells = leads
128                    .iter()
129                    .zip(&offsets)
130                    .map(|(l, &off)| (0..l.h00.nrows()).filter(|&k| mine(off + k)).collect())
131                    .collect();
132                // One mode solver per distinct lead (opposite leads often share h00 and h01).
133                let mut solvers: Vec<Option<ModeSolver>> = Vec::with_capacity(block_leads.len());
134                for (k, l) in block_leads.iter().enumerate() {
135                    let solver = l.as_ref().map(|l| {
136                        let twin = block_leads[..k]
137                            .iter()
138                            .position(|m| m.as_ref().is_some_and(|m| m.h00 == l.h00 && m.h01 == l.h01));
139                        match twin {
140                            Some(t) => solvers[t].clone().expect("solver of a lead"),
141                            None => ModeSolver::new(&l.h00, &l.h01),
142                        }
143                    });
144                    solvers.push(solver);
145                }
146                Some(MultiBlock { tree: sites.tree(region, &h, mine), leads: block_leads, solvers, cells })
147            })
148            .collect();
149        let orbital_kinds = interfaces
150            .iter()
151            .map(|itf| (0..itf.slice.len()).flat_map(|i| 0..itf.slice.site_orbitals(i)).collect())
152            .collect();
153        Self { h, region: region.clone(), lead_count: leads.len(), orbital_kinds, blocks }
154    }
155
156    /// Number of leads.
157    pub fn lead_count(&self) -> usize {
158        self.lead_count
159    }
160
161    /// Number of independent blocks solved separately.
162    pub fn block_count(&self) -> usize {
163        self.blocks.len()
164    }
165
166    /// Transmissions `T[p][q] = Tr[Γ_p G_pq Γ_q G_pq†]` from lead `q` into lead `p` at `energy`,
167    /// with mode-matching self-energies, as [`crate::MultiSolution::transmission`].
168    pub fn transmissions(&self, energy: f64) -> Result<Vec<Vec<f64>>, GreenError> {
169        self.transmissions_with_precision(energy, Precision::Double)
170    }
171
172    /// [`Self::transmissions`] with the fronts in `precision` (see [`Precision`]), unchecked:
173    /// [`crate::checked`] measures the error on a batch of points.
174    pub fn transmissions_with_precision(
175        &self,
176        energy: f64,
177        precision: Precision,
178    ) -> Result<Vec<Vec<f64>>, GreenError> {
179        use rayon::prelude::*;
180        let parts: Vec<Result<Vec<Vec<f64>>, GreenError>> =
181            self.blocks.par_iter().map(|b| self.block_transmissions(b, energy, precision)).collect();
182        let n = self.lead_count;
183        let mut t = vec![vec![0.0; n]; n];
184        for part in parts {
185            for (row, add) in t.iter_mut().zip(part?) {
186                row.iter_mut().zip(add).for_each(|(x, y)| *x += y);
187            }
188        }
189        Ok(t)
190    }
191
192    /// Self-energies of the leads a block reaches: `Σ_p = V_p g V_p†`, with the surface Green's
193    /// function `g` computed once per distinct lead (opposite leads of a symmetric device often
194    /// share h00 and h01).
195    fn self_energies(block: &MultiBlock, energy: f64) -> Result<Vec<Option<CMat>>, GreenError> {
196        let surfaces = Self::surfaces(block, energy)?;
197        Ok(block
198            .leads
199            .iter()
200            .zip(&surfaces)
201            .map(|(l, g)| l.as_ref().zip(g.as_ref()).map(|(l, g)| sandwich(&l.coupling, g)))
202            .collect())
203    }
204
205    /// Surface Green's functions `g` of the leads a block reaches, computed once per distinct
206    /// lead and shared by the leads equal to it.
207    fn surfaces(block: &MultiBlock, energy: f64) -> Result<Vec<Option<Rc<CMat>>>, GreenError> {
208        let mut done: Vec<(&AttachedLead, Rc<CMat>)> = Vec::new();
209        let mut out = Vec::with_capacity(block.leads.len());
210        for (l, solver) in block.leads.iter().zip(&block.solvers) {
211            let (Some(l), Some(solver)) = (l, solver) else {
212                out.push(None);
213                continue;
214            };
215            let g = match done.iter().find(|(m, _)| m.h00 == l.h00 && m.h01 == l.h01) {
216                Some((_, g)) => Rc::clone(g),
217                None => {
218                    let g = Rc::new(l.surface_green_with(solver, c64::new(energy, 0.0))?);
219                    done.push((l, Rc::clone(&g)));
220                    g
221                }
222            };
223            out.push(Some(g));
224        }
225        Ok(out)
226    }
227
228    /// Transmissions between sectors of the leads (spin, electrons and holes...).
229    /// `sectors[p]` labels the orbitals of each site of lead `p` (e.g. `[0, 1]` for electrons and
230    /// holes, `[0, 0, 1, 1]` with spin), or is `None` to take the lead as a whole; the lead
231    /// Hamiltonian must not couple different sectors.
232    ///
233    /// `t[k][l] = Tr[Γ_k G Γ_l G†]` from `labels[l]` into `labels[k]`, with `Γ_k` the broadening
234    /// of the lead projected on the sector. Between two sectors of the same lead it is a
235    /// reflection probability (Andreev reflection for electrons and holes); the diagonal is not a
236    /// reflection (use unitarity).
237    pub fn sector_transmissions(
238        &self,
239        energy: f64,
240        sectors: &[Option<Vec<usize>>],
241    ) -> Result<SectorTransmissions, GreenError> {
242        assert_eq!(sectors.len(), self.lead_count, "one sector labelling per lead");
243        let label = |p: usize, cell_orbital: usize| -> usize {
244            sectors[p].as_ref().map_or(0, |s| s[self.orbital_kinds[p][cell_orbital]])
245        };
246        let mut labels: Vec<(usize, usize)> = Vec::new();
247        for (p, kinds) in self.orbital_kinds.iter().enumerate() {
248            let mut own: Vec<usize> = (0..kinds.len()).map(|o| label(p, o)).collect();
249            own.sort_unstable();
250            own.dedup();
251            labels.extend(own.into_iter().map(|a| (p, a)));
252        }
253        let mut t = vec![vec![0.0; labels.len()]; labels.len()];
254        for block in &self.blocks {
255            let surfaces = Self::surfaces(block, energy)?;
256            // Γ of every (lead, sector) on the orbitals the lead couples to:
257            // Γ_{p,a} = V P_a i(g − g†) P_a V†.
258            let mut gammas: Vec<Option<CMat>> = vec![None; labels.len()];
259            for (p, (l, g)) in block.leads.iter().zip(&surfaces).enumerate() {
260                let (Some(l), Some(g)) = (l, g) else { continue };
261                let cell = &block.cells[p];
262                let tags: Vec<usize> = cell.iter().map(|&o| label(p, o)).collect();
263                for m in [&l.h00, &l.h01] {
264                    let mixed = (0..cell.len())
265                        .flat_map(|a| (0..cell.len()).map(move |b| (a, b)))
266                        .any(|(a, b)| tags[a] != tags[b] && m[(a, b)] != c64::new(0.0, 0.0));
267                    assert!(!mixed, "the Hamiltonian of lead {p} couples different sectors");
268                }
269                let gamma = broadening(g);
270                for (k, &(lead, sector)) in labels.iter().enumerate() {
271                    if lead != p {
272                        continue;
273                    }
274                    let n = cell.len();
275                    let projected = CMat::from_fn(n, n, |a, b| {
276                        if tags[a] == sector && tags[b] == sector {
277                            gamma[(a, b)]
278                        } else {
279                            c64::new(0.0, 0.0)
280                        }
281                    });
282                    gammas[k] = Some(sandwich(&l.coupling, &projected));
283                }
284            }
285            let sigmas: Vec<Option<CMat>> = block
286                .leads
287                .iter()
288                .zip(&surfaces)
289                .map(|(l, g)| l.as_ref().zip(g.as_ref()).map(|(l, g)| sandwich(&l.coupling, g)))
290                .collect();
291            let (kept, s, _) = self.root(block, energy, &sigmas, false, Precision::Double)?;
292            let k = kept.len();
293            let green = Lu::new(s.as_ref()).solve(CMat::identity(k, k).as_ref());
294            if !green.norm_max().is_finite() {
295                return Err(GreenError::Singular(energy));
296            }
297            for (a, &(pa, _)) in labels.iter().enumerate() {
298                for (b, &(pb, _)) in labels.iter().enumerate() {
299                    let (Some(la), Some(lb), Some(ga), Some(gb)) =
300                        (&block.leads[pa], &block.leads[pb], &gammas[a], &gammas[b])
301                    else {
302                        continue;
303                    };
304                    let (ia, ib) = (index(&kept, la), index(&kept, lb));
305                    let gab = CMat::from_fn(ia.len(), ib.len(), |x, y| green[(ia[x], ib[y])]);
306                    t[a][b] += caroli_trace(ga, &gab, gb);
307                }
308            }
309        }
310        Ok(SectorTransmissions { labels, t })
311    }
312
313    /// The Schur complement `S` of `z − H − Σ` on the orbitals the leads couple to (`kept`, in
314    /// increasing order), with the delayed variables eliminated: `(kept, S, delayed)`.
315    fn root(
316        &self,
317        block: &MultiBlock,
318        energy: f64,
319        sigmas: &[Option<CMat>],
320        keep: bool,
321        precision: Precision,
322    ) -> Result<(Vec<usize>, CMat, Factor), GreenError> {
323        let mut kept: Vec<usize> =
324            block.leads.iter().flatten().flat_map(|l| l.orbitals.iter().copied()).collect();
325        kept.sort_unstable();
326        kept.dedup();
327        let Root { delayed, mut f, factors } =
328            block.tree.root(&self.h, c64::new(energy, 0.0), &kept, keep, precision)?;
329        let nd = delayed.len();
330        for (l, s) in block.leads.iter().zip(sigmas) {
331            if let (Some(l), Some(s)) = (l, s) {
332                let at = index(&kept, l);
333                for (a, &i) in at.iter().enumerate() {
334                    for (b, &j) in at.iter().enumerate() {
335                        f[(nd + i, nd + j)] -= s[(a, b)];
336                    }
337                }
338            }
339        }
340        let (s, x) = if nd > 0 {
341            schur(&f, nd).ok_or(GreenError::Singular(energy))?
342        } else {
343            (f, CMat::zeros(0, kept.len()))
344        };
345        Ok((kept.clone(), s, Factor { elim: delayed, boundary: kept, x, children: factors }))
346    }
347
348    fn block_transmissions(
349        &self,
350        block: &MultiBlock,
351        energy: f64,
352        precision: Precision,
353    ) -> Result<Vec<Vec<f64>>, GreenError> {
354        let sigmas = Self::self_energies(block, energy)?;
355        let (kept, s, _) = self.root(block, energy, &sigmas, false, precision)?;
356        let k = kept.len();
357        let g = Lu::new(s.as_ref()).solve(CMat::identity(k, k).as_ref());
358        if !g.norm_max().is_finite() {
359            return Err(GreenError::Singular(energy));
360        }
361        let gammas: Vec<Option<CMat>> = sigmas.iter().map(|s| s.as_ref().map(broadening)).collect();
362        let n = self.lead_count;
363        let mut t = vec![vec![0.0; n]; n];
364        for (p, row) in t.iter_mut().enumerate() {
365            for (q, tpq) in row.iter_mut().enumerate() {
366                let (Some(lp), Some(lq), Some(gp), Some(gq)) =
367                    (&block.leads[p], &block.leads[q], &gammas[p], &gammas[q])
368                else {
369                    continue;
370                };
371                let (ip, iq) = (index(&kept, lp), index(&kept, lq));
372                let gpq = CMat::from_fn(ip.len(), iq.len(), |a, b| g[(ip[a], iq[b])]);
373                *tpq = caroli_trace(gp, &gpq, gq);
374            }
375        }
376        Ok(t)
377    }
378
379    /// Scattering states at `energy`: `ψ_p = G W_p` on every device orbital for each lead `p`
380    /// (`W_p W_p† = Γ_p`, one column per channel), as
381    /// [`crate::NestedTwoTerminal::scattering_states`].
382    pub fn scattering_states(&self, energy: f64) -> Result<ScatteringStates, GreenError> {
383        let n = self.h.n;
384        let mut parts: Vec<Vec<CMat>> = vec![Vec::new(); self.lead_count];
385        for block in &self.blocks {
386            let sigmas = Self::self_energies(block, energy)?;
387            let roots: Vec<Option<CMat>> =
388                sigmas.iter().map(|s| s.as_ref().map(gamma_root).transpose()).collect::<Result<_, _>>()?;
389            let (kept, s, delayed) = self.root(block, energy, &sigmas, true, Precision::Double)?;
390            // Sources: W_p on the orbitals of lead p, one block of columns per lead.
391            let widths: Vec<usize> = roots.iter().map(|w| w.as_ref().map_or(0, |w| w.ncols())).collect();
392            let total: usize = widths.iter().sum();
393            let mut rhs = CMat::zeros(kept.len(), total);
394            let mut c0 = 0;
395            for ((l, w), &width) in block.leads.iter().zip(&roots).zip(&widths) {
396                if let (Some(l), Some(w)) = (l, w) {
397                    for (a, &i) in index(&kept, l).iter().enumerate() {
398                        for c in 0..width {
399                            rhs[(i, c0 + c)] = w[(a, c)];
400                        }
401                    }
402                }
403                c0 += width;
404            }
405            let x = Lu::new(s.as_ref()).solve(rhs.as_ref());
406            if !x.norm_max().is_finite() {
407                return Err(GreenError::Singular(energy));
408            }
409            let mut psi = CMat::zeros(n, total);
410            for (a, &o) in kept.iter().enumerate() {
411                for c in 0..total {
412                    psi[(o, c)] = x[(a, c)];
413                }
414            }
415            delayed.back_substitute(&mut psi);
416            let mut c0 = 0;
417            for (p, &width) in widths.iter().enumerate() {
418                parts[p].push(psi.as_ref().subcols(c0, width).to_owned());
419                c0 += width;
420            }
421        }
422        let leads = parts
423            .into_iter()
424            .map(|blocks| {
425                let cols: usize = blocks.iter().map(|m| m.ncols()).sum();
426                let mut out = CMat::zeros(n, cols);
427                let mut c0 = 0;
428                for m in blocks {
429                    out.as_mut().subcols_mut(c0, m.ncols()).copy_from(&m);
430                    c0 += m.ncols();
431                }
432                out
433            })
434            .collect();
435        Ok(ScatteringStates { energy, leads })
436    }
437
438    /// Scattering matrix at `energy` in the basis of the propagating lead modes, as
439    /// `kwant.smatrix` (see [`SMatrix`]).
440    pub fn smatrix(&self, energy: f64) -> Result<SMatrix, GreenError> {
441        let z = c64::new(energy, 0.0);
442        let mut parts = Vec::with_capacity(self.blocks.len());
443        for block in &self.blocks {
444            // Every distinct lead once.
445            let mut solved: Vec<(usize, Rc<LeadSolution>)> = Vec::new();
446            let mut solutions: Vec<Option<Rc<LeadSolution>>> = Vec::with_capacity(self.lead_count);
447            for (p, l) in block.leads.iter().enumerate() {
448                let Some(l) = l else {
449                    solutions.push(None);
450                    continue;
451                };
452                let known = solved.iter().find(|(k, _)| {
453                    let m = block.leads[*k].as_ref().unwrap();
454                    m.h00 == l.h00 && m.h01 == l.h01
455                });
456                let solution = match known {
457                    Some((_, s)) => Rc::clone(s),
458                    None => Rc::new(LeadSolution::new(&l.h00, &l.h01, z)?),
459                };
460                if known.is_none() {
461                    solved.push((p, Rc::clone(&solution)));
462                }
463                solutions.push(Some(solution));
464            }
465            let sigmas: Vec<Option<CMat>> = block
466                .leads
467                .iter()
468                .zip(&solutions)
469                .map(|(l, s)| l.as_ref().zip(s.as_ref()).map(|(l, s)| s.self_energy(&l.coupling)))
470                .collect();
471            let (kept, s, _) = self.root(block, energy, &sigmas, false, Precision::Double)?;
472            let k = kept.len();
473            let green = Lu::new(s.as_ref()).solve(CMat::identity(k, k).as_ref());
474            if !green.norm_max().is_finite() {
475                return Err(GreenError::Singular(energy));
476            }
477            let leads: Vec<Option<ScatteringLead>> = block
478                .leads
479                .iter()
480                .zip(solutions)
481                .map(|(l, s)| {
482                    l.as_ref().zip(s).map(|(l, solution)| ScatteringLead {
483                        at: index(&kept, l),
484                        coupling: &l.coupling,
485                        h01: &l.h01,
486                        solution,
487                    })
488                })
489                .collect();
490            parts.push(scattering_blocks(&green, &leads));
491        }
492        Ok(SMatrix::assemble(energy, parts))
493    }
494
495    /// Spectral bond currents `2 Re Tr[H_ij G^<_ji]` between every pair of coupled sites, from
496    /// the scattering states and the lead occupations `f` (one per lead).
497    pub fn bond_currents(&self, states: &ScatteringStates, f: &[f64]) -> Vec<BondCurrent> {
498        crate::nested::bond_currents(&self.h, &self.region, states, f, None)
499    }
500
501    /// Bond currents of an on-site operator `O` (see
502    /// [`crate::NestedTwoTerminal::operator_currents`]).
503    pub fn operator_currents(&self, states: &ScatteringStates, f: &[f64], op: &CMat) -> Vec<BondCurrent> {
504        crate::nested::bond_currents(&self.h, &self.region, states, f, Some(op))
505    }
506
507    /// Spectral density `Σ_p f_p ψ_p† O ψ_p / 2π` of every site (`O = 1` for `None`).
508    pub fn site_densities(&self, states: &ScatteringStates, f: &[f64], op: Option<&CMat>) -> Vec<f64> {
509        crate::nested::site_densities(&self.region, states, f, op)
510    }
511
512    /// The device region (orbital layout of the scattering states).
513    pub fn region(&self) -> &Region {
514        &self.region
515    }
516}
517
518/// Positions in `kept` (sorted) of the orbitals of lead `l`.
519fn index(kept: &[usize], l: &AttachedLead) -> Vec<usize> {
520    l.orbitals.iter().map(|o| kept.binary_search(o).expect("lead orbital kept")).collect()
521}