Skip to main content

caroli_green/
two_terminal.rs

1//! Two-terminal devices: recursive Green's function and Caroli transmission.
2
3use crate::gauge::Gauge;
4use crate::modes::{LeadModes, sigma_left, sigma_right};
5use crate::{
6    GreenError, adj_mul, broadening, caroli_trace, decimation, inverse, mul, resolvent_matrix, sandwich,
7    sandwich_adj,
8};
9use caroli_lattice::Region;
10use caroli_model::{CMat, Model, c64};
11
12/// A semi-infinite lead: `h00` is the cell Hamiltonian, `h01 = ⟨n| H |n+1⟩` the coupling to
13/// the next cell along the transport axis (towards +∞).
14#[derive(Clone, Debug)]
15pub struct Lead {
16    /// Cell Hamiltonian `⟨n| H |n⟩`.
17    pub h00: CMat,
18    /// Coupling `⟨n| H |n+1⟩` to the next cell towards +∞, for the left lead too (towards the
19    /// device).
20    pub h01: CMat,
21}
22
23impl Lead {
24    /// Modes of the lead at `energy`.
25    pub fn modes(&self, energy: f64) -> Result<LeadModes, GreenError> {
26        LeadModes::new(&self.h00, &self.h01, energy)
27    }
28
29    /// Modes of the lead at a complex energy (see [`LeadModes::at`]).
30    pub fn modes_at(&self, z: c64) -> Result<LeadModes, GreenError> {
31        LeadModes::at(&self.h00, &self.h01, z)
32    }
33
34    /// Bands of the lead at the Bloch phase `k` (radians per cell), in increasing order: the
35    /// eigenvalues of `H(k) = h00 + h01 e^{ik} + h01† e^{−ik}`.
36    pub fn bands(&self, k: f64) -> Vec<f64> {
37        let n = self.h00.nrows();
38        let phase = c64::from_polar(1.0, k);
39        let h = CMat::from_fn(n, n, |i, j| {
40            self.h00[(i, j)] + self.h01[(i, j)] * phase + self.h01[(j, i)].conj() * phase.conj()
41        });
42        let h = CMat::from_fn(n, n, |i, j| (h[(i, j)] + h[(j, i)].conj()) * 0.5);
43        let mut e: Vec<f64> = h.self_adjoint_eigenvalues(faer::Side::Lower).expect("Hermitian eigenvalues");
44        e.sort_by(f64::total_cmp);
45        e
46    }
47}
48
49/// How lead self-energies are computed.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum SelfEnergyMethod {
52    /// Mode matching (exact at real energy).
53    Modes,
54    /// Mode matching at `E + iη` for the leads only, the device staying at real energy (the
55    /// thesis codes: generalised Schur decomposition at `E + iη`).
56    ModesBroadened {
57        /// Imaginary part `η > 0` of the leads' energy (units of the Hamiltonian).
58        eta: f64,
59    },
60    /// Decimation at energy `E + iη`.
61    Decimation {
62        /// Imaginary part `η > 0` of the energy, in the leads and in the device (units of the
63        /// Hamiltonian).
64        eta: f64,
65    },
66}
67
68/// A device of `N` slices between a left lead (towards −∞) and a right lead (towards +∞).
69///
70/// `couplings[n] = ⟨n| H |n+1⟩`. The left lead couples to slice 0 through `left.h01`
71/// (`⟨lead| H |0⟩`) and the right lead to slice `N−1` through `right.h01` (`⟨N−1| H |lead⟩`):
72/// leads and device share the cross-section at the interfaces.
73#[derive(Clone, Debug)]
74pub struct TwoTerminal {
75    /// Hamiltonian `⟨n| H |n⟩` of each slice, `n = 0..N`.
76    pub slices: Vec<CMat>,
77    /// Couplings `⟨n| H |n+1⟩` between consecutive slices (`N − 1` of them).
78    pub couplings: Vec<CMat>,
79    /// Lead towards −∞, coupled to slice 0 through `left.h01`.
80    pub left: Lead,
81    /// Lead towards +∞, coupled to slice `N−1` through `right.h01`.
82    pub right: Lead,
83    /// Sites of each slice (orbital layout of `slices[n]`), when built from a model; empty for
84    /// systems assembled by hand.
85    pub regions: Vec<Region>,
86}
87
88impl TwoTerminal {
89    /// Two-terminal system built from a model on a region cut along primitive vector `axis`;
90    /// both leads continue the first and last slices of the region with the clean `lead`
91    /// model (the region's own model may carry disorder).
92    pub fn from_model(device: &Model, lead: &Model, region: &Region, axis: usize) -> Self {
93        for hop in lead.hoppings() {
94            assert!(hop.offset[axis].abs() <= 1, "a lead hopping skips a cell along axis {axis}");
95        }
96        crate::gauge::assert_same_field(device, lead);
97        let (slices, diag, off) = device.slice_blocks(region, axis);
98        let mut step = [0i64; 3];
99        step[axis] = 1;
100        // In a uniform field, everything in the gauge invariant along the axis.
101        let gauge = Gauge::along(device, step);
102        let diag = diag.into_iter().zip(&slices).map(|(m, s)| gauge.transform(m, s, s)).collect();
103        let off = off
104            .into_iter()
105            .enumerate()
106            .map(|(k, m)| gauge.transform(m, &slices[k], &slices[k + 1]))
107            .collect();
108        let lead_gauge = Gauge::along(lead, step);
109        let (first, last) = (&slices[0], &slices[slices.len() - 1]);
110        let (h00, h01) = lead_gauge.lead(first, step, [-step[0], -step[1], -step[2]]);
111        let left = Lead { h00, h01 };
112        let (h00, h01) = lead_gauge.lead(last, step, step);
113        let right = Lead { h00, h01 };
114        Self { slices: diag, couplings: off, left, right, regions: slices }
115    }
116
117    /// Shifts the electrostatic potential of the left and right leads (bias): adds `v·1` to
118    /// their cell Hamiltonians.
119    pub fn with_lead_potentials(mut self, left: f64, right: f64) -> Self {
120        for (lead, v) in [(&mut self.left, left), (&mut self.right, right)] {
121            for i in 0..lead.h00.nrows() {
122                lead.h00[(i, i)] += c64::new(v, 0.0);
123            }
124        }
125        self
126    }
127
128    /// Transmissions at many energies, in parallel, by independent blocks.
129    pub fn transmissions(&self, energies: &[f64], method: SelfEnergyMethod) -> Vec<Result<f64, GreenError>> {
130        use rayon::prelude::*;
131        use std::borrow::Cow;
132        let blocks = self.blocks();
133        // A single block (the usual case) is the system itself, not a copy of all its slices.
134        let parts: Vec<Cow<'_, Self>> = if blocks.len() > 1 {
135            blocks.iter().map(|b| Cow::Owned(self.restricted(b))).collect()
136        } else {
137            vec![Cow::Borrowed(self)]
138        };
139        energies.par_iter().map(|&e| parts.iter().map(|p| p.transmission_with(e, method)).sum()).collect()
140    }
141
142    /// Recursive sweeps from both ends at one energy (see [`Sweeps`]).
143    pub fn sweeps(&self, energy: f64, method: SelfEnergyMethod) -> Result<Sweeps, GreenError> {
144        let (sigma_l, sigma_r) = self.self_energies(energy, method)?;
145        let z = c64::new(energy, device_eta(method));
146        let n = self.slices.len();
147        let mut left = Vec::with_capacity(n);
148        for k in 0..n {
149            let mut a = resolvent_matrix(z, &self.slices[k]);
150            if k == 0 {
151                a -= &sigma_l;
152            } else {
153                let v = &self.couplings[k - 1];
154                a -= sandwich_adj(v, &left[k - 1]);
155            }
156            left.push(inverse(&a));
157        }
158        let mut right = vec![CMat::zeros(0, 0); n];
159        for k in (0..n).rev() {
160            let mut a = resolvent_matrix(z, &self.slices[k]);
161            if k == n - 1 {
162                a -= &sigma_r;
163            } else {
164                let v = &self.couplings[k];
165                a -= sandwich(v, &right[k + 1]);
166            }
167            right[k] = inverse(&a);
168        }
169        Ok(Sweeps { z, sigma_l, sigma_r, left, right })
170    }
171
172    /// Lead self-energies `(Σ_L, Σ_R)` on the first and last slices.
173    pub fn self_energies(&self, energy: f64, method: SelfEnergyMethod) -> Result<(CMat, CMat), GreenError> {
174        match method {
175            SelfEnergyMethod::Modes | SelfEnergyMethod::ModesBroadened { .. } => {
176                let z = match method {
177                    SelfEnergyMethod::ModesBroadened { eta } => c64::new(energy, eta),
178                    _ => c64::new(energy, 0.0),
179                };
180                // Identical leads (the usual case) share one set of modes.
181                let ml = self.left.modes_at(z)?;
182                let same = self.left.h00 == self.right.h00 && self.left.h01 == self.right.h01;
183                let own = if same { None } else { Some(self.right.modes_at(z)?) };
184                let mr = own.as_ref().unwrap_or(&ml);
185                Ok((sigma_left(&self.left.h01, &ml), sigma_right(&self.right.h01, mr)))
186            }
187            SelfEnergyMethod::Decimation { eta } => {
188                let z = c64::new(energy, eta);
189                let away_left = self.left.h01.adjoint().to_owned();
190                let gl = decimation::surface_green(&self.left.h00, &away_left, z)?;
191                let gr = decimation::surface_green(&self.right.h00, &self.right.h01, z)?;
192                let sigma_l = sandwich_adj(&self.left.h01, &gl);
193                let sigma_r = sandwich(&self.right.h01, &gr);
194                Ok((sigma_l, sigma_r))
195            }
196        }
197    }
198
199    /// Transmission `T(E) = Tr[Γ_L G_1N Γ_R G_1N†]` with mode-matching self-energies.
200    pub fn transmission(&self, energy: f64) -> Result<f64, GreenError> {
201        self.transmission_with(energy, SelfEnergyMethod::Modes)
202    }
203
204    /// Transmission with a chosen self-energy method.
205    pub fn transmission_with(&self, energy: f64, method: SelfEnergyMethod) -> Result<f64, GreenError> {
206        Ok(self.solve(energy, method)?.transmission())
207    }
208
209    /// Orbitals of the cross-section that no slice, coupling or lead matrix connects, as
210    /// independent sets (e.g. the two spin blocks of BHZ with spin-conserving disorder). One set
211    /// if the slices differ in size.
212    pub fn blocks(&self) -> Vec<Vec<usize>> {
213        let w = self.left.h00.nrows();
214        let same = self.slices.iter().all(|h| h.nrows() == w) && self.right.h00.nrows() == w;
215        if !same {
216            return vec![(0..w).collect()];
217        }
218        let mut parent: Vec<usize> = (0..w).collect();
219        fn find(p: &mut [usize], mut i: usize) -> usize {
220            while p[i] != i {
221                p[i] = p[p[i]];
222                i = p[i];
223            }
224            i
225        }
226        let mats = self.slices.iter().chain(&self.couplings).chain([
227            &self.left.h00,
228            &self.left.h01,
229            &self.right.h00,
230            &self.right.h01,
231        ]);
232        for m in mats {
233            for j in 0..m.ncols() {
234                for i in 0..m.nrows() {
235                    if m[(i, j)] != c64::new(0.0, 0.0) {
236                        let (a, b) = (find(&mut parent, i), find(&mut parent, j));
237                        parent[a.max(b)] = a.min(b);
238                    }
239                }
240            }
241        }
242        let mut sets: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
243        for i in 0..w {
244            let r = find(&mut parent, i);
245            sets.entry(r).or_default().push(i);
246        }
247        sets.into_values().collect()
248    }
249
250    /// The system restricted to `orbitals` of every slice (one of [`Self::blocks`]).
251    pub fn restricted(&self, orbitals: &[usize]) -> Self {
252        let pick =
253            |m: &CMat| CMat::from_fn(orbitals.len(), orbitals.len(), |i, j| m[(orbitals[i], orbitals[j])]);
254        Self {
255            slices: self.slices.iter().map(pick).collect(),
256            couplings: self.couplings.iter().map(pick).collect(),
257            left: Lead { h00: pick(&self.left.h00), h01: pick(&self.left.h01) },
258            right: Lead { h00: pick(&self.right.h00), h01: pick(&self.right.h01) },
259            regions: Vec::new(),
260        }
261    }
262
263    /// Transmission summed over the independent [`Self::blocks`], each solved on its own: for
264    /// `b` equal blocks the recursion costs `b²` times less.
265    pub fn transmission_by_blocks(&self, energy: f64, method: SelfEnergyMethod) -> Result<f64, GreenError> {
266        let blocks = self.blocks();
267        if blocks.len() == 1 {
268            return self.transmission_with(energy, method);
269        }
270        blocks.iter().map(|b| self.restricted(b).transmission_with(energy, method)).sum()
271    }
272
273    /// Lead self-energies and the Green's function `G_1N` between the first and last slices.
274    pub fn solve(&self, energy: f64, method: SelfEnergyMethod) -> Result<EndToEnd, GreenError> {
275        let (sigma_l, sigma_r) = self.self_energies(energy, method)?;
276        let z = c64::new(energy, device_eta(method));
277        let n = self.slices.len();
278        // Left-connected Green's functions g_n = [z − H_nn − V_{n−1}† g_{n−1} V_{n−1} − Σ]⁻¹
279        // and the first row G_1n = G_1,n−1 V_{n−1} g_n.
280        let mut a = resolvent_matrix(z, &self.slices[0]) - &sigma_l;
281        if n == 1 {
282            a -= &sigma_r;
283        }
284        let mut g = inverse(&a);
285        let mut g1n = g.clone();
286        for k in 1..n {
287            let v = &self.couplings[k - 1];
288            let mut a = resolvent_matrix(z, &self.slices[k]) - sandwich_adj(v, &g);
289            if k == n - 1 {
290                a -= &sigma_r;
291            }
292            g = inverse(&a);
293            g1n = mul(&mul(&g1n, v), &g);
294        }
295        Ok(EndToEnd { sigma_l, sigma_r, g1n })
296    }
297}
298
299/// Imaginary part of the energy used inside the device.
300fn device_eta(method: SelfEnergyMethod) -> f64 {
301    match method {
302        SelfEnergyMethod::Modes | SelfEnergyMethod::ModesBroadened { .. } => 0.0,
303        SelfEnergyMethod::Decimation { eta } => eta,
304    }
305}
306
307/// Recursive sweeps of a two-terminal device at one energy `z`:
308/// `left[n]` is the Green's function of slices `0..=n` with the left lead only, `right[n]` that
309/// of slices `n..N` with the right lead only. Everything else follows:
310/// `G_nn = [z − H_nn − Σ^<-side_n − Σ^>-side_n]⁻¹`, `G_n0 = right[n] V_{n−1}† G_{n−1,0}` and
311/// `G_{n,N−1} = left[n] V_n G_{n+1,N−1}`.
312#[derive(Clone, Debug)]
313pub struct Sweeps {
314    /// Energy of the device: `E`, or `E + iη` with [`SelfEnergyMethod::Decimation`].
315    pub z: c64,
316    /// Self-energy `Σ_L` of the left lead on slice 0.
317    pub sigma_l: CMat,
318    /// Self-energy `Σ_R` of the right lead on slice `N−1`.
319    pub sigma_r: CMat,
320    /// `left[n]`: block `(n, n)` of the Green's function of slices `0..=n` with the left lead only.
321    pub left: Vec<CMat>,
322    /// `right[n]`: block `(n, n)` of the Green's function of slices `n..N` with the right lead only.
323    pub right: Vec<CMat>,
324}
325
326impl Sweeps {
327    /// Full diagonal block `G_nn`.
328    pub fn diagonal(&self, sys: &TwoTerminal, n: usize) -> CMat {
329        let last = self.left.len() - 1;
330        let mut a = resolvent_matrix(self.z, &sys.slices[n]);
331        if n == 0 {
332            a -= &self.sigma_l;
333        } else {
334            let v = &sys.couplings[n - 1];
335            a -= sandwich_adj(v, &self.left[n - 1]);
336        }
337        if n == last {
338            a -= &self.sigma_r;
339        } else {
340            let v = &sys.couplings[n];
341            a -= sandwich(v, &self.right[n + 1]);
342        }
343        inverse(&a)
344    }
345
346    /// Column `G_n0` for every slice `n` (propagation from the left lead).
347    pub fn first_column(&self, sys: &TwoTerminal) -> Vec<CMat> {
348        let mut col = vec![self.diagonal(sys, 0)];
349        for n in 1..self.left.len() {
350            let next = mul(&self.right[n], &adj_mul(&sys.couplings[n - 1], &col[n - 1]));
351            col.push(next);
352        }
353        col
354    }
355
356    /// Column `G_{n,N−1}` for every slice `n` (propagation from the right lead).
357    pub fn last_column(&self, sys: &TwoTerminal) -> Vec<CMat> {
358        let last = self.left.len() - 1;
359        let mut col = vec![CMat::zeros(0, 0); last + 1];
360        col[last] = self.diagonal(sys, last);
361        for n in (0..last).rev() {
362            col[n] = mul(&self.left[n], &mul(&sys.couplings[n], &col[n + 1]));
363        }
364        col
365    }
366}
367
368/// Result of [`TwoTerminal::solve`]: lead self-energies on the first and last slices and the
369/// retarded Green's function between them.
370#[derive(Clone, Debug)]
371pub struct EndToEnd {
372    /// Self-energy `Σ_L` of the left lead on the first slice.
373    pub sigma_l: CMat,
374    /// Self-energy `Σ_R` of the right lead on the last slice.
375    pub sigma_r: CMat,
376    /// Block `G_1N` of the retarded Green's function: rows on the first slice, columns on the last.
377    pub g1n: CMat,
378}
379
380impl EndToEnd {
381    /// Caroli transmission `Tr[Γ_L G_1N Γ_R G_1N†]`.
382    pub fn transmission(&self) -> f64 {
383        caroli_trace(&broadening(&self.sigma_l), &self.g1n, &broadening(&self.sigma_r))
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    fn one(x: f64) -> CMat {
392        CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0))
393    }
394
395    fn chain(n: usize) -> TwoTerminal {
396        TwoTerminal {
397            slices: vec![one(0.0); n],
398            couplings: vec![one(-1.0); n - 1],
399            left: Lead { h00: one(0.0), h01: one(-1.0) },
400            right: Lead { h00: one(0.0), h01: one(-1.0) },
401            regions: Vec::new(),
402        }
403    }
404
405    /// BHZ ribbon with on-site disorder: two spin blocks, same transmission as the full system.
406    #[test]
407    fn blocks_of_bhz_with_spin_conserving_disorder() {
408        use caroli_model::presets::{BhzParams, bhz};
409        let clean = bhz(BhzParams::default());
410        let pot = |s: &caroli_lattice::Site| {
411            let v = ((s.cell[0] * 7 + s.cell[1] * 3) % 5) as f64 * 0.1 - 0.2;
412            Some(CMat::from_fn(4, 4, |i, j| if i == j { c64::new(v, 0.0) } else { c64::new(0.0, 0.0) }))
413        };
414        let device = bhz(BhzParams::default()).with_onsite_term(pot);
415        let region = Region::cuboid(clean.lattice(), [6, 5, 0]);
416        let sys = TwoTerminal::from_model(&device, &clean, &region, 0);
417        let blocks = sys.blocks();
418        assert_eq!(blocks.len(), 2);
419        assert_eq!(blocks[0].len(), 10);
420        for e in [-0.3, 0.05, 0.4] {
421            let full = sys.transmission(e).unwrap();
422            let split = sys.transmission_by_blocks(e, SelfEnergyMethod::Modes).unwrap();
423            assert!((full - split).abs() < 1e-10, "E {e}: {full} vs {split}");
424        }
425    }
426
427    /// The sweeps agree with the direct inversion of the whole device matrix.
428    #[test]
429    fn sweeps_match_full_inversion() {
430        let mut sys = chain(6);
431        sys.slices[2] = one(0.4);
432        sys.slices[4] = one(-0.3);
433        let e = 0.37;
434        let sw = sys.sweeps(e, SelfEnergyMethod::Modes).unwrap();
435        let n = 6;
436        let mut a = CMat::from_fn(n, n, |i, j| match i.abs_diff(j) {
437            0 => c64::new(e, 0.0) - sys.slices[i][(0, 0)],
438            1 => c64::new(1.0, 0.0),
439            _ => c64::new(0.0, 0.0),
440        });
441        a[(0, 0)] -= sw.sigma_l[(0, 0)];
442        a[(n - 1, n - 1)] -= sw.sigma_r[(0, 0)];
443        let g = inverse(&a);
444        let first = sw.first_column(&sys);
445        let last = sw.last_column(&sys);
446        for k in 0..n {
447            assert!((sw.diagonal(&sys, k)[(0, 0)] - g[(k, k)]).norm() < 1e-12);
448            assert!((first[k][(0, 0)] - g[(k, 0)]).norm() < 1e-12);
449            assert!((last[k][(0, 0)] - g[(k, n - 1)]).norm() < 1e-12);
450        }
451        let direct = sys.solve(e, SelfEnergyMethod::Modes).unwrap();
452        assert!((direct.g1n[(0, 0)] - g[(0, n - 1)]).norm() < 1e-12);
453    }
454
455    /// Clean chain with hopping −1: T = 1 inside the band |E| < 2, 0 outside, at every energy,
456    /// including the band centre where decimation is ill-conditioned.
457    #[test]
458    fn chain_transmission_modes() {
459        let sys = chain(5);
460        for e in [-1.9, -1.0, 0.0, 1e-9, 0.3, 1.5] {
461            let t = sys.transmission(e).unwrap();
462            assert!((t - 1.0).abs() < 1e-12, "T({e}) = {t}");
463        }
464        assert!(sys.transmission(2.5).unwrap().abs() < 1e-12);
465    }
466
467    #[test]
468    fn chain_transmission_decimation() {
469        let sys = chain(5);
470        for e in [-1.9, -1.0, 0.3, 1.5] {
471            let t = sys.transmission_with(e, SelfEnergyMethod::Decimation { eta: 1e-12 }).unwrap();
472            assert!((t - 1.0).abs() < 1e-9, "T({e}) = {t}");
473        }
474    }
475
476    /// A single impurity of strength u in a chain: T = 1 / (1 + (u / (2 sin k))²), E = −2 cos k.
477    #[test]
478    fn chain_impurity() {
479        let mut sys = chain(5);
480        let u = 0.7;
481        sys.slices[2] = one(u);
482        for e in [-1.2, 0.0, 0.8] {
483            let k = (-e / 2.0f64).acos();
484            let exact = 1.0 / (1.0 + (u / (2.0 * k.sin())).powi(2));
485            let t = sys.transmission(e).unwrap();
486            assert!((t - exact).abs() < 1e-12, "T({e}) = {t}, exact {exact}");
487        }
488    }
489
490    /// Analytic surface Green's function of the chain: g = (E − i sqrt(4 − E²)) / 2 for |E| < 2,
491    /// from decimation and from the modes.
492    #[test]
493    fn chain_surface_green() {
494        let e = 0.7;
495        let exact = c64::new(e / 2.0, -(4.0 - e * e).sqrt() / 2.0);
496        let g = decimation::surface_green(&one(0.0), &one(-1.0), c64::new(e, 1e-12)).unwrap();
497        assert!((g[(0, 0)] - exact).norm() < 1e-8, "{} vs {exact}", g[(0, 0)]);
498        let modes = LeadModes::new(&one(0.0), &one(-1.0), e).unwrap();
499        let g = crate::modes::surface_green_right(&one(0.0), &one(-1.0), e, &modes);
500        assert!((g[(0, 0)] - exact).norm() < 1e-12, "{} vs {exact}", g[(0, 0)]);
501        assert_eq!(modes.channels(), 1);
502    }
503}