1use crate::gauge::Gauge;
9use crate::modes::{ModeSolver, sigma_right};
10use crate::{GreenError, SelfEnergyMethod, broadening, caroli_trace, decimation, inverse, sandwich};
11use caroli_lattice::{Cell, Region};
12use caroli_model::{CMat, Model, c64};
13
14#[derive(Clone, Debug)]
16pub struct AttachedLead {
17 pub h00: CMat,
19 pub h01: CMat,
21 pub orbitals: Vec<usize>,
23 pub coupling: CMat,
25}
26
27impl AttachedLead {
28 pub fn surface_green(&self, energy: f64, method: SelfEnergyMethod) -> Result<CMat, GreenError> {
30 let z = match method {
31 SelfEnergyMethod::Modes => c64::new(energy, 0.0),
32 SelfEnergyMethod::ModesBroadened { eta } | SelfEnergyMethod::Decimation { eta } => {
33 c64::new(energy, eta)
34 }
35 };
36 if let SelfEnergyMethod::Decimation { .. } = method {
37 return decimation::surface_green(&self.h00, &self.h01, z);
38 }
39 self.surface_green_with(&ModeSolver::new(&self.h00, &self.h01), z)
40 }
41
42 pub(crate) fn surface_green_with(&self, solver: &ModeSolver, z: c64) -> Result<CMat, GreenError> {
44 let rest = sigma_right(&self.h01, &solver.modes_at(z)?);
45 let n = self.h00.nrows();
46 Ok(inverse(&CMat::from_fn(n, n, |i, j| {
47 (if i == j { z } else { c64::new(0.0, 0.0) }) - self.h00[(i, j)] - rest[(i, j)]
48 })))
49 }
50
51 pub fn self_energy(&self, energy: f64, method: SelfEnergyMethod) -> Result<CMat, GreenError> {
53 let g = self.surface_green(energy, method)?;
54 Ok(sandwich(&self.coupling, &g))
55 }
56}
57
58#[derive(Clone, Debug)]
60pub struct MultiTerminal {
61 pub h: CMat,
64 pub leads: Vec<AttachedLead>,
66 pub region: Option<Region>,
68}
69
70#[derive(Clone, Debug)]
73pub struct Interface {
74 pub slice: Region,
77 pub outward: Cell,
80}
81
82impl MultiTerminal {
83 pub fn from_model(device: &Model, lead: &Model, region: &Region, interfaces: &[Interface]) -> Self {
87 crate::gauge::assert_same_field(device, lead);
88 Self {
89 h: device.hamiltonian(region),
90 leads: attach_leads(lead, region, interfaces),
91 region: Some(region.clone()),
92 }
93 }
94
95 pub fn solve(&self, energy: f64, method: SelfEnergyMethod) -> Result<MultiSolution, GreenError> {
97 let n = self.h.nrows();
98 let eta = match method {
99 SelfEnergyMethod::Decimation { eta } => eta,
100 _ => 0.0,
101 };
102 let mut a = CMat::from_fn(n, n, |i, j| {
103 (if i == j { c64::new(energy, eta) } else { c64::new(0.0, 0.0) }) - self.h[(i, j)]
104 });
105 let mut sigmas = Vec::with_capacity(self.leads.len());
106 for lead in &self.leads {
107 let s = lead.self_energy(energy, method)?;
108 for (p, &i) in lead.orbitals.iter().enumerate() {
109 for (q, &j) in lead.orbitals.iter().enumerate() {
110 a[(i, j)] -= s[(p, q)];
111 }
112 }
113 sigmas.push(s);
114 }
115 Ok(MultiSolution { g: inverse(&a), sigmas })
116 }
117}
118
119pub(crate) fn attach_leads(lead: &Model, region: &Region, interfaces: &[Interface]) -> Vec<AttachedLead> {
121 interfaces
122 .iter()
123 .map(|itf| {
124 let shift = |k: i64| -> Cell { [k * itf.outward[0], k * itf.outward[1], k * itf.outward[2]] };
125 let first = itf.slice.translated(shift(1));
126 assert!(
127 first.sites().iter().all(|s| region.index_of(s).is_none()),
128 "the first lead cell overlaps the device"
129 );
130 let skip = lead.coupling(&itf.slice, &itf.slice.translated(shift(2)));
131 assert!(skip.norm_max() == 0.0, "a lead hopping reaches beyond the next cell");
132 let gauge = Gauge::along(lead, itf.outward);
135 let (h00, h01) = gauge.lead(&itf.slice, itf.outward, itf.outward);
136 let v = gauge.transform_columns(lead.coupling(region, &first), &first);
137 let orbitals: Vec<usize> =
138 (0..v.nrows()).filter(|&i| (0..v.ncols()).any(|j| v[(i, j)] != c64::new(0.0, 0.0))).collect();
139 AttachedLead {
140 h00,
141 h01,
142 coupling: CMat::from_fn(orbitals.len(), v.ncols(), |a, j| v[(orbitals[a], j)]),
143 orbitals,
144 }
145 })
146 .collect()
147}
148
149pub fn lead_voltages(t: &[Vec<f64>], currents: &[f64], ground: usize) -> Vec<f64> {
157 let n = t.len();
158 assert!(currents.len() == n && t.iter().all(|row| row.len() == n), "one current per lead");
159 assert!(
160 currents.iter().sum::<f64>().abs() <= 1e-12 * currents.iter().map(|c| c.abs()).sum::<f64>().max(1.0)
161 );
162 let g = |p: usize, q: usize| {
163 if p == q { (0..n).filter(|&r| r != p).map(|r| t[r][p]).sum() } else { -t[p][q] }
164 };
165 let free: Vec<usize> = (0..n).filter(|&p| p != ground).collect();
166 let a = CMat::from_fn(free.len(), free.len(), |i, j| c64::new(g(free[i], free[j]), 0.0));
167 let b = CMat::from_fn(free.len(), 1, |i, _| c64::new(currents[free[i]], 0.0));
168 let v = caroli_dense::Lu::new(a.as_ref()).solve(b.as_ref());
169 let mut out = vec![0.0; n];
170 for (i, &p) in free.iter().enumerate() {
171 out[p] = v[(i, 0)].re;
172 }
173 out
174}
175
176#[derive(Clone, Debug)]
178pub struct MultiSolution {
179 pub g: CMat,
181 pub sigmas: Vec<CMat>,
183}
184
185impl MultiSolution {
186 pub fn block(&self, sys: &MultiTerminal, p: usize, q: usize) -> CMat {
188 let (rp, rq) = (&sys.leads[p].orbitals, &sys.leads[q].orbitals);
189 CMat::from_fn(rp.len(), rq.len(), |i, j| self.g[(rp[i], rq[j])])
190 }
191
192 pub fn transmission(&self, sys: &MultiTerminal, p: usize, q: usize) -> f64 {
194 let g = self.block(sys, p, q);
195 caroli_trace(&broadening(&self.sigmas[p]), &g, &broadening(&self.sigmas[q]))
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use crate::TwoTerminal;
203 use caroli_lattice::Lattice;
204
205 #[test]
208 fn narrow_lead_on_graphene() {
209 let lat = Lattice::honeycomb(1.0, 1);
210 let one = |x: f64| CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0));
211 let g = Model::new(lat.clone())
212 .hopping(0, 1, [0, 0, 0], one(-1.0))
213 .hopping(0, 1, [0, -1, 0], one(-1.0))
214 .hopping(0, 1, [1, -1, 0], one(-1.0));
215 let site = |x: i64, y: i64, s: usize| caroli_lattice::Site { cell: [x, y, 0], sub: s };
216 let column = |x: i64, ys: std::ops::Range<i64>| {
217 Region::from_sites(&lat, ys.flat_map(|y| (0..2).map(move |s| site(x, y, s))).collect())
218 };
219 let device = |x0: i64| {
220 let mut sites: Vec<caroli_lattice::Site> =
221 (0..6).flat_map(|x| (0..6).flat_map(move |y| (0..2).map(move |s| site(x, y, s)))).collect();
222 for x in x0..0 {
223 sites.extend((2..4).flat_map(|y| (0..2).map(move |s| site(x, y, s))));
224 }
225 Region::from_sites(&lat, sites)
226 };
227 let t = |x0: i64, e: f64| {
228 let region = device(x0);
229 let sys = MultiTerminal::from_model(
230 &g,
231 &g,
232 ®ion,
233 &[
234 Interface { slice: column(x0, 2..4), outward: [-1, 0, 0] },
235 Interface { slice: column(5, 0..6), outward: [1, 0, 0] },
236 ],
237 );
238 sys.solve(e, SelfEnergyMethod::Modes).unwrap().transmission(&sys, 1, 0)
239 };
240 for e in [-0.7, 0.45, 1.3] {
241 let (a, b) = (t(0, e), t(-1, e));
242 assert!((a - b).abs() < 1e-9, "E {e}: {a} vs {b}");
243 }
244 }
245
246 #[test]
249 fn agrees_with_two_terminal_and_unitarity() {
250 let lat = Lattice::square(1.0, 1);
252 let one = |x: f64| CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0));
253 let clean =
254 Model::new(lat.clone()).hopping(0, 0, [1, 0, 0], one(-1.0)).hopping(0, 0, [0, 1, 0], one(-1.0));
255 let pot = move |s: &caroli_lattice::Site| match s.cell {
256 [2, 1, _] => Some(one(0.7)),
257 [3, 2, _] => Some(one(-0.4)),
258 _ => None,
259 };
260 let device = Model::new(lat.clone())
261 .hopping(0, 0, [1, 0, 0], one(-1.0))
262 .hopping(0, 0, [0, 1, 0], one(-1.0))
263 .with_onsite_term(pot);
264 let region = Region::cuboid(&lat, [6, 4, 0]);
265 let slices = region.slices(0);
266 let two = TwoTerminal::from_model(&device, &clean, ®ion, 0);
267 let multi = MultiTerminal::from_model(
268 &device,
269 &clean,
270 ®ion,
271 &[
272 Interface { slice: slices[0].clone(), outward: [-1, 0, 0] },
273 Interface { slice: slices[5].clone(), outward: [1, 0, 0] },
274 ],
275 );
276 for e in [-1.3, 0.2, 0.9] {
277 let t2 = two.transmission(e).unwrap();
278 let sol = multi.solve(e, SelfEnergyMethod::Modes).unwrap();
279 let tm = sol.transmission(&multi, 0, 1);
280 assert!((t2 - tm).abs() < 1e-10, "E {e}: {t2} vs {tm}");
281 assert!((sol.transmission(&multi, 1, 0) - tm).abs() < 1e-10);
282 }
283 }
284}