Coverage for tbkit/transport.py: 100%

629 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-21 11:05 +0000

1r""" 

2Quantum transport through a finite Tight-Binding device attached to 

3semi-infinite leads: the Landauer-Buttiker picture, in which the (linear, 

4zero-temperature) conductance between two leads is the transmission 

5probability at the Fermi energy, 

6 

7.. math:: 

8 

9 G = \frac{e^2}{h}\,T(E_F)\, ,\qquad 

10 T(E) = \mathrm{Tr}\left[\Gamma_{out}\,G^r\,\Gamma_{in}\,G^a\right]\, , 

11 

12(the Caroli formula) with :math:`G^r = [E + i\eta - H - \sum_l\Sigma_l]^{-1}` 

13the device's retarded Green's function, :math:`\Sigma_l` the self-energy of 

14lead :math:`l` and :math:`\Gamma_l = i(\Sigma_l - \Sigma_l^\dagger)`. 

15 

16A lead is a semi-infinite repetition of a unit cell with Hamiltonian 

17:math:`h_0`, each cell coupled to the next one (away from the device) by 

18:math:`v`; its surface cell is coupled to some device sites by 

19:math:`\tau`. Its surface Green's function comes from the decimation 

20algorithm of Lopez Sancho, Lopez Sancho and Rubio (J. Phys. F 15, 851 

21(1985)), and :math:`\Sigma = \tau\, g_s\,\tau^\dagger`. 

22 

23Examples 

24-------- 

25Example usage:: 

26 

27 # a perfect chain of 10 sites between two chain leads: T = 1 in the band 

28 tr = Transport(sys.ham) 

29 h0, v = np.zeros((1, 1)), np.ones((1, 1)) 

30 tr.add_lead(h0, v, coupling=np.ones((1, 1)), sites=[0]) 

31 tr.add_lead(h0, v, coupling=np.ones((1, 1)), sites=[9]) 

32 T = tr.transmission(np.linspace(-1.9, 1.9, 50)) 

33 

34*Transport.attach_lead* builds the coupling and finds the device sites 

35itself, from a lead given as a 1D *KSpace* model placed in the device's 

36coordinates (e.g. ``tr.attach_lead(sys, strip, 1)``). 

37 

38*Transport.smatrix* gives the scattering matrix itself. It uses the exact 

39propagating and evanescent modes of the leads (*lead_modes*, with no 

40broadening) and one sparse factorization of the device per energy (the 

41formulation of Groth et al. 2014, as in Kwant). *Transport.wave_function* 

42and *Transport.ldos* give the scattering states and the local density of 

43states they carry. *Transport.transmission* uses the scattering matrix by 

44default. 

45 

46With more leads, *Transport.conductance_matrix* and 

47*four_terminal_resistance* solve the Landauer-Buttiker equations (Hall 

48bars); *bond_currents* and *local_currents* map the current; 

49*transmission_eigenvalues*, *shot_noise* and *fano_factor* give the shot 

50noise. By default they too come from the scattering matrix and the 

51scattering states, on the same sparse factorization. *RecursiveTransport* computes the two-terminal transmission of long 

52quasi-1D devices slice by slice (recursive Green's function), without 

53inverting the whole device. 

54""" 

55from __future__ import annotations 

56 

57import threading 

58from concurrent.futures import ThreadPoolExecutor 

59from typing import Callable, NamedTuple, TypeVar 

60 

61import numpy as np 

62from numpy.typing import ArrayLike, NDArray 

63import scipy.linalg as LA 

64import scipy.sparse as sp 

65import scipy.sparse.linalg as spla 

66 

67import tbkit.error_handling as error_handling 

68 

69_MUMPS: list = [] # [the python-mumps module, or None without it], once looked for 

70_MUMPS_LOCK = threading.Lock() # MUMPS is not thread-safe: one call at a time 

71_MUMPS_WIDTH = 50 # orbitals of the widest lead from which solver 'auto' takes MUMPS 

72_POOL = threading.local() # .active is set in the threads of _EnergyWorkers._map 

73_SCHUR_FILL = 64 # largest Schur complement of _mumps_schur, in entries per unknown 

74_SCHUR_GROWTH = 1e3 # largest Schur entry, over the largest of the matrix, that is trusted 

75 

76_T = TypeVar('_T') 

77 

78def surface_green( 

79 h0: ArrayLike, v: ArrayLike, energy: float, eta: float = 1e-9, tol: float = 1e-12, 

80 max_iter: int = 10000, 

81) -> NDArray[np.complex128]: 

82 r''' 

83 Get the surface Green's function of a semi-infinite lead: cells 

84 :math:`0, 1, 2, \dots`, with :math:`H_{nn} = h_0` and 

85 :math:`H_{n,n+1} = v`, :math:`H_{n+1,n} = v^\dagger`, by the 

86 Lopez Sancho-Rubio decimation (each iteration doubles the number of 

87 cells accounted for, so it converges in a few tens of steps inside the 

88 bands, as :math:`\eta\to0^+`). 

89 

90 Parameters 

91 ---------- 

92 h0 : Square complex array 

93 Cell Hamiltonian. 

94 v : Square complex array, same shape 

95 Coupling of a cell to the next one. 

96 energy : Real number 

97 Energy. 

98 eta : Positive real, default 1e-9 

99 Broadening. 

100 tol : Positive real, default 1e-12 

101 Convergence threshold on 

102 the norm of the renormalized couplings. 

103 max_iter : Positive integer, default 10000 

104 

105 Returns 

106 ------- 

107 gs 

108 Complex ndarray, same shape as *h0*: :math:`g_s = [E+i\eta - h_0 - \Sigma_{bulk}]^{-1}`. 

109 ''' 

110 h0 = np.atleast_2d(np.asarray(h0, dtype='c16')) 

111 v = np.atleast_2d(np.asarray(v, dtype='c16')) 

112 error_handling.lead(h0, v) 

113 error_handling.real_number(energy, 'energy') 

114 error_handling.positive_real(eta, 'eta') 

115 error_handling.positive_real(tol, 'tol') 

116 error_handling.positive_int(max_iter, 'max_iter') 

117 gs, _ = _green_surface_bulk(np.array([energy + 1j * eta]), h0, v, v.conj().T, tol, max_iter, 

118 'surface_green') 

119 return gs[0] 

120 

121 

122def _green_surface_bulk( 

123 z: NDArray[np.complex128], h0: NDArray[np.complex128], alpha: NDArray[np.complex128], 

124 beta: NDArray[np.complex128], tol: float, max_iter: int, name: str, 

125) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]: 

126 r''' 

127 Private function. The surface and bulk Green's functions of one cell 

128 of the semi-infinite chain of *_decimation* (*h0*, *alpha*, *beta* of 

129 shape (m, m)) at the complex energies *z*, shapes (nz, m, m). 

130 

131 The first decimation step inverts :math:`z - h_0`: at an energy equal to 

132 an eigenvalue of :math:`h_0` (E = 0 for a plain chain) that is 

133 :math:`\sim1/\eta`, and the precision is lost. Regrouping n = 1, 2 or 3 

134 cells into one (the same chain) moves those energies: at each energy, 

135 the best-conditioned grouping is used. 

136 ''' 

137 m = len(h0) 

138 # Scaling cell n by r**n is a similarity transform that leaves the 

139 # Green's function of every cell unchanged: balancing the couplings of a 

140 # non-reciprocal chain keeps the renormalized ones from overflowing 

141 # (r = 1 when beta = alpha^dagger). 

142 n_a, n_b = np.linalg.norm(alpha), np.linalg.norm(beta) 

143 if n_a > 0 and n_b > 0: 

144 r = np.sqrt(n_b / n_a) 

145 alpha, beta = alpha * r, beta / r 

146 groups, best, choice = [], None, np.zeros(len(z), int) 

147 for c, n in enumerate((1, 2, 3)): 

148 hn = (np.kron(np.eye(n), h0) + np.kron(np.eye(n, k=1), alpha) 

149 + np.kron(np.eye(n, k=-1), beta)) 

150 an = np.kron(np.eye(n, k=1 - n), alpha) 

151 bn = np.kron(np.eye(n, k=n - 1), beta) 

152 groups.append((hn, an, bn)) 

153 smin = np.linalg.svd(z[:, None, None] * np.eye(n * m)[None] - hn, compute_uv=False)[:, -1] 

154 if best is None: 

155 best = smin 

156 else: 

157 better = smin > best * (1. + 1e-12) 

158 choice[better], best = c, np.where(better, smin, best) 

159 gs, gb = np.empty((len(z), m, m), 'c16'), np.empty((len(z), m, m), 'c16') 

160 for c, (hn, an, bn) in enumerate(groups): 

161 sel = choice == c 

162 if np.any(sel): 

163 s_, b_ = _decimation(z[sel], hn, an, bn, tol, max_iter, name) 

164 gs[sel], gb[sel] = s_[:, :m, :m], b_[:, :m, :m] 

165 return gs, gb 

166 

167 

168def _decimation( 

169 z: NDArray[np.complex128], h0: NDArray[np.complexfloating], alpha: NDArray[np.complexfloating], 

170 beta: NDArray[np.complexfloating], tol: float, max_iter: int, name: str, 

171) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]: 

172 r''' 

173 Private function. The Lopez Sancho-Rubio decimation of a semi-infinite 

174 chain of cells :math:`0, 1, 2, \dots` (:math:`H_{nn} = h_0`, 

175 :math:`H_{n,n+1} = \alpha`, :math:`H_{n+1,n} = \beta`, with 

176 :math:`\beta = \alpha^\dagger` unless the chain is non-reciprocal) at 

177 many complex energies *z* (shape (nz,)) at once; *h0*, *alpha* and *beta* 

178 have shape (m, m) or (nz, m, m). Used by *surface_green* and 

179 *KSpace.surface_spectral_function*, which validate the arguments. It 

180 stops when the renormalized couplings are below *tol* at every energy 

181 (a RuntimeError naming *name* after *max_iter* iterations). 

182 

183 Returns 

184 ------- 

185 gs : Complex ndarray, shape (nz, m, m) 

186 Surface Green's function (cell 0). 

187 gb : Complex ndarray, shape (nz, m, m) 

188 Bulk Green's function 

189 (one cell of the infinite chain). 

190 ''' 

191 m = h0.shape[-1] 

192 zi = np.asarray(z, dtype='c16')[:, None, None] * np.eye(m)[None] 

193 eps_s = np.broadcast_to(h0, zi.shape).astype('c16') 

194 eps = eps_s.copy() 

195 alpha = np.broadcast_to(alpha, zi.shape).astype('c16') 

196 beta = np.broadcast_to(beta, zi.shape).astype('c16') 

197 for _ in range(max_iter): 

198 g = np.linalg.inv(zi - eps) 

199 ag, bg = alpha @ g, beta @ g 

200 eps_s = eps_s + ag @ beta 

201 eps = eps + ag @ beta + bg @ alpha 

202 alpha, beta = ag @ alpha, bg @ beta 

203 if np.all(np.linalg.norm(alpha, axis=(1, 2)) + np.linalg.norm(beta, axis=(1, 2)) < tol): 

204 break 

205 else: 

206 error_handling.converged(False, name) 

207 return np.linalg.inv(zi - eps_s), np.linalg.inv(zi - eps) 

208 

209 

210def lead_from_kspace(ks, direction: int = 1) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]: 

211 r''' 

212 Get the cell Hamiltonian :math:`h_0` and coupling :math:`v` of a lead 

213 from a 1D periodic model (e.g. a ribbon, see *kspace.ribbon*), whose 

214 hoppings reach at most the neighbouring cells. 

215 

216 Parameters 

217 ---------- 

218 ks : **KSpace** instance, 1D 

219 direction : +1 or -1, default 1 

220 Direction, along the 

221 model's primitive vector, in which the lead extends away from the 

222 device: :math:`v` gathers the hoppings to the cell at 

223 :math:`\mathbf{R} = \pm\mathbf{a}_1`. 

224 

225 Returns 

226 ------- 

227 h0 : Complex ndarray, shape (norb, norb) 

228 v : Complex ndarray, shape (norb, norb) 

229 ''' 

230 error_handling.dim_exact(ks.dim, 1) 

231 error_handling.lead_direction(direction) 

232 h0 = np.diag(ks.onsite).astype('c16') + ks._onsite_offdiag 

233 v = np.zeros((ks.norb, ks.norb), 'c16') 

234 for i, j, (n,), t in ks._hop_cells(): 

235 error_handling.nearest_cells(n) 

236 if n == 0: 

237 h0[i, j] += t 

238 elif n == direction: 

239 v[i, j] += t 

240 return h0, v 

241 

242 

243class LeadModes(NamedTuple): 

244 r''' 

245 The propagating modes of a lead at one energy (see *lead_modes*): 

246 the incoming ones first (moving towards the device, velocity < 0), then 

247 the outgoing ones, each group by block of the conservation law, then in 

248 increasing momentum. 

249 

250 * **wave_functions** -- Complex ndarray, shape (m, n_modes). Mode :math:`\phi` 

251 on the lead's surface cell: cell :math:`n` carries :math:`\lambda^n\phi`, 

252 with :math:`\lambda = e^{ik}`. Normalized to unit current. 

253 * **momenta** -- Real ndarray, shape (n_modes,). :math:`k` in :math:`(-\pi, \pi]`. 

254 * **velocities** -- Real ndarray, shape (n_modes,). :math:`dE/dk`, 

255 positive away from the device. 

256 * **blocks** -- Integer ndarray, shape (n_modes,). The block of the 

257 conservation law each mode belongs to: the index of its eigenvalue, 

258 in increasing order (all 0 without a conservation law). 

259 ''' 

260 wave_functions: NDArray[np.complex128] 

261 momenta: NDArray[np.float64] 

262 velocities: NDArray[np.float64] 

263 blocks: NDArray[np.int64] 

264 

265 

266def lead_modes( 

267 h0: ArrayLike, v: ArrayLike, energy: float, conservation_law: ArrayLike | None = None, 

268) -> LeadModes: 

269 r''' 

270 Get the propagating modes of a semi-infinite lead (cells 

271 :math:`0, 1, 2, \dots` away from the device, :math:`H_{nn} = h_0`, 

272 :math:`H_{n,n+1} = v`) at one energy. A mode :math:`\psi_n = \lambda^n\phi` 

273 solves :math:`(E - h_0 - \lambda v - \lambda^{-1}v^\dagger)\phi = 0`, the 

274 generalized eigenproblem of the transfer matrix 

275 

276 .. math:: 

277 

278 \begin{pmatrix} 0 & 1\\ -v^\dagger & E - h_0\end{pmatrix} 

279 \begin{pmatrix}\phi\\ \lambda\phi\end{pmatrix} = \lambda 

280 \begin{pmatrix} 1 & 0\\ 0 & v\end{pmatrix} 

281 \begin{pmatrix}\phi\\ \lambda\phi\end{pmatrix}\, , 

282 

283 solved as an ordinary eigenproblem when :math:`v` is well conditioned, 

284 and by the QZ algorithm otherwise, so that a singular :math:`v` is 

285 allowed (in real arithmetic for a real lead). The 

286 modes with :math:`|\lambda| = 1` propagate with the velocity 

287 :math:`dE/dk = -2\,\mathrm{Im}(\lambda\phi^\dagger v\phi)` (diagonalized 

288 within degenerate modes). There is no broadening :math:`\eta`, so the 

289 modes are exact up to the band edges. 

290 

291 A *conservation_law* :math:`Q` (spin :math:`\sigma_z`, the electron-hole 

292 :math:`\tau_z` of a normal lead, a valley) commutes with :math:`h_0` and 

293 :math:`v`. The modes are then found in each eigenspace of :math:`Q` 

294 separately, so that every mode carries one of its eigenvalues, even 

295 when modes of different blocks are degenerate. 

296 

297 Parameters 

298 ---------- 

299 h0 : Square complex array, Hermitian 

300 Cell Hamiltonian. 

301 v : Square complex array, same shape 

302 Coupling of a cell to the 

303 next one, away from the device. 

304 energy : Real number 

305 Energy, not at a band edge of the lead. 

306 conservation_law : Hermitian complex array, shape of *h0*, or None, default None 

307 

308 Returns 

309 ------- 

310 modes : **LeadModes**: the wave functions, momenta, velocities and blocks 

311 ''' 

312 h0 = np.atleast_2d(np.asarray(h0, dtype='c16')) 

313 v = np.atleast_2d(np.asarray(v, dtype='c16')) 

314 error_handling.lead(h0, v) 

315 error_handling.real_number(energy, 'energy') 

316 law = _law_blocks(h0, v, conservation_law) 

317 return _lead_modes(h0, v, float(energy), law)[0] 

318 

319 

320def _law_blocks( 

321 h0: NDArray[np.complex128], v: NDArray[np.complex128], law: ArrayLike | None, 

322) -> list[NDArray[np.complex128]] | None: 

323 r''' 

324 Private function. Validate a conservation law of a lead and return an 

325 orthonormal basis (shape (m, d)) of each of its eigenspaces, in 

326 increasing eigenvalue (None without a conservation law). 

327 ''' 

328 if law is None: 

329 return None 

330 law = np.atleast_2d(np.asarray(law, dtype='c16')) 

331 error_handling.conservation_law(law, h0, v) 

332 w, u = np.linalg.eigh(law) 

333 breaks = np.flatnonzero(np.diff(w) > 1e-8 * max(1., np.max(np.abs(w)))) + 1 

334 return [u[:, g] for g in np.split(np.arange(len(w)), breaks)] 

335 

336 

337def _lead_modes( 

338 h0: NDArray[np.complex128], v: NDArray[np.complex128], energy: float, 

339 law: list[NDArray[np.complex128]] | None = None, tol: float = 1e-6, 

340) -> tuple[LeadModes, int, NDArray[np.complex128], NDArray[np.complex128]]: 

341 r''' 

342 Private function. The modes of a lead (see *lead_modes*), the number of 

343 incoming ones, and a basis of every solution that leaves the device or 

344 decays away from it: its values on cells 0 and 1, *u0* and *u1* of shape 

345 (m, m). Its first columns are the outgoing modes of *LeadModes*, the 

346 others span the evanescent modes (a Schur basis of the pencil, which 

347 stays well conditioned when :math:`v` is singular and many 

348 :math:`\lambda` vanish). Modes with :math:`||\lambda| - 1| \le` *tol* 

349 propagate. With the eigenspaces *law* of a conservation law 

350 (*_law_blocks*), each block :math:`P^\dagger h_0P`, :math:`P^\dagger vP` 

351 is solved on its own and embedded back. 

352 ''' 

353 if law is not None: 

354 # the incoming modes of every block, then the outgoing ones, then 

355 # the evanescent ones: the order of the single-block case 

356 phi_parts, k_parts, vel_parts, block, out0, out1, ev0, ev1 = ([] for _ in range(8)) 

357 for ib, p in enumerate(law): 

358 md, n, u0, u1 = _lead_modes(p.conj().T @ h0 @ p, p.conj().T @ v @ p, energy, None, tol) 

359 phi_parts.append((p @ md.wave_functions[:, :n], p @ md.wave_functions[:, n:])) 

360 k_parts.append((md.momenta[:n], md.momenta[n:])) 

361 vel_parts.append((md.velocities[:n], md.velocities[n:])) 

362 block.append(np.full(n, ib)) 

363 out0.append(p @ u0[:, :n]) 

364 out1.append(p @ u1[:, :n]) 

365 ev0.append(p @ u0[:, n:]) 

366 ev1.append(p @ u1[:, n:]) 

367 modes = LeadModes(np.hstack([f[0] for f in phi_parts] + [f[1] for f in phi_parts]), 

368 np.concatenate([f[0] for f in k_parts] + [f[1] for f in k_parts]), 

369 np.concatenate([f[0] for f in vel_parts] + [f[1] for f in vel_parts]), 

370 np.concatenate(block * 2)) 

371 return modes, sum(len(b) for b in block), np.hstack(out0 + ev0), np.hstack(out1 + ev1) 

372 error_handling.hermitian_operator(h0) 

373 m = len(h0) 

374 # real arithmetic for a real lead: about twice as fast 

375 real = not (np.any(h0.imag) or np.any(v.imag)) 

376 hr, vr = (h0.real, v.real) if real else (h0, v) 

377 output = 'real' if real else 'complex' 

378 eye, zero = np.eye(m), np.zeros((m, m)) 

379 a = np.block([[zero, eye], [-vr.conj().T, energy * eye - hr]]) 

380 # decaying (|lambda| < 1, including lambda = 0) first; beta = 0 is lambda = infinity 

381 if np.linalg.cond(v) < 1e4: 

382 # invertible v: the ordinary eigenproblem of B^-1 A, an order of magnitude faster than QZ 

383 a[m:] = LA.solve(vr, a[m:]) 

384 sort = (lambda x, y: np.hypot(x, y) < 1 - tol) if real else (lambda x: np.abs(x) < 1 - tol) 

385 _, z, n_dec = LA.schur(a, output=output, sort=sort) 

386 alpha, vecs = LA.eig(a) 

387 beta = np.ones(2 * m) 

388 else: 

389 b = np.block([[eye, zero], [zero, vr]]) 

390 _, _, alpha, beta, _, z = LA.ordqz(a, b, sort=lambda al, be: np.abs(al) < (1 - tol) * np.abs(be), 

391 output=output) 

392 n_dec = int(np.sum(np.abs(alpha) < (1 - tol) * np.abs(beta))) 

393 (alpha, beta), vecs = LA.eig(a, b, homogeneous_eigvals=True) 

394 unit = (np.abs(np.abs(alpha) - np.abs(beta)) <= tol * np.abs(beta)) & (beta != 0) 

395 lams, vecs = alpha[unit] / beta[unit], vecs[:m, unit] 

396 phi_cols: list = [] 

397 k_list: list = [] 

398 vel_list: list = [] 

399 left = list(range(len(lams))) 

400 while left: 

401 # a group of degenerate lambdas: its modes span the kernel of the 

402 # Hermitian E - h0 - lam v - lam^* v^dagger; diagonalize the velocity there 

403 group = [i for i in left if abs(lams[i] - lams[left[0]]) < tol] 

404 left = [i for i in left if i not in group] 

405 lam = np.mean(lams[group]) 

406 lam /= abs(lam) 

407 if len(group) == 1: 

408 phi = vecs[:, group] / np.linalg.norm(vecs[:, group]) 

409 else: 

410 # an orthonormal basis of the kernel, which eig does not guarantee 

411 w, u = np.linalg.eigh(energy * eye - h0 - lam * v - np.conj(lam) * v.conj().T) 

412 phi = u[:, np.argsort(np.abs(w))[:len(group)]] 

413 vel, rot = np.linalg.eigh(1j * (lam * phi.conj().T @ v @ phi 

414 - np.conj(lam) * phi.conj().T @ v.conj().T @ phi)) 

415 error_handling.lead_band_edge(np.min(np.abs(vel)) > tol, energy) 

416 phi_cols.append(phi @ rot / np.sqrt(np.abs(vel))) 

417 k_list += [np.angle(lam)] * len(group) 

418 vel_list.append(vel) 

419 phis = np.hstack(phi_cols) if phi_cols else np.zeros((m, 0), 'c16') 

420 ks, vels = np.array(k_list), np.concatenate(vel_list) if vel_list else np.zeros(0) 

421 order = np.lexsort((ks, vels > 0)) # incoming (v < 0) first, then by momentum 

422 phis, ks, vels = phis[:, order], ks[order], vels[order] 

423 n_in = int(np.sum(vels < 0)) 

424 error_handling.lead_band_edge(2 * n_in == len(vels) and n_in + n_dec == m, energy) 

425 out = phis[:, n_in:] 

426 u0 = np.hstack([out, z[:m, :n_dec]]) 

427 u1 = np.hstack([out * np.exp(1j * ks[n_in:]), z[m:, :n_dec]]) 

428 return LeadModes(phis, ks, vels, np.zeros(len(ks), int)), n_in, u0, u1 

429 

430 

431def _mumps_module(solver: str, width: int): 

432 r''' 

433 Private function. The python-mumps module that the sparse solver 

434 *solver* (*Transport.solver*) uses, or None for SuperLU. ``'auto'`` is 

435 MUMPS when python-mumps is installed and the widest lead has at least 

436 *_MUMPS_WIDTH* orbitals (*width*): below, on narrow or small devices, 

437 SuperLU is as fast or faster. In the threads of *set_workers* it is 

438 SuperLU too: MUMPS runs one factorization at a time, SuperLU one per 

439 thread. 

440 ''' 

441 error_handling.transport_solver(solver) 

442 if solver == 'superlu' or (solver == 'auto' and (width < _MUMPS_WIDTH or getattr(_POOL, 'active', False))): 

443 return None 

444 if not _MUMPS: 

445 try: 

446 import mumps 

447 except ImportError: 

448 mumps = None 

449 _MUMPS.append(mumps) 

450 if _MUMPS[0] is None and solver == 'mumps': 

451 raise ImportError("\n\nTransport.solver = 'mumps' needs the python-mumps package " 

452 "(conda install -c conda-forge python-mumps).\n") 

453 return _MUMPS[0] 

454 

455 

456def _solve(mat, rhs, rows: NDArray[np.int64] | None, solver: str, width: int) -> NDArray[np.complex128]: 

457 r''' 

458 Private function. Solve the sparse system *mat* x = *rhs* (both CSC, 

459 one column of *rhs* per right-hand side) with one factorization, and 

460 return the rows *rows* of x (every row for None), as a dense array. 

461 *solver* and *width* (the orbitals of the widest lead) choose between 

462 MUMPS and SuperLU (*_mumps_module*). 

463 

464 With MUMPS and *rows*, nothing but the interface (*rows* and the rows 

465 where *rhs* is not zero) is solved for: MUMPS eliminates the other 

466 unknowns and returns the Schur complement on the interface 

467 (*_mumps_schur*), a small dense system. Otherwise the matrix is 

468 factorized (MUMPS or *scipy.sparse.linalg.splu*) and the right-hand 

469 sides are solved in column blocks. 

470 ''' 

471 mumps = _mumps_module(solver, width) 

472 if mumps is None or mat.shape[0] == 1: # python-mumps 0.0.6 refuses a 1 x 1 solution 

473 lu = spla.splu(mat) 

474 return _solve_columns(lambda b: lu.solve(b.toarray()), rhs, rows) 

475 with _MUMPS_LOCK: 

476 sol = None if rows is None else _mumps_schur(mumps, mat, rhs, rows) 

477 return _mumps_columns(mumps, mat, rhs, rows) if sol is None else sol 

478 

479 

480def _solve_columns(solve: Callable, rhs, rows: NDArray[np.int64] | None) -> NDArray[np.complex128]: 

481 r''' 

482 Private function. The rows *rows* of the solutions *solve* (rhs), from 

483 the sparse right-hand sides in column blocks whose dense solutions 

484 take at most 64 MB. 

485 ''' 

486 size, n_rhs = rhs.shape 

487 chunk = max(1, 2**22 // size) 

488 keep = slice(None) if rows is None else rows 

489 return np.hstack([solve(rhs[:, c:c + chunk])[keep] for c in range(0, n_rhs, chunk)]) 

490 

491 

492def _mumps_columns(mumps, mat, rhs, rows: NDArray[np.int64] | None) -> NDArray[np.complex128]: 

493 r''' 

494 Private function. *_solve* by a MUMPS factorization of the whole matrix. 

495 ''' 

496 ctx = mumps.Context() 

497 try: # the MUMPS instance is freed here, under _MUMPS_LOCK, even after an error 

498 ctx.factor(mat.tocoo()) 

499 return _solve_columns(ctx.solve, rhs, rows) 

500 finally: 

501 del ctx 

502 

503 

504def _mumps_schur(mumps, mat, rhs, rows: NDArray[np.int64]) -> NDArray[np.complex128] | None: 

505 r''' 

506 Private function. *_solve* through the Schur complement. With I the 

507 interface (*rows* and the non-zero rows of *rhs*) and D the other 

508 unknowns, where the right-hand side vanishes, 

509 

510 .. math:: 

511 

512 S x_I = b_I\, ,\qquad S = A_{II} - A_{ID}A_{DD}^{-1}A_{DI}\, , 

513 

514 and MUMPS returns S without the triangular solves of a full solution. 

515 

516 Returns None, for *_solve* to factorize the whole matrix instead, when 

517 the interface is the whole system or too large for a dense S (more 

518 than *_SCHUR_FILL* entries per unknown), or when :math:`A_{DD}` is singular or nearly so 

519 (an eigenstate of the device cut from its leads at this energy), which 

520 shows as an S with entries above *_SCHUR_GROWTH* times those of the matrix. 

521 ''' 

522 idx = np.union1d(rows, rhs.indices) 

523 if idx.size == mat.shape[0] or idx.size**2 > _SCHUR_FILL * mat.shape[0]: 

524 return None 

525 ctx = mumps.Context() 

526 try: # the MUMPS instance is freed here, under _MUMPS_LOCK 

527 schur = ctx.schur(idx, mat.tocoo(), discard_factors=True) 

528 except mumps.MUMPSError: 

529 return None 

530 finally: 

531 del ctx 

532 if not np.all(np.isfinite(schur)) or np.abs(schur).max() > _SCHUR_GROWTH * np.abs(mat.data).max(): 

533 return None 

534 return np.linalg.solve(schur, rhs.tocsr()[idx].toarray())[np.searchsorted(idx, rows)] 

535 

536 

537class SMatrix(): 

538 r''' 

539 The scattering matrix of a device at one energy (see 

540 *Transport.smatrix*): ``data[a, b]`` is the amplitude of outgoing mode 

541 *a* for an incoming mode *b* of unit current. The rows are the outgoing 

542 modes of lead 0, then lead 1, ...; the columns the incoming ones, in the 

543 order of *lead_info*. It is unitary for a Hermitian device. 

544 

545 A lead is an integer, or a tuple ``(lead, block)`` that keeps only the 

546 modes in one block of the lead's conservation law (*Transport.add_lead*), 

547 for example ``(0, 1)`` for the electrons and ``(0, 0)`` for the holes of 

548 a normal lead with :math:`Q = \tau_z`. 

549 

550 Attributes 

551 ---------- 

552 data : Complex ndarray, shape (n_out, n_in) 

553 lead_info : List of **LeadModes**, one per lead 

554 ''' 

555 

556 def __init__( 

557 self, data: NDArray[np.complex128], lead_info: list[LeadModes], n_blocks: list[int] | None = None, 

558 ) -> None: 

559 self.data = data 

560 self.lead_info = lead_info 

561 self._n_blocks = [1] * len(lead_info) if n_blocks is None else list(n_blocks) 

562 counts = [int(np.sum(m.velocities < 0)) for m in lead_info] 

563 self._bounds = np.concatenate([[0], np.cumsum(counts)]).astype(int) 

564 

565 def _modes(self, lead: int | tuple[int, int], outgoing: bool) -> NDArray[np.int64]: 

566 r''' 

567 Private method. The rows (*outgoing*) or columns of the modes of a 

568 lead, or of one block of it. 

569 ''' 

570 error_handling.lead_block(lead, self._n_blocks) 

571 l = lead[0] if isinstance(lead, tuple) else lead 

572 idx = np.arange(self._bounds[l], self._bounds[l + 1]) 

573 if isinstance(lead, tuple): 

574 n = len(idx) 

575 blocks = self.lead_info[l].blocks 

576 idx = idx[(blocks[n:] if outgoing else blocks[:n]) == lead[1]] 

577 return idx 

578 

579 def num_propagating(self, lead: int | tuple[int, int]) -> int: 

580 r''' 

581 Get the number of propagating modes (incoming, as many as outgoing) 

582 of a lead, or of one block of it. 

583 

584 Parameters 

585 ---------- 

586 lead : Integer or tuple (lead, block) 

587 

588 Returns 

589 ------- 

590 n : Integer 

591 ''' 

592 return len(self._modes(lead, False)) 

593 

594 def submatrix( 

595 self, lead_out: int | tuple[int, int], lead_in: int | tuple[int, int], 

596 ) -> NDArray[np.complex128]: 

597 r''' 

598 Get the block of the scattering matrix from lead *lead_in* to lead 

599 *lead_out*: the transmission amplitudes :math:`t`, or the reflection 

600 amplitudes :math:`r` if the two are equal. 

601 

602 Parameters 

603 ---------- 

604 lead_out : Integer or tuple (lead, block) 

605 lead_in : Integer or tuple (lead, block) 

606 

607 Returns 

608 ------- 

609 s 

610 Complex ndarray, shape (num_propagating(lead_out), num_propagating(lead_in)). 

611 ''' 

612 return self.data[np.ix_(self._modes(lead_out, True), self._modes(lead_in, False))] 

613 

614 def transmission(self, lead_out: int | tuple[int, int], lead_in: int | tuple[int, int]) -> float: 

615 r''' 

616 Get the transmission :math:`\sum_{ab}|S_{ab}|^2` from lead *lead_in* 

617 to lead *lead_out* (the reflection if they are equal). With blocks, 

618 ``transmission((0, 0), (0, 1))`` is, for example, the Andreev 

619 reflection of electrons into holes. 

620 

621 Parameters 

622 ---------- 

623 lead_out : Integer or tuple (lead, block) 

624 lead_in : Integer or tuple (lead, block) 

625 

626 Returns 

627 ------- 

628 T : Real number 

629 ''' 

630 return float(np.sum(np.abs(self.submatrix(lead_out, lead_in)) ** 2)) 

631 

632 

633class _EnergyWorkers(): 

634 r''' 

635 Private mixin. The threads over which *Transport* and 

636 *RecursiveTransport* spread the energies of their many-energy methods. 

637 ''' 

638 workers = 1 # threads over the energies, see set_workers 

639 

640 def set_workers(self, workers: int) -> None: 

641 r''' 

642 Set the number of threads over which the methods taking many energies 

643 spread them: *transmission* and *fano_factor*, and for *Transport* 

644 also *shot_noise*, and *conductance*, *thermoelectric*, 

645 *conductance_matrix* and *four_terminal_resistance* at a finite 

646 temperature (the energies of the Fermi window). Each 

647 energy is one sparse factorization (or, for *RecursiveTransport*, 

648 dense inversions of slices), mostly in 

649 LAPACK and SuperLU, which release the GIL, so the energies run in 

650 parallel. In these threads the default *Transport.solver* keeps 

651 SuperLU, since MUMPS factorizes one matrix at a time. The 

652 results do not depend on *workers*, up to rounding. 

653 

654 Parameters 

655 ---------- 

656 workers : Positive integer 

657 Number of threads (default 1, no threads). 

658 

659 Examples 

660 -------- 

661 Example usage:: 

662 

663 tr.set_workers(4) 

664 T = tr.transmission(np.linspace(-2, 2, 400)) 

665 ''' 

666 error_handling.positive_int(workers, 'workers') 

667 self.workers = workers 

668 

669 def _map(self, func: Callable[[float], _T], energies: NDArray[np.float64]) -> list[_T]: 

670 r''' 

671 Private method. *func* at every energy, in order, spread over 

672 *workers* threads. 

673 ''' 

674 if self.workers > 1 and len(energies) > 1: 

675 with ThreadPoolExecutor(min(self.workers, len(energies)), 

676 initializer=setattr, initargs=(_POOL, 'active', True)) as pool: 

677 return list(pool.map(func, (float(e) for e in energies))) 

678 return [func(float(e)) for e in energies] 

679 

680 

681class Transport(_EnergyWorkers): 

682 r''' 

683 A finite device, of Hamiltonian *ham* (e.g. *System.ham*), to which 

684 semi-infinite leads are attached with *add_lead*; *transmission* then 

685 gives the Landauer transmission between two of them. 

686 

687 The device is stored sparse. *smatrix*, *wave_function*, *ldos*, and by 

688 default (*eta* None) the transmissions, conductance matrix, currents and 

689 noise, only factorize the sparse matrix. With a broadening *eta* (and, 

690 as a fallback, for non-Hermitian leads, with *eta* = 1e-9) these use the 

691 Green's function, but only its columns on the sites of the leads, from 

692 one sparse factorization of :math:`E + i\eta - H - \sum_l\Sigma_l` per 

693 energy. Only *get_green* and *self_energy*, which return full matrices, 

694 build the dense matrix *ham* (once, the first time it is needed). 

695 

696 The sparse solver is *solver*: ``'mumps'`` (the optional python-mumps 

697 package, ``conda install -c conda-forge python-mumps``), ``'superlu'`` 

698 (SciPy) or ``'auto'``, the default. MUMPS is several times faster on 

699 large 2D and 3D devices, and where only the leads matter (*smatrix*, 

700 the transmissions, the noise) it solves for the lead sites alone. 

701 SuperLU is as fast or faster on small devices and on narrow ones, 

702 however long. ``'auto'`` takes MUMPS when it is installed and a lead 

703 has at least 50 orbitals, and SuperLU otherwise; for a wide device 

704 with narrow leads, set MUMPS, on the class or on one object:: 

705 

706 tr.solver = 'mumps' 

707 

708 Parameters 

709 ---------- 

710 ham : Square matrix (sparse or dense) 

711 Device Hamiltonian. 

712 ''' 

713 solver = 'auto' # sparse solver: 'auto', 'mumps' or 'superlu' 

714 

715 def __init__(self, ham) -> None: 

716 ham = sp.csr_matrix(ham, dtype='c16') 

717 error_handling.square_matrix(ham, 'ham') 

718 self._ham = ham 

719 self._dense: NDArray[np.complex128] | None = None 

720 self.leads: list = [] # list of (h0, v, coupling, sites) 

721 self._laws: list = [] # eigenspaces of each lead's conservation law, or None 

722 self._added_pos = np.zeros((0, 0)) # sites added by attach_lead(extend=True), and tags 

723 self._added_tags: list[str] = [] 

724 

725 @property 

726 def ham(self) -> NDArray[np.complex128]: 

727 r''' 

728 The device Hamiltonian, as a dense complex ndarray. 

729 ''' 

730 if self._dense is None: 

731 self._dense = self._ham.toarray() 

732 return self._dense 

733 

734 def add_lead( 

735 self, h0: ArrayLike, v: ArrayLike, coupling: ArrayLike, sites: list[int], 

736 conservation_law: ArrayLike | None = None, 

737 ) -> None: 

738 r''' 

739 Attach a semi-infinite lead (see *surface_green*). 

740 

741 A *conservation_law* :math:`Q`, Hermitian and commuting with 

742 :math:`h_0` and :math:`v`, sorts the lead's modes into the eigenspaces 

743 of :math:`Q` (*lead_modes*), and *smatrix* then resolves its blocks: 

744 :math:`\sigma_z` for spin-resolved transport, the electron-hole 

745 :math:`\tau_z` of a normal lead for Andreev reflection. The device 

746 itself need not conserve :math:`Q`. 

747 

748 Parameters 

749 ---------- 

750 h0 : Square complex array, shape (m, m) 

751 Lead cell Hamiltonian. 

752 v : Square complex array, shape (m, m) 

753 Coupling of a lead cell 

754 to the next one, away from the device. 

755 coupling : Complex array, shape (len(sites), m) 

756 Hoppings 

757 :math:`\tau` between the device *sites* and the lead's surface cell. 

758 sites : List of device site (row) indices the lead touches 

759 conservation_law : Hermitian complex array, shape (m, m), or None, default None 

760 Its blocks are numbered in increasing eigenvalue. 

761 ''' 

762 h0 = np.atleast_2d(np.asarray(h0, dtype='c16')) 

763 v = np.atleast_2d(np.asarray(v, dtype='c16')) 

764 error_handling.lead(h0, v) 

765 coupling = np.atleast_2d(np.asarray(coupling, dtype='c16')) 

766 error_handling.lead_coupling(coupling, sites, len(h0), self._ham.shape[0]) 

767 law = _law_blocks(h0, v, conservation_law) 

768 self.leads.append((h0, v, coupling, list(sites))) 

769 self._laws.append(law) 

770 

771 def attach_lead( 

772 self, sys, ks, direction: int = 1, conservation_law: ArrayLike | None = None, 

773 extend: bool = False, 

774 ) -> tuple[sp.csr_matrix, NDArray[np.float64]] | None: 

775 r''' 

776 Attach a semi-infinite lead given as a 1D *KSpace* model (e.g. a 

777 ribbon, see *kspace.ribbon*) to the device built from *sys*, without 

778 writing the coupling by hand. Returns, with *extend*, the enlarged 

779 device (None otherwise). 

780 

781 The lead's sites sit at :math:`\boldsymbol\tau_o + n\mathbf{a}_1` 

782 (its *unit_cell* positions, in the coordinates of *sys*, and its 

783 primitive vector). The device sites found at these positions, with 

784 the same tag, are copies of lead orbitals; the outermost cell along 

785 *direction* that holds some of them is the interface. The lead 

786 starts at the next cell, and couples to the interface sites through 

787 its own hoppings: :math:`\tau = v` restricted to their orbitals (see 

788 *lead_from_kspace*, which also gives :math:`h_0` and :math:`v`). 

789 Every lead orbital with a hopping into the next cell must be present 

790 in the interface cell. 

791 

792 With *extend*, a device whose edge is ragged relative to the lead 

793 (a disc under a strip, a flake under a zigzag lead) is completed 

794 first, as Kwant's *attach_lead* does: starting from the lead's first 

795 cell, every lead site reached through the lead's hoppings and absent 

796 from the device is added to it, cell by cell towards the device, 

797 until the sites reached are all present. The added sites take the 

798 lead's onsite energies and its hoppings to their neighbours (device 

799 or added sites at lead positions). They come after the device 

800 sites, so the sites of the leads already attached keep their 

801 indices, and a later *attach_lead* with the same *sys* knows of them. 

802 

803 Parameters 

804 ---------- 

805 sys 

806 **System** instance (one orbital per site) whose 

807 Hamiltonian, in the same site order, is the device of this 

808 *Transport* (followed by the sites added by earlier *extend* calls). 

809 ks 

810 **KSpace** instance, 1D and spinless, with hoppings 

811 between neighbouring cells only. 

812 direction : +1 or -1, default 1 

813 Direction, along the 

814 lead's primitive vector, in which the lead extends away from the device. 

815 conservation_law : Hermitian complex array, shape (norb, norb), or None, default None 

816 See *add_lead*. 

817 extend : Boolean, default False 

818 Add the missing lead 

819 sites to the device instead of refusing an incomplete interface. 

820 

821 Returns 

822 ------- 

823 ham : Sparse CSR complex matrix 

824 The device Hamiltonian, 

825 the added sites last. 

826 positions : Real ndarray, shape (n_sites, space_dim) 

827 The 

828 positions of its sites, those of *sys* first. 

829 

830 Examples 

831 -------- 

832 Example usage:: 

833 

834 strip = ribbon(lattices.square(), hoppings, width=5, direction=1) 

835 tr = Transport(sys.ham) 

836 tr.attach_lead(sys, strip, -1) # at the left end of the device 

837 tr.attach_lead(sys, strip, 1) # at the right end 

838 ham, pos = tr.attach_lead(disc, strip, 1, extend=True) # ragged edge 

839 ''' 

840 from tbkit.orbital import OrbitalSystem 

841 error_handling.sys(sys) 

842 error_handling.not_orbital_system(sys, OrbitalSystem) 

843 error_handling.empty_coor(sys.lat.coor) 

844 error_handling.boolean(extend, 'extend') 

845 error_handling.lead_device_size(sys.lat.sites + len(self._added_tags), self._ham.shape[0]) 

846 error_handling.spinless(ks.spin) 

847 h0, v = lead_from_kspace(ks, direction) 

848 error_handling.lead_space_dim(ks.space_dim, sys.lat.space_dim) 

849 _law_blocks(h0, v, conservation_law) 

850 pos = self._site_positions(sys) 

851 tags = np.concatenate([sys.lat.coor['tag'], np.array(self._added_tags, dtype=str)]) 

852 a = np.array(ks.lat.prim_vec[0], dtype='f8') 

853 tau = ks.orbital_positions() 

854 cell = np.zeros(len(pos), int) 

855 orb = np.full(len(pos), -1) 

856 for o in range(ks.norb): 

857 rel = pos - tau[o] 

858 n = np.rint(rel @ a / (a @ a)).astype(int) 

859 hit = (orb < 0) & (np.linalg.norm(rel - n[:, None] * a, axis=1) < error_handling.ATOL) \ 

860 & (tags == ks.tags[o]) 

861 cell[hit], orb[hit] = n[hit], o 

862 on_lead = orb >= 0 

863 error_handling.lead_overlap(bool(on_lead.any())) 

864 edge = direction * np.max(direction * cell[on_lead]) 

865 if extend: 

866 added = self._extend(h0, v, direction, cell, orb, edge) 

867 new = np.reshape([tau[o] + n * a for n, o in added], (-1, pos.shape[1])) 

868 self._added_pos = np.concatenate([self._added_pos.reshape(-1, pos.shape[1]), new]) 

869 self._added_tags += [str(ks.tags[o]) for _, o in added] 

870 cell = np.concatenate([cell, [n for n, _ in added]]).astype(int) 

871 orb = np.concatenate([orb, [o for _, o in added]]).astype(int) 

872 on_lead = orb >= 0 

873 interface = np.flatnonzero(on_lead & (cell == edge)) 

874 bonded = np.flatnonzero(np.any(v != 0, axis=1)) # orbitals coupled to the next cell 

875 error_handling.lead_interface(sorted(set(bonded) - set(orb[interface]))) 

876 sites = interface[np.isin(orb[interface], bonded)] 

877 self.add_lead(h0, v, v[orb[sites]], [int(s) for s in sites], conservation_law) 

878 if extend: 

879 return self._ham.copy(), self._site_positions(sys) 

880 return None 

881 

882 def _site_positions(self, sys) -> NDArray[np.float64]: 

883 r''' 

884 Private method. The positions of the device sites: those of *sys*, 

885 then the sites added by *attach_lead* (*extend*). 

886 ''' 

887 pos = np.stack([sys.lat.coor[f] for f in ('x', 'y', 'z')[:sys.lat.space_dim]], axis=1) 

888 return np.concatenate([pos, self._added_pos.reshape(-1, pos.shape[1])]) 

889 

890 def _extend( 

891 self, h0: NDArray[np.complex128], v: NDArray[np.complex128], direction: int, 

892 cell: NDArray[np.int64], orb: NDArray[np.int64], edge: int, 

893 ) -> list[tuple[int, int]]: 

894 r''' 

895 Private method. Add to the device the lead sites missing between the 

896 lead and the device (see *attach_lead*): a flood fill from the lead's 

897 first cell (*edge* + *direction*) over the lead's hoppings, which 

898 stops at the device sites (*cell*, *orb*: their lead cell and 

899 orbital, -1 off the lead) and may not go past the device's innermost 

900 lead cell. Returns the added sites as (cell, orbital), in the order 

901 they are appended to the device. 

902 ''' 

903 norb = len(h0) 

904 present = {(int(n), int(o)): s for s, (n, o) in enumerate(zip(cell, orb)) if o >= 0} 

905 inner = np.min(direction * cell[orb >= 0]) 

906 hop = (h0 != 0) & ~np.eye(norb, dtype=bool) 

907 

908 def neighbours(n, o): 

909 return [(n, int(j)) for j in np.flatnonzero(hop[o] | hop[:, o])] \ 

910 + [(n + direction, int(j)) for j in np.flatnonzero(v[o])] \ 

911 + [(n - direction, int(i)) for i in np.flatnonzero(v[:, o])] 

912 

913 stack = [(int(edge) + direction, o) for o in range(norb)] 

914 seen = set(stack) 

915 added: list[tuple[int, int]] = [] 

916 while stack: 

917 for n, o in neighbours(*stack.pop()): 

918 if direction * n > direction * edge or (n, o) in seen: 

919 continue 

920 seen.add((n, o)) 

921 if (n, o) not in present: 

922 error_handling.lead_extension(direction * n >= inner) 

923 added.append((n, o)) 

924 stack.append((n, o)) 

925 n_dev = self._ham.shape[0] 

926 index = {**present, **{site: n_dev + k for k, site in enumerate(added)}} 

927 rows, cols, vals = [], [], [] 

928 for n, o in added: 

929 s = index[(n, o)] 

930 for m, p in [(n, o)] + neighbours(n, o): 

931 r = index.get((m, p)) 

932 if r is None: 

933 continue 

934 t = h0[o, p] if m == n else v[o, p] if m == n + direction else np.conj(v[p, o]) 

935 rows += [s] if r >= n_dev else [s, r] 

936 cols += [r] if r >= n_dev else [r, s] 

937 vals += [t] if r >= n_dev else [t, np.conj(t)] 

938 size = n_dev + len(added) 

939 self._ham = sp.csr_matrix( 

940 sp.block_diag([self._ham, sp.csr_matrix((len(added), len(added)))], format='csr') 

941 + sp.csr_matrix((vals, (rows, cols)), shape=(size, size)), dtype='c16') 

942 self._dense = None 

943 return added 

944 

945 def self_energy(self, lead: int, energy: float, eta: float = 1e-9) -> NDArray[np.complex128]: 

946 r''' 

947 Get the self-energy :math:`\Sigma = \tau g_s \tau^\dagger` of a lead, 

948 embedded in the device space. 

949 

950 Parameters 

951 ---------- 

952 lead : Integer 

953 Lead index (in the order of *add_lead*). 

954 energy : Real number 

955 eta : Positive real, default 1e-9 

956 

957 Returns 

958 ------- 

959 sigma : Complex ndarray, shape of *ham* 

960 ''' 

961 error_handling.lead_index(lead, len(self.leads)) 

962 h0, v, tau, sites = self.leads[lead] 

963 sigma = np.zeros_like(self.ham) 

964 sigma[np.ix_(sites, sites)] = tau @ surface_green(h0, v, energy, eta) @ tau.conj().T 

965 return sigma 

966 

967 def get_green(self, energy: float, eta: float = 1e-9) -> NDArray[np.complex128]: 

968 r''' 

969 Get the retarded Green's function of the device with all its leads, 

970 :math:`G^r = [E + i\eta - H - \sum_l \Sigma_l]^{-1}`, as a dense 

971 matrix (a dense inversion: the methods of this class never call it, 

972 and only factorize the sparse matrix). 

973 

974 Parameters 

975 ---------- 

976 energy : Real number 

977 eta : Positive real, default 1e-9 

978 

979 Returns 

980 ------- 

981 G : Complex ndarray, shape of *ham* 

982 ''' 

983 error_handling.real_number(energy, 'energy') 

984 error_handling.positive_real(eta, 'eta') 

985 sigma = sum((self.self_energy(l, energy, eta) for l in range(len(self.leads))), 

986 np.zeros_like(self.ham)) 

987 return LA.inv((energy + 1j * eta) * np.eye(len(self.ham)) - self.ham - sigma) 

988 

989 def transmission( 

990 self, energies: ArrayLike, lead_in: int = 0, lead_out: int = 1, eta: float | None = None, 

991 ) -> NDArray[np.float64]: 

992 r''' 

993 Get the transmission from lead *lead_in* to lead *lead_out*: the 

994 two-terminal conductance in units of :math:`e^2/h` (per spin, for a 

995 spinless model). 

996 

997 By default (*eta* None) it is :math:`\sum_{ab}|S_{ab}|^2` over the block of 

998 the scattering matrix (*smatrix*), exact up to the band edges of the 

999 leads. With a broadening *eta* (and, as a fallback, for non-Hermitian 

1000 leads or *lead_in* = *lead_out*, with *eta* = 1e-9) it is the Caroli 

1001 formula :math:`T(E) = \mathrm{Tr}[\Gamma_{out} G^r \Gamma_{in} G^a]`. 

1002 The two agree to :math:`O(\eta)`. 

1003 

1004 Parameters 

1005 ---------- 

1006 energies : Real array 

1007 Energies. 

1008 lead_in : Integer, default 0 

1009 lead_out : Integer, default 1 

1010 eta : Positive real or None, default None 

1011 

1012 Returns 

1013 ------- 

1014 T : Real ndarray, same length as *energies* 

1015 ''' 

1016 error_handling.lead_index(lead_in, len(self.leads)) 

1017 error_handling.lead_index(lead_out, len(self.leads)) 

1018 energies = np.atleast_1d(np.asarray(energies, dtype='f8')) 

1019 if self._exact(eta) and lead_in != lead_out: 

1020 return np.array(self._map(lambda e: np.sum(np.abs(self._amplitudes(e, lead_in, lead_out)) ** 2), 

1021 energies), dtype='f8') 

1022 eta = 1e-9 if eta is None else eta 

1023 s_in, s_out = self.leads[lead_in][3], self.leads[lead_out][3] 

1024 

1025 def caroli(e): 

1026 g, gam = self._green_columns(e, eta, s_in, s_out) 

1027 return np.trace(gam[lead_out] @ g @ gam[lead_in] @ g.conj().T).real 

1028 return np.array(self._map(caroli, energies), dtype='f8') 

1029 

1030 def _green_columns( 

1031 self, energy: float, eta: float, cols: ArrayLike, keep: ArrayLike | None = None, 

1032 ) -> tuple[NDArray[np.complex128], list[NDArray[np.complex128]]]: 

1033 r''' 

1034 Private method. The columns *cols* of the retarded Green's function, 

1035 :math:`G^r_{:,c} = [E + i\eta - H - \sum_l\Sigma_l]^{-1}e_c` (shape 

1036 (n_sites, len(cols)), or (len(keep), len(cols)) with only the sites 

1037 *keep*), from one sparse factorization (*_solve*): the 

1038 self-energies only fill the blocks of the lead sites. Also returns 

1039 the broadening :math:`\Gamma_l = i(\Sigma_l - \Sigma_l^\dagger)` of 

1040 every lead, restricted to its sites (shape (len(sites), len(sites))). 

1041 ''' 

1042 n = self._ham.shape[0] 

1043 mat = ((energy + 1j * eta) * sp.identity(n, dtype='c16', format='csr') - self._ham).tocoo() 

1044 rows, columns, data = [mat.row], [mat.col], [mat.data] 

1045 gam = [] 

1046 for h0, v, tau, sites in self.leads: 

1047 sig = tau @ surface_green(h0, v, energy, eta) @ tau.conj().T 

1048 gam.append(1j * (sig - sig.conj().T)) 

1049 rr, cc = np.meshgrid(sites, sites, indexing='ij') 

1050 rows.append(rr.ravel()) 

1051 columns.append(cc.ravel()) 

1052 data.append(-sig.ravel()) 

1053 # duplicate entries (a site shared by two leads) are summed 

1054 mat = sp.csc_matrix((np.concatenate(data), (np.concatenate(rows), np.concatenate(columns))), 

1055 shape=(n, n)) 

1056 cols = np.asarray(cols, dtype=int).ravel() 

1057 rhs = sp.csc_matrix((np.ones(len(cols), 'c16'), (cols, np.arange(len(cols)))), shape=(n, len(cols))) 

1058 return _solve(mat, rhs, None if keep is None else np.asarray(keep, dtype=int).ravel(), 

1059 self.solver, self._width()), gam 

1060 

1061 def _width(self) -> int: 

1062 r''' 

1063 Private method. The number of orbitals of the widest lead, the 

1064 cross-section by which the solver ``'auto'`` chooses (*_mumps_module*). 

1065 ''' 

1066 return max(len(h0) for h0, _, _, _ in self.leads) 

1067 

1068 # ------------------------------------------------------------------ 

1069 # Scattering matrix and scattering states 

1070 # ------------------------------------------------------------------ 

1071 

1072 def _exact(self, eta: float | None) -> bool: 

1073 r''' 

1074 Private method. Whether a method with a broadening *eta* uses the 

1075 scattering matrix and states (*eta* None and Hermitian leads) rather 

1076 than the Green's function (*_green_columns*). 

1077 ''' 

1078 return eta is None and all(np.allclose(h0, h0.conj().T) for h0, _, _, _ in self.leads) 

1079 

1080 def _amplitudes(self, energy: float, lead_in: int, lead_out: int) -> NDArray[np.complex128]: 

1081 r''' 

1082 Private method. The block of the scattering matrix from lead 

1083 *lead_in* to lead *lead_out*, from the modes injected by *lead_in* 

1084 only: shape (outgoing modes of *lead_out*, incoming modes of *lead_in*). 

1085 ''' 

1086 modes, sol = self._scattering(energy, [lead_in], slice(self._ham.shape[0], None)) 

1087 a = sum(len(h0) for h0, _, _, _ in self.leads[:lead_out]) 

1088 return sol[a:a + int(np.sum(modes[lead_out].velocities > 0))] 

1089 

1090 def _scattering(self, energy: float, inject: list[int], keep: slice = slice(None)) -> tuple: 

1091 r''' 

1092 Private method. Solve the scattering problem for every incoming mode 

1093 of the leads *inject* (Groth et al. 2014). In lead :math:`l`, the 

1094 wave function on cells 0 and 1 is the incoming mode plus 

1095 :math:`U_0 b_l`, :math:`U_1 b_l` (*_lead_modes*: outgoing and 

1096 evanescent). The unknowns are the device wave function 

1097 :math:`\psi` and the amplitudes :math:`b_l`, and the equations are 

1098 the Schrodinger equation on the device and on the surface cell of 

1099 every lead, 

1100 

1101 .. math:: 

1102 

1103 (E - H)\psi - \sum_l\tau_l U_{0,l}b_l = \sum_l\tau_l\phi^{in}_l\, ,\qquad 

1104 -\tau_l^\dagger\psi + [(E - h_0)U_0 - vU_1]b_l = -(E - h_0 - \lambda_{in}v)\phi^{in}_l\, , 

1105 

1106 one sparse system of size n_sites + sum_l m_l, factorized once 

1107 (*_solve*) for every right-hand side. Only the rows 

1108 *keep* of the solution are computed (e.g. the lead amplitudes for the 

1109 scattering matrix). 

1110 

1111 Returns 

1112 ------- 

1113 modes : List of **LeadModes**, one per lead 

1114 sol 

1115 Complex ndarray, shape (n_sites + sum_l m_l, n_in) before 

1116 *keep*: one column per incoming mode of the leads *inject*, in order. 

1117 ''' 

1118 error_handling.real_number(energy, 'energy') 

1119 n = self._ham.shape[0] 

1120 found = [_lead_modes(h0, v, energy, law) for (h0, v, _, _), law in zip(self.leads, self._laws)] 

1121 size = n + sum(len(h0) for h0, _, _, _ in self.leads) 

1122 device = (energy * sp.eye(n, dtype='c16') - self._ham).tocoo() 

1123 coo = ([device.row], [device.col], [device.data]) 

1124 rhs_coo: tuple = ([], [], []) 

1125 

1126 def block(r, c, values, out=coo): 

1127 rr, cc = np.meshgrid(r, c, indexing='ij') 

1128 out[0].append(rr.ravel()) 

1129 out[1].append(cc.ravel()) 

1130 out[2].append(values.ravel()) 

1131 

1132 n_rhs, a = 0, n 

1133 for l, ((h0, v, tau, sites), (modes, n_in, u0, u1)) in enumerate(zip(self.leads, found)): 

1134 m = len(h0) 

1135 lead = np.arange(a, a + m) 

1136 e_h0 = energy * np.eye(m) - h0 

1137 block(sites, lead, -tau @ u0) 

1138 block(lead, sites, -tau.conj().T) 

1139 block(lead, lead, e_h0 @ u0 - v @ u1) 

1140 if l in inject: 

1141 phi = modes.wave_functions[:, :n_in] 

1142 cols = np.arange(n_rhs, n_rhs + n_in) 

1143 block(sites, cols, tau @ phi, rhs_coo) 

1144 block(lead, cols, -(e_h0 @ phi - v @ phi * np.exp(1j * modes.momenta[:n_in])), rhs_coo) 

1145 n_rhs += n_in 

1146 a += m 

1147 if n_rhs == 0: 

1148 return [f[0] for f in found], np.zeros((size, 0), 'c16')[keep] 

1149 mat, rhs = (sp.csc_matrix((np.concatenate(x), (np.concatenate(r), np.concatenate(c))), shape=(size, s)) 

1150 for (r, c, x), s in ((coo, size), (rhs_coo, n_rhs))) 

1151 rows = None if keep == slice(None) else np.arange(size)[keep] 

1152 return [f[0] for f in found], _solve(mat, rhs, rows, self.solver, self._width()) 

1153 

1154 def smatrix(self, energy: float) -> SMatrix: 

1155 r''' 

1156 Get the scattering matrix at one energy: the amplitudes of the 

1157 outgoing modes of every lead for each incoming mode of unit 

1158 current, from the exact lead modes (*lead_modes*, no broadening) and 

1159 one sparse factorization of the device. It is unitary for a 

1160 Hermitian device. Every lead must be Hermitian. The blocks of the 

1161 leads' conservation laws (*add_lead*) are addressed as 

1162 ``(lead, block)`` in *SMatrix.submatrix* and *SMatrix.transmission*. 

1163 

1164 Parameters 

1165 ---------- 

1166 energy : Real number 

1167 Energy, not at a band edge of a lead. 

1168 

1169 Returns 

1170 ------- 

1171 S : **SMatrix**: *data*, *lead_info*, *submatrix*, *transmission* 

1172 

1173 Examples 

1174 -------- 

1175 Example usage:: 

1176 

1177 s = tr.smatrix(0.3) 

1178 t = s.submatrix(1, 0) # transmission amplitudes, lead 0 to lead 1 

1179 T = s.transmission(1, 0) # = tr.transmission(0.3, 0, 1) 

1180 ''' 

1181 modes, sol = self._scattering(energy, list(range(len(self.leads))), slice(self._ham.shape[0], None)) 

1182 rows, a = [], 0 

1183 for (h0, _, _, _), mode in zip(self.leads, modes): 

1184 rows.append(sol[a:a + int(np.sum(mode.velocities > 0))]) 

1185 a += len(h0) 

1186 data = np.vstack(rows) if rows else np.zeros((0, 0), 'c16') 

1187 return SMatrix(data, modes, [1 if law is None else len(law) for law in self._laws]) 

1188 

1189 def wave_function(self, energy: float, lead: int) -> NDArray[np.complex128]: 

1190 r''' 

1191 Get the scattering states injected from a lead: the wave function on 

1192 the device of each incoming mode of unit current (*lead_modes*), 

1193 with the scattered part leaving through every lead. 

1194 

1195 Parameters 

1196 ---------- 

1197 energy : Real number 

1198 Energy, not at a band edge of a lead. 

1199 lead : Integer 

1200 Injecting lead. 

1201 

1202 Returns 

1203 ------- 

1204 psi 

1205 Complex ndarray, shape (n_modes, n_sites): one row 

1206 per incoming mode of the lead. 

1207 ''' 

1208 error_handling.lead_index(lead, len(self.leads)) 

1209 _, sol = self._scattering(energy, [lead]) 

1210 return sol[:self._ham.shape[0]].T 

1211 

1212 def ldos(self, energy: float) -> NDArray[np.float64]: 

1213 r''' 

1214 Get the local density of states carried by the scattering states, 

1215 :math:`\rho_i(E) = \frac{1}{2\pi}\sum_{l,a}|\psi_{la}(i)|^2` over every 

1216 incoming mode :math:`a` of every lead :math:`l` (unit current 

1217 normalization). The bound states of the device, which no lead 

1218 feeds, are left out. 

1219 

1220 Parameters 

1221 ---------- 

1222 energy : Real number 

1223 Energy, not at a band edge of a lead. 

1224 

1225 Returns 

1226 ------- 

1227 rho : Real ndarray, shape (n_sites,) 

1228 ''' 

1229 _, sol = self._scattering(energy, list(range(len(self.leads)))) 

1230 return np.sum(np.abs(sol[:self._ham.shape[0]]) ** 2, axis=1) / (2 * np.pi) 

1231 

1232 # ------------------------------------------------------------------ 

1233 # Finite temperature: conductance and thermoelectric coefficients 

1234 # ------------------------------------------------------------------ 

1235 

1236 def _onsager( 

1237 self, mu: float, temperature: float, lead_in: int, lead_out: int, eta: float | None, 

1238 n_points: int, 

1239 ) -> tuple[float, float, float]: 

1240 r''' 

1241 Private method. The integrals :math:`L_n = \int dE\,(E - \mu)^n\,T(E) 

1242 (-\partial f/\partial E)`, n = 0, 1, 2. 

1243 ''' 

1244 energies, weights = _fermi_window(mu, temperature, n_points) 

1245 t = self.transmission(energies, lead_in, lead_out, eta) * weights 

1246 de = energies - mu 

1247 return float(t.sum()), float(np.sum(t * de)), float(np.sum(t * de**2)) 

1248 

1249 def conductance( 

1250 self, mu: float, temperature: float = 0., lead_in: int = 0, lead_out: int = 1, 

1251 eta: float | None = None, n_points: int = 101, 

1252 ) -> float: 

1253 r''' 

1254 Get the two-terminal linear conductance at a finite temperature, in 

1255 units of :math:`e^2/h`, 

1256 

1257 .. math:: 

1258 

1259 G = \int dE\,\left(-\frac{\partial f}{\partial E}\right)T(E)\, , 

1260 

1261 with the Fermi-Dirac :math:`f` at chemical potential :math:`\mu`. The 

1262 integral runs over :math:`|E - \mu| \le 36k_BT` on *n_points* equally 

1263 spaced energies (the trapezoidal rule, spectrally accurate for 

1264 a smooth :math:`T(E)`). Resolving features of :math:`T(E)` narrower than 

1265 :math:`k_BT` needs more points. At zero temperature it is :math:`T(\mu)`. 

1266 

1267 Parameters 

1268 ---------- 

1269 mu : Real number 

1270 Chemical potential. 

1271 temperature : Positive real or zero 

1272 Default value 0 (:math:`k_B = 1`). 

1273 lead_in : Integer, default 0 

1274 lead_out : Integer, default 1 

1275 eta : Positive real or None 

1276 Default value None (see *transmission*). 

1277 n_points : Positive integer, default 101 

1278 

1279 Returns 

1280 ------- 

1281 G : Real number 

1282 ''' 

1283 error_handling.real_number(mu, 'mu') 

1284 error_handling.positive_real_zero(temperature, 'temperature') 

1285 error_handling.positive_int(n_points, 'n_points') 

1286 if temperature == 0: 

1287 return float(self.transmission([mu], lead_in, lead_out, eta)[0]) 

1288 return self._onsager(mu, temperature, lead_in, lead_out, eta, n_points)[0] 

1289 

1290 def thermoelectric( 

1291 self, mu: float, temperature: float, lead_in: int = 0, lead_out: int = 1, 

1292 eta: float | None = None, n_points: int = 101, 

1293 ) -> tuple[float, float, float]: 

1294 r''' 

1295 Get the two-terminal thermoelectric coefficients in linear response 

1296 (Sivan and Imry 1986), from :math:`L_n = \int dE\,(E - \mu)^n\,T(E) 

1297 (-\partial f/\partial E)`: 

1298 

1299 .. math:: 

1300 

1301 G = L_0\, ,\qquad S = -\frac{L_1}{T L_0}\, ,\qquad 

1302 \kappa = \frac{1}{T}\left(L_2 - \frac{L_1^2}{L_0}\right)\, , 

1303 

1304 the conductance (:math:`e^2/h`), the thermopower (:math:`k_B/e`, for 

1305 electrons of charge :math:`-e`) and the electronic thermal conductance 

1306 at zero current (:math:`k_B/h` times the energy unit). At low 

1307 temperature they obey the Mott formula 

1308 :math:`S = -\frac{\pi^2}{3}T\,\frac{d\ln T(E)}{dE}` and the 

1309 Wiedemann-Franz law :math:`\kappa = \frac{\pi^2}{3}TG`. The integrals 

1310 are those of *conductance*. 

1311 

1312 Parameters 

1313 ---------- 

1314 mu : Real number 

1315 Chemical potential. 

1316 temperature : Positive real (:math:`k_B = 1`) 

1317 lead_in : Integer, default 0 

1318 lead_out : Integer, default 1 

1319 eta : Positive real or None 

1320 Default value None (see *transmission*). 

1321 n_points : Positive integer, default 101 

1322 

1323 Returns 

1324 ------- 

1325 G : Real number 

1326 S : Real number (NaN when nothing is transmitted) 

1327 kappa : Real number 

1328 ''' 

1329 error_handling.real_number(mu, 'mu') 

1330 error_handling.positive_real(temperature, 'temperature') 

1331 error_handling.positive_int(n_points, 'n_points') 

1332 l0, l1, l2 = self._onsager(mu, temperature, lead_in, lead_out, eta, n_points) 

1333 if l0 < 1e-14: 

1334 return l0, np.nan, l2 / temperature 

1335 return l0, -l1 / (temperature * l0), (l2 - l1**2 / l0) / temperature 

1336 

1337 # ------------------------------------------------------------------ 

1338 # Multi-terminal conductance, currents and noise 

1339 # ------------------------------------------------------------------ 

1340 

1341 def transmission_matrix(self, energy: float, eta: float | None = None) -> NDArray[np.float64]: 

1342 r''' 

1343 Get the transmissions :math:`T_{pq}` between every pair of leads at 

1344 one energy, from lead :math:`q` to lead :math:`p` (the diagonal, a 

1345 reflection, is set to 0). By default (*eta* None) they come from one 

1346 scattering matrix (*smatrix*), :math:`T_{pq} = \sum_{ab}|S_{ab}|^2` 

1347 over its block from :math:`q` to :math:`p`; with a broadening *eta*, 

1348 from the Caroli formula :math:`\mathrm{Tr}[\Gamma_pG^r\Gamma_qG^a]` 

1349 (see *transmission*). 

1350 

1351 Parameters 

1352 ---------- 

1353 energy : Real number 

1354 eta : Positive real or None, default None 

1355 

1356 Returns 

1357 ------- 

1358 T : Real ndarray, shape (n_leads, n_leads) 

1359 ''' 

1360 n = len(self.leads) 

1361 if self._exact(eta): 

1362 s = self.smatrix(energy) 

1363 return np.array([[s.transmission(p, q) if p != q else 0. for q in range(n)] for p in range(n)]) 

1364 eta = 1e-9 if eta is None else eta 

1365 lead_sites = np.unique(np.concatenate([np.asarray(sites, dtype=int).ravel() 

1366 for _, _, _, sites in self.leads])) 

1367 g, gam = self._green_columns(energy, eta, lead_sites, lead_sites) 

1368 at = [np.searchsorted(lead_sites, sites) for _, _, _, sites in self.leads] 

1369 out = np.zeros((n, n)) 

1370 for p in range(n): 

1371 for q in range(n): 

1372 if p != q: 

1373 gpq = g[np.ix_(at[p], at[q])] 

1374 out[p, q] = np.trace(gam[p] @ gpq @ gam[q] @ gpq.conj().T).real 

1375 return out 

1376 

1377 def conductance_matrix( 

1378 self, energy: float, eta: float | None = None, temperature: float = 0., n_points: int = 101, 

1379 ) -> NDArray[np.float64]: 

1380 r''' 

1381 Get the Landauer-Buttiker conductance matrix (Buttiker 1986), in units 

1382 of :math:`e^2/h`: the linear-response currents flowing *into* the 

1383 device from each lead, :math:`I_p = \sum_q G_{pq}V_q`, with 

1384 

1385 .. math:: 

1386 

1387 G_{pq} = -T_{pq}\ (p\neq q)\, ,\qquad G_{pp} = \sum_{q\neq p}T_{qp}\, . 

1388 

1389 Its rows and columns add up to zero (current conservation, and no 

1390 current at equal voltages). At a finite *temperature* it is averaged 

1391 over the Fermi window, :math:`\int dE\,(-\partial f/\partial E)\,G(E)` 

1392 (see *conductance*). The transmissions come from *transmission_matrix*. 

1393 

1394 Parameters 

1395 ---------- 

1396 energy : Real number 

1397 Fermi energy (chemical potential). 

1398 eta : Positive real or None, default None 

1399 See *transmission_matrix*. 

1400 temperature : Positive real or zero 

1401 Default value 0 (:math:`k_B = 1`). 

1402 n_points : Positive integer, default 101 

1403 Energies in the 

1404 Fermi window, at a finite temperature. 

1405 

1406 Returns 

1407 ------- 

1408 G : Real ndarray, shape (n_leads, n_leads) 

1409 ''' 

1410 error_handling.positive_real_zero(temperature, 'temperature') 

1411 error_handling.positive_int(n_points, 'n_points') 

1412 if temperature > 0: 

1413 energies, weights = _fermi_window(energy, temperature, n_points) 

1414 return sum(w * g for g, w in zip(self._map(lambda e: self.conductance_matrix(e, eta), energies), 

1415 weights)) 

1416 t = self.transmission_matrix(energy, eta) 

1417 return np.diag(t.sum(axis=0)) - t 

1418 

1419 def four_terminal_resistance( 

1420 self, energy: float, current: tuple[int, int], voltage: tuple[int, int], eta: float | None = None, 

1421 temperature: float = 0., n_points: int = 101, 

1422 ) -> float: 

1423 r''' 

1424 Get a four-terminal (or two-terminal) resistance from the 

1425 Landauer-Buttiker equations: a current :math:`I` enters through lead 

1426 ``current[0]`` and leaves through ``current[1]``, every other lead is 

1427 an ideal voltage probe (no net current), and the result is 

1428 :math:`R = (V_a - V_b)/I` with ``voltage = (a, b)``, in units of 

1429 :math:`h/e^2`. On a Hall bar, a longitudinal pair gives 

1430 :math:`R_{xx}` and a transverse pair :math:`R_{xy}`; in the quantum 

1431 Hall regime with :math:`\nu` edge channels, :math:`|R_{xy}| = 1/\nu` 

1432 and :math:`R_{xx} = 0` (Buttiker 1988). 

1433 

1434 Parameters 

1435 ---------- 

1436 energy : Real number 

1437 Fermi energy. 

1438 current : Tuple of two distinct lead indices (source, drain) 

1439 voltage : Tuple of two lead indices (a, b) 

1440 eta : Positive real or None, default None 

1441 See *transmission_matrix*. 

1442 temperature : Positive real or zero 

1443 Default value 0 (see *conductance_matrix*). 

1444 n_points : Positive integer, default 101 

1445 

1446 Returns 

1447 ------- 

1448 R : Real number 

1449 ''' 

1450 error_handling.lead_pair(current, len(self.leads), 'current', True) 

1451 error_handling.lead_pair(voltage, len(self.leads), 'voltage', False) 

1452 g = self.conductance_matrix(energy, eta, temperature, n_points) 

1453 source, drain = current 

1454 keep = [p for p in range(len(self.leads)) if p != drain] # the drain is grounded 

1455 currents = np.zeros(len(keep)) 

1456 currents[keep.index(source)] = 1. 

1457 volts = np.zeros(len(self.leads)) 

1458 volts[keep] = LA.solve(g[np.ix_(keep, keep)], currents) 

1459 return float(volts[voltage[0]] - volts[voltage[1]]) 

1460 

1461 def _bond_list( 

1462 self, energy: float, lead: int, eta: float | None, 

1463 ) -> tuple[NDArray[np.int64], NDArray[np.int64], NDArray[np.float64]]: 

1464 r''' 

1465 Private method. The bond currents of *bond_currents* on the bonds 

1466 :math:`i \neq j` of the device (the nonzero :math:`H_{ij}`): rows, 

1467 columns and currents. By default :math:`A^{(q)}_{ji}` comes from the 

1468 scattering states, otherwise from the Green's function columns of 

1469 the lead (*_green_columns*). 

1470 ''' 

1471 error_handling.lead_index(lead, len(self.leads)) 

1472 h = self._ham.tocoo() 

1473 bond = h.row != h.col 

1474 rows, cols, hij = h.row[bond], h.col[bond], h.data[bond] 

1475 if self._exact(eta): 

1476 psi = self.wave_function(energy, lead) 

1477 a_ji = np.sum(psi[:, cols] * psi[:, rows].conj(), axis=0) 

1478 else: 

1479 eta = 1e-9 if eta is None else eta 

1480 g, gam = self._green_columns(energy, eta, self.leads[lead][3]) 

1481 a_ji = np.sum((g[cols] @ gam[lead]) * g[rows].conj(), axis=1) 

1482 return rows, cols, -2 * np.imag(hij * a_ji) 

1483 

1484 def bond_currents(self, energy: float, lead: int, eta: float | None = None) -> NDArray[np.float64]: 

1485 r''' 

1486 Get the bond currents carried, per unit energy, by the electrons 

1487 injected from one lead (the non-equilibrium current when that lead's 

1488 electrochemical potential is raised), 

1489 

1490 .. math:: 

1491 

1492 J_{i\to j} = -2\,\mathrm{Im}\left[H_{ij}\,A^{(q)}_{ji}\right]\, ,\qquad 

1493 A^{(q)} = G^r\Gamma_qG^a = \sum_a\psi_a\psi_a^\dagger\, , 

1494 

1495 in units of :math:`e/h` per unit energy: summed over a cross-section 

1496 of a two-terminal device, it is the transmission :math:`T(E)`. The 

1497 matrix is antisymmetric, and the currents are conserved at every 

1498 site not touched by a lead. By default (*eta* None) :math:`A^{(q)}` 

1499 comes from the scattering states :math:`\psi_a` of the lead 

1500 (*wave_function*, unit current), on the bonds of the sparse device 

1501 only; with a broadening *eta*, from the columns of :math:`G^r` on the 

1502 lead's sites (one sparse factorization). 

1503 

1504 Parameters 

1505 ---------- 

1506 energy : Real number 

1507 lead : Integer 

1508 Injecting lead. 

1509 eta : Positive real or None, default None 

1510 

1511 Returns 

1512 ------- 

1513 J 

1514 Real ndarray, shape of *ham*: J[i, j] is the current 

1515 from site i to site j. 

1516 ''' 

1517 rows, cols, j = self._bond_list(energy, lead, eta) 

1518 n = self._ham.shape[0] 

1519 return sp.csr_matrix((j, (rows, cols)), shape=(n, n)).toarray() 

1520 

1521 def local_currents( 

1522 self, energy: float, lead: int, positions: ArrayLike, eta: float | None = None, 

1523 ) -> NDArray[np.float64]: 

1524 r''' 

1525 Get the current density vector on every site from the bond currents 

1526 (*bond_currents*): half of the currents of the bonds leaving the 

1527 site, along their bond vectors, 

1528 :math:`\mathbf{j}_i = \frac12\sum_jJ_{i\to j}(\mathbf{r}_j - \mathbf{r}_i)`. 

1529 It never builds a dense matrix of the device. 

1530 

1531 Parameters 

1532 ---------- 

1533 energy : Real number 

1534 lead : Integer 

1535 Injecting lead. 

1536 positions : Real array, shape (n_sites, d) 

1537 Site positions 

1538 (e.g. ``np.column_stack([lat.coor['x'], lat.coor['y']])``). 

1539 eta : Positive real or None, default None 

1540 

1541 Returns 

1542 ------- 

1543 j : Real ndarray, shape (n_sites, d) 

1544 ''' 

1545 positions = np.asarray(positions, dtype='f8') 

1546 error_handling.site_positions(positions, self._ham.shape[0]) 

1547 rows, cols, bonds = self._bond_list(energy, lead, eta) 

1548 out = np.zeros_like(positions) 

1549 np.add.at(out, rows, 0.5 * bonds[:, None] * (positions[cols] - positions[rows])) 

1550 return out 

1551 

1552 def transmission_eigenvalues( 

1553 self, energy: float, lead_in: int = 0, lead_out: int = 1, eta: float | None = None, 

1554 ) -> NDArray[np.float64]: 

1555 r''' 

1556 Get the transmission eigenvalues :math:`T_n`, eigenvalues of 

1557 :math:`t^\dagger t`: their sum is the transmission. By default (*eta* 

1558 None) :math:`t` is the block of the scattering matrix from 

1559 *lead_in* to *lead_out* (*smatrix*), and the list is padded with the 

1560 zeros of the closed channels; with a broadening *eta* it is 

1561 :math:`t = \Gamma_{out}^{1/2}G^r\Gamma_{in}^{1/2}` (and, as a 

1562 fallback, with *eta* = 1e-9 for *lead_in* = *lead_out*). 

1563 

1564 Parameters 

1565 ---------- 

1566 energy : Real number 

1567 lead_in : Integer, default 0 

1568 lead_out : Integer, default 1 

1569 eta : Positive real or None, default None 

1570 

1571 Returns 

1572 ------- 

1573 T_n 

1574 Real ndarray, in decreasing order, of length 

1575 min(len(sites_in), len(sites_out)). 

1576 ''' 

1577 error_handling.lead_index(lead_in, len(self.leads)) 

1578 error_handling.lead_index(lead_out, len(self.leads)) 

1579 s_in, s_out = self.leads[lead_in][3], self.leads[lead_out][3] 

1580 if self._exact(eta) and lead_in != lead_out: 

1581 t = self._amplitudes(energy, lead_in, lead_out) 

1582 vals = np.linalg.svd(t, compute_uv=False) ** 2 if t.size else np.zeros(0) 

1583 # at most min(len(s_in), len(s_out)) channels transmit: the others are zeros 

1584 out = np.zeros(min(len(s_in), len(s_out))) 

1585 out[:min(len(out), len(vals))] = vals[:len(out)] 

1586 return out 

1587 eta = 1e-9 if eta is None else eta 

1588 g, gam = self._green_columns(energy, eta, s_in, s_out) 

1589 return _eigen_transmissions(gam[lead_out], g, gam[lead_in]) 

1590 

1591 def shot_noise( 

1592 self, energies: ArrayLike, lead_in: int = 0, lead_out: int = 1, eta: float | None = None, 

1593 ) -> NDArray[np.float64]: 

1594 r''' 

1595 Get the zero-temperature shot-noise factor :math:`\sum_nT_n(1-T_n)` 

1596 (Lesovik 1989; Buttiker 1990): the noise power at bias :math:`V` is 

1597 :math:`S = 2\frac{e^3|V|}{h}\sum_nT_n(1-T_n)` (per spin). 

1598 

1599 Parameters 

1600 ---------- 

1601 energies : Real array 

1602 Energies. 

1603 lead_in : Integer, default 0 

1604 lead_out : Integer, default 1 

1605 eta : Positive real or None, default None 

1606 See *transmission_eigenvalues*. 

1607 

1608 Returns 

1609 ------- 

1610 noise : Real ndarray, same length as *energies* 

1611 ''' 

1612 error_handling.frequencies(energies, 'energies') 

1613 energies = np.atleast_1d(np.asarray(energies, dtype='f8')) 

1614 return np.array(self._map(lambda e: _noise(self.transmission_eigenvalues(e, lead_in, lead_out, eta)), 

1615 energies), dtype='f8') 

1616 

1617 def fano_factor( 

1618 self, energies: ArrayLike, lead_in: int = 0, lead_out: int = 1, eta: float | None = None, 

1619 ) -> NDArray[np.float64]: 

1620 r''' 

1621 Get the Fano factor of the zero-temperature shot noise, 

1622 

1623 .. math:: 

1624 

1625 F = \frac{\sum_nT_n(1-T_n)}{\sum_nT_n}\, , 

1626 

1627 the noise in units of the Poisson value :math:`2e|I|`: 0 for a 

1628 ballistic conductor (every :math:`T_n` is 0 or 1), close to 1 for a 

1629 tunnel barrier, 1/3 for a diffusive wire (Beenakker and Buttiker 1992). 

1630 

1631 Parameters 

1632 ---------- 

1633 energies : Real array 

1634 Energies. 

1635 lead_in : Integer, default 0 

1636 lead_out : Integer, default 1 

1637 eta : Positive real or None, default None 

1638 See *transmission_eigenvalues*. 

1639 

1640 Returns 

1641 ------- 

1642 F 

1643 Real ndarray, same length as *energies* (NaN where 

1644 nothing is transmitted). 

1645 ''' 

1646 error_handling.frequencies(energies, 'energies') 

1647 energies = np.atleast_1d(np.asarray(energies, dtype='f8')) 

1648 return np.array(self._map(lambda e: _fano(self.transmission_eigenvalues(e, lead_in, lead_out, eta)), 

1649 energies), dtype='f8') 

1650 

1651 

1652def _fermi_window( 

1653 mu: float, temperature: float, n_points: int, 

1654) -> tuple[NDArray[np.float64], NDArray[np.float64]]: 

1655 r''' 

1656 Private function. Energies and weights of the trapezoidal rule for 

1657 :math:`\int dE\,(-\partial f/\partial E)\,F(E)`, on *n_points* equally 

1658 spaced energies with :math:`|E - \mu| \le 36T` (the weight is below 

1659 1e-15 beyond). The weights add up to 1. 

1660 ''' 

1661 x = np.linspace(-36., 36., n_points) if n_points > 1 else np.zeros(1) 

1662 w = 1 / (4 * np.cosh(x / 2) ** 2) 

1663 return mu + temperature * x, w / w.sum() 

1664 

1665 

1666def _sqrt_psd(mat: NDArray[np.complex128]) -> NDArray[np.complex128]: 

1667 ''' 

1668 Private function. Square root of a positive semi-definite Hermitian matrix. 

1669 ''' 

1670 w, u = np.linalg.eigh(0.5 * (mat + mat.conj().T)) 

1671 return (u * np.sqrt(np.clip(w, 0., None))) @ u.conj().T 

1672 

1673 

1674def _eigen_transmissions( 

1675 gam_out: NDArray[np.complex128], g: NDArray[np.complex128], gam_in: NDArray[np.complex128], 

1676) -> NDArray[np.float64]: 

1677 r''' 

1678 Private function. Transmission eigenvalues: the squared singular values 

1679 of :math:`\Gamma_{out}^{1/2}G\,\Gamma_{in}^{1/2}` (*g* the block of the 

1680 Green's function from the input to the output sites). 

1681 ''' 

1682 t = _sqrt_psd(gam_out) @ g @ _sqrt_psd(gam_in) 

1683 return np.linalg.svd(t, compute_uv=False) ** 2 

1684 

1685 

1686def _noise(t: NDArray[np.float64]) -> float: 

1687 ''' 

1688 Private function. Shot-noise factor sum T_n (1 - T_n). 

1689 ''' 

1690 return float(np.sum(t * (1 - t))) 

1691 

1692 

1693def _fano(t: NDArray[np.float64]) -> float: 

1694 ''' 

1695 Private function. Fano factor from transmission eigenvalues (NaN if none transmit). 

1696 ''' 

1697 total = t.sum() 

1698 return _noise(t) / float(total) if total > 1e-12 else np.nan 

1699 

1700 

1701def slices_from_positions(x: ArrayLike, tol: float = 1e-6) -> list[list[int]]: 

1702 r''' 

1703 Group the sites of a device into slices of equal coordinate *x* (e.g. 

1704 the columns of a strip along :math:`x`), ordered by increasing *x*, for 

1705 *RecursiveTransport*. 

1706 

1707 Parameters 

1708 ---------- 

1709 x : Real array 

1710 One coordinate per site (e.g. ``lat.coor['x']``). 

1711 tol : Positive real, default 1e-6 

1712 Coordinates closer than 

1713 *tol* belong to the same slice. 

1714 

1715 Returns 

1716 ------- 

1717 slices : List of lists of site indices 

1718 ''' 

1719 x = np.asarray(x, dtype='f8').ravel() 

1720 error_handling.ndarray_empty(x, 'x') 

1721 error_handling.positive_real(tol, 'tol') 

1722 order = np.argsort(x, kind='stable') 

1723 breaks = np.flatnonzero(np.diff(x[order]) > tol) + 1 

1724 return [sorted(s.tolist()) for s in np.split(order, breaks)] 

1725 

1726 

1727class RecursiveTransport(_EnergyWorkers): 

1728 r''' 

1729 Two-terminal transport through a long quasi-1D device by the recursive 

1730 Green's function method (Thouless and Kirkpatrick 1981; Lee and Fisher 

1731 1981; MacKinnon 1985). The device is cut into slices :math:`1\dots N`, 

1732 each coupled only to its neighbours, with the left lead on slice 1 and 

1733 the right lead on slice :math:`N`. The left-connected Green's functions 

1734 

1735 .. math:: 

1736 

1737 g_1 = [z - H_{11} - \Sigma_L]^{-1}\, ,\qquad 

1738 g_{i} = [z - H_{ii} - H_{i,i-1}\,g_{i-1}H_{i-1,i}]^{-1}\, , 

1739 

1740 (:math:`\Sigma_R` added in the last one, :math:`z = E + i\eta`) and the 

1741 propagator :math:`G_{i1} = g_iH_{i,i-1}G_{i-1,1}` give 

1742 :math:`T = \mathrm{Tr}[\Gamma_RG_{N1}\Gamma_LG_{N1}^\dagger]`. The cost 

1743 grows linearly with the length, and only slice-sized matrices are 

1744 inverted, never the whole device (compare *Transport*, which inverts 

1745 the dense device matrix). 

1746 

1747 Parameters 

1748 ---------- 

1749 ham : Square matrix, sparse (preferred for long devices) or dense 

1750 Device Hamiltonian. 

1751 slices 

1752 List of lists of site indices: a partition of the device 

1753 into slices, ordered from the left lead to the right one, with 

1754 hoppings between neighbouring slices only (see *slices_from_positions*). 

1755 left 

1756 Tuple (h0, v, coupling): the left lead (see *Transport.add_lead*), 

1757 with a coupling of shape (len(slices[0]), len(h0)), its rows in the 

1758 order of ``slices[0]``. 

1759 right : Tuple (h0, v, coupling): the right lead, coupled to ``slices[-1]`` 

1760 

1761 Examples 

1762 -------- 

1763 Example usage:: 

1764 

1765 slices = slices_from_positions(lat.coor['x']) 

1766 rgf = RecursiveTransport(sys.ham, slices, (h0, v_left, tau), (h0, v_right, tau)) 

1767 T = rgf.transmission(energies) 

1768 ''' 

1769 

1770 def __init__(self, ham, slices: list[list[int]], left: tuple, right: tuple) -> None: 

1771 ham = sp.csr_matrix(ham, dtype='c16') 

1772 error_handling.square_matrix(ham, 'ham') 

1773 error_handling.slices(slices, ham.shape[0]) 

1774 label = np.empty(ham.shape[0], dtype=int) 

1775 pos = np.empty(ham.shape[0], dtype=int) 

1776 for n, s in enumerate(slices): 

1777 label[s] = n 

1778 pos[s] = np.arange(len(s)) 

1779 coo = ham.tocoo() 

1780 coo.sum_duplicates() 

1781 lr, lc = label[coo.row], label[coo.col] 

1782 error_handling.block_tridiagonal(int(np.abs(lr - lc).max(initial=0))) 

1783 self.slices = [list(s) for s in slices] 

1784 sizes = [len(s) for s in self.slices] 

1785 self.blocks = [np.zeros((m, m), 'c16') for m in sizes] 

1786 self.couplings = [np.zeros((m, k), 'c16') for m, k in zip(sizes[:-1], sizes[1:])] 

1787 # scatter every nonzero entry into its block (lc == lr) or coupling 

1788 # (lc == lr + 1), grouped by slice; the lower couplings are their adjoints 

1789 for target, keep in ((self.blocks, lr == lc), (self.couplings, lc == lr + 1)): 

1790 order = np.argsort(lr[keep], kind='stable') 

1791 rows, cols = pos[coo.row[keep]][order], pos[coo.col[keep]][order] 

1792 vals, owner = coo.data[keep][order], lr[keep][order] 

1793 bounds = np.searchsorted(owner, np.arange(len(target) + 1)) 

1794 for n, mat in enumerate(target): 

1795 a, b = bounds[n], bounds[n + 1] 

1796 mat[rows[a:b], cols[a:b]] = vals[a:b] 

1797 self.leads = [] 

1798 for lead, s in ((left, self.slices[0]), (right, self.slices[-1])): 

1799 error_handling.lead_tuple(lead) 

1800 h0 = np.atleast_2d(np.asarray(lead[0], dtype='c16')) 

1801 v = np.atleast_2d(np.asarray(lead[1], dtype='c16')) 

1802 error_handling.lead(h0, v) 

1803 tau = np.atleast_2d(np.asarray(lead[2], dtype='c16')) 

1804 error_handling.lead_coupling(tau, list(range(len(s))), len(h0), len(s)) 

1805 self.leads.append((h0, v, tau)) 

1806 

1807 def _propagator(self, energy: float, eta: float) -> tuple: 

1808 r''' 

1809 Private method. :math:`G_{N1}` and the broadenings of the two leads. 

1810 ''' 

1811 sig = [tau @ surface_green(h0, v, energy, eta) @ tau.conj().T for h0, v, tau in self.leads] 

1812 gam = [1j * (s - s.conj().T) for s in sig] 

1813 z = energy + 1j * eta 

1814 last = len(self.blocks) - 1 

1815 g = g_n1 = None 

1816 for i, h in enumerate(self.blocks): 

1817 a = z * np.eye(len(h)) - h 

1818 if i == 0: 

1819 a = a - sig[0] 

1820 else: 

1821 v = self.couplings[i - 1] 

1822 a = a - v.conj().T @ g @ v 

1823 if i == last: 

1824 a = a - sig[1] 

1825 g = LA.inv(a) 

1826 g_n1 = g if i == 0 else g @ self.couplings[i - 1].conj().T @ g_n1 

1827 return g_n1, gam 

1828 

1829 def transmission(self, energies: ArrayLike, eta: float = 1e-9) -> NDArray[np.float64]: 

1830 r''' 

1831 Get the transmission from the left lead to the right one: the same 

1832 as *Transport.transmission* for the same device and leads. 

1833 

1834 Parameters 

1835 ---------- 

1836 energies : Real array 

1837 Energies. 

1838 eta : Positive real, default 1e-9 

1839 

1840 Returns 

1841 ------- 

1842 T : Real ndarray, same length as *energies* 

1843 ''' 

1844 error_handling.frequencies(energies, 'energies') 

1845 energies = np.atleast_1d(np.asarray(energies, dtype='f8')) 

1846 error_handling.positive_real(eta, 'eta') 

1847 

1848 def caroli(e): 

1849 g, (gam_l, gam_r) = self._propagator(e, eta) 

1850 return np.trace(gam_r @ g @ gam_l @ g.conj().T).real 

1851 return np.array(self._map(caroli, energies), dtype='f8') 

1852 

1853 def transmission_eigenvalues(self, energy: float, eta: float = 1e-9) -> NDArray[np.float64]: 

1854 r''' 

1855 Get the transmission eigenvalues (see *Transport.transmission_eigenvalues*). 

1856 

1857 Parameters 

1858 ---------- 

1859 energy : Real number 

1860 eta : Positive real, default 1e-9 

1861 

1862 Returns 

1863 ------- 

1864 T_n : Real ndarray, in decreasing order 

1865 ''' 

1866 error_handling.real_number(energy, 'energy') 

1867 error_handling.positive_real(eta, 'eta') 

1868 g, (gam_l, gam_r) = self._propagator(energy, eta) 

1869 return _eigen_transmissions(gam_r, g, gam_l) 

1870 

1871 def fano_factor(self, energies: ArrayLike, eta: float = 1e-9) -> NDArray[np.float64]: 

1872 r''' 

1873 Get the Fano factor of the shot noise (see *Transport.fano_factor*). 

1874 

1875 Parameters 

1876 ---------- 

1877 energies : Real array 

1878 Energies. 

1879 eta : Positive real, default 1e-9 

1880 

1881 Returns 

1882 ------- 

1883 F : Real ndarray, same length as *energies* 

1884 ''' 

1885 error_handling.frequencies(energies, 'energies') 

1886 energies = np.atleast_1d(np.asarray(energies, dtype='f8')) 

1887 return np.array(self._map(lambda e: _fano(self.transmission_eigenvalues(e, eta)), energies), dtype='f8')