Coverage for tbkit/kpm.py: 100%

369 statements  

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

1r""" 

2The kernel polynomial method (KPM; Silver and Roder 1994, Weisse, 

3Wellein, Alvermann and Fehske, Rev. Mod. Phys. 78, 275 (2006)): spectral 

4quantities of a large sparse Hamiltonian from its Chebyshev moments, 

5without diagonalizing it. The spectrum is first mapped into 

6:math:`(-1, 1)`, :math:`\tilde H = (H - b)/a`; then 

7 

8.. math:: 

9 

10 \delta(E - H) = \sum_{m=0}^{M-1} c_m(E)\, T_m(\tilde H)\, ,\qquad 

11 c_m(E) = \frac{(2-\delta_{m0})\,g_m\,T_m(\epsilon)}{a\pi\sqrt{1-\epsilon^2}}\, , 

12 

13with :math:`\epsilon = (E-b)/a`, :math:`T_m` the Chebyshev polynomials 

14(computed by the recursion :math:`T_{m+1}(\tilde H)|r\rangle = 

152\tilde H\,T_m(\tilde H)|r\rangle - T_{m-1}(\tilde H)|r\rangle`, one sparse 

16matrix-vector product each), and :math:`g_m` a kernel that damps the Gibbs 

17oscillations of the truncated series (Jackson: an almost Gaussian 

18broadening of width about :math:`\pi a/M`). Traces are estimated with a 

19few random-phase vectors, :math:`\mathrm{Tr}\,A \approx 

20\frac1R\sum_r\langle r|A|r\rangle`, whose error falls as :math:`1/\sqrt{RN}`: 

21the cost is :math:`O(MRN)` for :math:`N` sites, so millions of sites are 

22within reach. 

23 

24The Hamiltonian must be Hermitian (*System.ham*, a sparse matrix). 

25""" 

26from __future__ import annotations 

27 

28import numpy as np 

29from numpy.typing import ArrayLike, NDArray 

30import scipy.sparse as sparse 

31from scipy.integrate import trapezoid 

32from scipy.special import jv 

33 

34import tbkit.error_handling as error_handling 

35import tbkit.occupation as occupation 

36 

37 

38PI = np.pi 

39 

40 

41def spectral_bounds(ham) -> tuple[float, float]: 

42 r''' 

43 Get bounds on the spectrum of a Hermitian matrix from Gershgorin's 

44 circle theorem: every eigenvalue lies within 

45 :math:`H_{ii} \pm \sum_{j\neq i}|H_{ij}|` for some :math:`i`. 

46 

47 Parameters 

48 ---------- 

49 ham : Square sparse (or dense) Hermitian matrix 

50 

51 Returns 

52 ------- 

53 e_min, e_max : Real numbers 

54 ''' 

55 ham = sparse.csr_matrix(ham) 

56 diag = ham.diagonal().real 

57 radii = np.asarray(abs(ham).sum(axis=1)).ravel() - np.abs(ham.diagonal()) 

58 return float(np.min(diag - radii)), float(np.max(diag + radii)) 

59 

60 

61def jackson_kernel(n_moments: int) -> NDArray[np.float64]: 

62 r''' 

63 Get the Jackson kernel 

64 

65 .. math:: 

66 

67 g_m = \frac{(M-m+1)\cos\frac{\pi m}{M+1} 

68 + \sin\frac{\pi m}{M+1}\cot\frac{\pi}{M+1}}{M+1}\, , 

69 

70 the optimal choice for spectral densities (positive, and resolution 

71 about :math:`\pi/M` in the scaled energy). 

72 

73 Parameters 

74 ---------- 

75 n_moments : Positive integer :math:`M` 

76 

77 Returns 

78 ------- 

79 g : Real ndarray, shape (n_moments,) 

80 ''' 

81 error_handling.positive_int(n_moments, 'n_moments') 

82 m = np.arange(n_moments) 

83 q = PI / (n_moments + 1) 

84 return ((n_moments - m + 1) * np.cos(q * m) + np.sin(q * m) / np.tan(q)) / (n_moments + 1) 

85 

86 

87def lorentz_kernel(n_moments: int, lam: float = 4.) -> NDArray[np.float64]: 

88 r''' 

89 Get the Lorentz kernel :math:`g_m = \sinh[\lambda(1 - m/M)]/\sinh\lambda`, 

90 which gives Lorentzian broadening (the better choice for Green's 

91 functions). 

92 

93 Parameters 

94 ---------- 

95 n_moments : Positive integer :math:`M` 

96 lam : Positive real, default 4 

97 

98 Returns 

99 ------- 

100 g : Real ndarray, shape (n_moments,) 

101 ''' 

102 error_handling.positive_int(n_moments, 'n_moments') 

103 error_handling.positive_real(lam, 'lam') 

104 return np.sinh(lam * (1. - np.arange(n_moments) / n_moments)) / np.sinh(lam) 

105 

106 

107def _setup( 

108 ham, n_moments, kernel, bounds, e_grid, n_grid=1001, 

109) -> tuple[sparse.csr_matrix, NDArray[np.float64], NDArray[np.float64], float, float]: 

110 ''' 

111 Private function. Validate, rescale the Hamiltonian, and build the 

112 coefficients c_m(E) (shape (n_moments, len(e_grid))). 

113 ''' 

114 error_handling.positive_int(n_moments, 'n_moments') 

115 error_handling.kpm_kernel(kernel) 

116 ham_s, a, b = _rescale(ham, bounds) 

117 if e_grid is None: 

118 e_grid = b + a * np.cos(PI * (np.arange(n_grid) + 0.5) / n_grid)[::-1] 

119 e_grid = np.atleast_1d(np.asarray(e_grid, dtype='f8')) 

120 error_handling.ndarray_empty(e_grid, 'e_grid') 

121 eps = (e_grid - b) / a 

122 error_handling.kpm_grid(eps) 

123 return ham_s, e_grid, _coefficients(eps, n_moments, kernel, a), a, b 

124 

125 

126def _coefficients(eps, n_moments, kernel, a) -> NDArray[np.float64]: 

127 ''' 

128 Private function. The coefficients c_m(E) of delta(E - H) at the scaled 

129 energies eps, shape (n_moments, len(eps)). 

130 ''' 

131 g = jackson_kernel(n_moments) if kernel == 'jackson' else lorentz_kernel(n_moments) 

132 tm = np.cos(np.arange(n_moments)[:, None] * np.arccos(eps)[None, :]) 

133 weight = np.where(np.arange(n_moments) == 0, 1., 2.) 

134 return (weight * g)[:, None] * tm / (a * PI * np.sqrt(1. - eps ** 2))[None, :] 

135 

136 

137def _rescale(ham, bounds) -> tuple[sparse.csr_matrix, float, float]: 

138 ''' 

139 Private function. Validate a Hermitian Hamiltonian and map its spectrum 

140 into (-0.99, 0.99): H~ = (H - b)/a. 

141 ''' 

142 ham = sparse.csr_matrix(ham, dtype='c16') 

143 error_handling.square_matrix(ham, 'ham') 

144 error_handling.hermitian(ham) 

145 if bounds is None: 

146 bounds = spectral_bounds(ham) 

147 error_handling.lims(bounds) 

148 e_min, e_max = bounds 

149 a = (e_max - e_min) / (2. - 0.02) # keep the scaled spectrum inside (-0.99, 0.99) 

150 b = (e_max + e_min) / 2. 

151 return (ham - b * sparse.identity(ham.shape[0], format='csr')) / a, a, b 

152 

153 

154def _vectors(n: int, n_random: int | None, seed) -> NDArray[np.complex128]: 

155 ''' 

156 Private function. Random-phase vectors (columns, |r_i| = 1), or, if 

157 n_random is None, the full basis (the exact trace). 

158 ''' 

159 if n_random is None: 

160 return np.eye(n, dtype='c16') 

161 error_handling.positive_int(n_random, 'n_random') 

162 rng = np.random.default_rng(seed) 

163 return np.exp(2j * PI * rng.random((n, n_random))) 

164 

165 

166def _chebyshev(ham_s, vec: NDArray[np.complex128], n_moments: int): 

167 ''' 

168 Private function. Yield T_m(H~) vec for m < n_moments, keeping only two 

169 vectors in memory. 

170 ''' 

171 prev, cur = None, vec 

172 for m in range(n_moments): 

173 yield cur 

174 prev, cur = cur, (ham_s @ cur if m == 0 else 2 * (ham_s @ cur) - prev) 

175 

176 

177def _diagonal_moments(ham_s, vecs: NDArray[np.complex128], n_moments: int) -> NDArray[np.float64]: 

178 ''' 

179 Private function. mu_m = <v|T_m(H~)|v> for every column v of vecs, shape 

180 (n_moments, n_columns), from half as many products: mu_2m = 2<t_m|t_m> - mu_0, 

181 mu_2m+1 = 2<t_m+1|t_m> - mu_1 (Weisse et al., Eq. (48)). 

182 ''' 

183 def dot(u, w): 

184 return (u.real * w.real + u.imag * w.imag).sum(axis=0) # Re <u|w> 

185 

186 mu = np.empty((n_moments + 1, vecs.shape[1])) 

187 prev = None 

188 for m, t in enumerate(_chebyshev(ham_s, vecs, n_moments // 2 + 1)): 

189 if m == 0: 

190 mu[0] = dot(vecs, vecs) 

191 else: 

192 if m == 1: 

193 mu[1] = dot(vecs, t) 

194 mu[2 * m - 1] = 2 * dot(t, prev) - mu[1] 

195 if 2 * m <= n_moments: 

196 mu[2 * m] = 2 * dot(t, t) - mu[0] 

197 prev = t 

198 return mu[:n_moments] 

199 

200 

201def _two_index_moments(ham_s, va, vb, vec: NDArray[np.complex128], n_moments: int) -> NDArray[np.complex128]: 

202 ''' 

203 Private function. mu_mn = sum_r <r| v_a T_m(H~) v_b T_n(H~) |r> over the 

204 columns r of vec (not divided by their number). 

205 ''' 

206 mu = np.zeros((n_moments, n_moments), 'c16') 

207 block = 32 

208 for r in vec.T: 

209 right = np.array([vb @ t for t in _chebyshev(ham_s, r, n_moments)]).T # v_b T_n |r> 

210 left = np.empty((block, len(r)), 'c16') # T_m v_a |r>, a block of m at a time 

211 for m, t in enumerate(_chebyshev(ham_s, va @ r, n_moments)): 

212 left[m % block] = t 

213 if m % block == block - 1 or m == n_moments - 1: 

214 start = m - m % block 

215 mu[start:m + 1] += left[:m % block + 1].conj() @ right 

216 return mu 

217 

218 

219def dos( 

220 ham, n_moments: int = 256, n_random: int | None = 10, e_grid: ArrayLike | None = None, 

221 kernel: str = 'jackson', seed=None, bounds: tuple[float, float] | None = None, 

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

223 r''' 

224 Get the density of states :math:`\rho(E) = \mathrm{Tr}\,\delta(E - H)` 

225 (normalized, like *tbkit.dos.density_of_states*, to integrate to the 

226 number of states). 

227 

228 Parameters 

229 ---------- 

230 ham : Square sparse Hermitian matrix (e.g. *System.ham*) 

231 n_moments : Positive integer, default 256 

232 Number of 

233 Chebyshev moments (the energy resolution is about 

234 :math:`\pi a/M`, :math:`2a` the spectral width). 

235 n_random : Positive integer, or None, default 10 

236 Number of 

237 random vectors for the trace; None for the exact trace (N vectors: 

238 small systems only). 

239 e_grid : Real array 

240 Default value None: 1001 Chebyshev nodes over 

241 the spectrum. Energies, inside the spectral bounds. 

242 kernel : String, default 'jackson' 

243 'jackson' or 'lorentz'. 

244 seed 

245 Default value None. Seed of the random vectors. 

246 bounds : Pair of reals 

247 Default value None (Gershgorin bounds, see 

248 *spectral_bounds*). Bounds enclosing the whole spectrum. 

249 

250 Returns 

251 ------- 

252 e_grid : Real ndarray 

253 rho : Real ndarray, same shape 

254 ''' 

255 ham_s, e_grid, coef, _, _ = _setup(ham, n_moments, kernel, bounds, e_grid) 

256 vec = _vectors(ham_s.shape[0], n_random, seed) 

257 mu = np.array([np.vdot(vec, t).real for t in _chebyshev(ham_s, vec, n_moments)]) 

258 if n_random is not None: 

259 mu = mu / n_random # E<r|A|r> = Tr A for random phases 

260 return e_grid, mu @ coef 

261 

262 

263def dos_from_levels( 

264 levels: ArrayLike, n_moments: int, bounds: tuple[float, float], e_grid: ArrayLike, 

265 kernel: str = 'jackson', 

266) -> NDArray[np.float64]: 

267 r''' 

268 Get the KPM density of states of a *known* spectrum: every level 

269 broadened by exactly the truncated, kernel-damped Chebyshev series that 

270 *dos* uses. It is the reference *dos* converges to (up to the random 

271 trace), e.g. for the bands of a periodic model on a k-mesh. 

272 

273 Parameters 

274 ---------- 

275 levels : Real array 

276 Energy levels. 

277 n_moments : Positive integer 

278 Number of Chebyshev moments. 

279 bounds : Pair of reals 

280 Spectral bounds (those of *dos*, e.g. 

281 *spectral_bounds* of the Hamiltonian it is compared with). 

282 e_grid : Real array 

283 Energies. 

284 kernel : String, default 'jackson' 

285 

286 Returns 

287 ------- 

288 rho 

289 Real ndarray, same shape as *e_grid* (integrating to the number of levels). 

290 ''' 

291 levels = np.asarray(levels, dtype='f8').ravel() 

292 error_handling.ndarray_empty(levels, 'levels') 

293 _, e_grid, coef, a, b = _setup(sparse.identity(1, format='csr'), n_moments, kernel, bounds, e_grid) 

294 error_handling.kpm_grid((levels - b) / a) 

295 tm = np.cos(np.arange(n_moments)[:, None] * np.arccos((levels - b) / a)[None, :]) 

296 return coef.T @ tm.sum(axis=1) 

297 

298 

299def ldos( 

300 ham, site: int, n_moments: int = 256, e_grid: ArrayLike | None = None, 

301 kernel: str = 'jackson', bounds: tuple[float, float] | None = None, 

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

303 r''' 

304 Get the local density of states on one site (or orbital), 

305 :math:`\rho_i(E) = \langle i|\delta(E-H)|i\rangle`, exactly (no random vectors). 

306 

307 Parameters 

308 ---------- 

309 ham : Square sparse Hermitian matrix 

310 site : Integer 

311 Site (row) index. 

312 n_moments : Positive integer, default 256 

313 e_grid 

314 See *dos*. 

315 kernel 

316 See *dos*. 

317 bounds 

318 See *dos*. 

319 

320 Returns 

321 ------- 

322 e_grid : Real ndarray 

323 rho : Real ndarray, same shape 

324 ''' 

325 ham_s, e_grid, coef, _, _ = _setup(ham, n_moments, kernel, bounds, e_grid) 

326 error_handling.site_index(site, ham_s.shape[0]) 

327 vec = np.zeros(ham_s.shape[0], 'c16') 

328 vec[site] = 1. 

329 mu = np.array([t[site].real for t in _chebyshev(ham_s, vec, n_moments)]) 

330 return e_grid, mu @ coef 

331 

332 

333def conductivity( 

334 ham, x: ArrayLike, n_moments: int = 128, n_random: int | None = 10, 

335 e_grid: ArrayLike | None = None, kernel: str = 'jackson', seed=None, 

336 bounds: tuple[float, float] | None = None, area: float | None = None, 

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

338 r''' 

339 Get the zero-temperature DC conductivity along :math:`x` from the 

340 Kubo-Greenwood formula, 

341 

342 .. math:: 

343 

344 \sigma_{xx}(E) = \frac{\pi}{\Omega}\, 

345 \mathrm{Tr}\left[v_x\,\delta(E-H)\,v_x\,\delta(E-H)\right]\, ,\qquad 

346 v_x = i[H, x]\, , 

347 

348 in units of :math:`e^2/\hbar` (:math:`\hbar = e = 1`), by the 

349 two-dimensional Chebyshev expansion of Weisse et al. (the moments 

350 :math:`\mu_{mn} = \mathrm{Tr}[v_x T_m(\tilde H) v_x T_n(\tilde H)]`, 

351 :math:`O(M N)` memory, the DOS needing only :math:`O(N)`). 

352 

353 Parameters 

354 ---------- 

355 ham : Square sparse Hermitian matrix 

356 x : Real array, one coordinate per site (e.g. *lat.coor['x']*) 

357 n_moments : Positive integer, default 128 

358 n_random : Positive integer, or None, default 10 

359 See *dos*. 

360 e_grid 

361 See *dos*. 

362 kernel 

363 See *dos*. 

364 seed 

365 See *dos*. 

366 bounds 

367 See *dos*. 

368 area : Positive real 

369 Default value None (the number of sites): 

370 the area (volume) :math:`\Omega` of the sample. 

371 

372 Returns 

373 ------- 

374 e_grid : Real ndarray 

375 sigma : Real ndarray, same shape 

376 ''' 

377 ham_s, e_grid, coef, a, b = _setup(ham, n_moments, kernel, bounds, e_grid) 

378 n = ham_s.shape[0] 

379 x = np.asarray(x, dtype='f8') 

380 error_handling.ndarray(x, 'x', n) 

381 if area is None: 

382 area = float(n) 

383 error_handling.positive_real(area, 'area') 

384 # v = i [H, x]: v_ij = i H_ij (x_j - x_i); the scale a comes back below 

385 ham_c = sparse.csr_matrix(ham, dtype='c16') 

386 vel = 1j * (ham_c @ sparse.diags(x) - sparse.diags(x) @ ham_c) 

387 mu = _two_index_moments(ham_s, vel, vel, _vectors(n, n_random, seed), n_moments) 

388 if n_random is not None: 

389 mu = mu / n_random 

390 sigma = PI / area * np.einsum('me,mn,ne->e', coef, mu, coef).real 

391 return e_grid, sigma 

392 

393 

394def hall_conductivity( 

395 ham, vx, vy, n_moments: int = 256, n_random: int | None = 10, 

396 e_grid: ArrayLike | None = None, kernel: str = 'jackson', seed=None, 

397 bounds: tuple[float, float] | None = None, area: float | None = None, 

398 temperature: float = 0., 

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

400 r''' 

401 Get the Hall conductivity :math:`\sigma_{xy}(\mu)` of a large sample, at 

402 any Fermi level and temperature, from the Kubo-Bastin formula expanded 

403 in Chebyshev polynomials (Garcia, Covaci and Rappoport, Phys. Rev. Lett. 

404 114, 116602 (2015), Eqs. (1)-(5)). Bastin's formula, 

405 

406 .. math:: 

407 

408 \sigma^{B}_{\alpha\beta}(\mu) = \frac{ie^2\hbar}{\Omega}\int d\varepsilon\,f(\varepsilon)\, 

409 \mathrm{Tr}\left[v_\alpha\,\delta(\varepsilon-H)\,v_\beta\,\frac{dG^+}{d\varepsilon} 

410 - v_\alpha\,\frac{dG^-}{d\varepsilon}\,v_\beta\,\delta(\varepsilon-H)\right]\, , 

411 

412 :math:`G^\pm = (\varepsilon - H \pm i0)^{-1}`, becomes, with the spectrum 

413 rescaled into :math:`(-1, 1)`, :math:`\tilde H = (H-b)/a`, 

414 

415 .. math:: 

416 

417 \sigma^{B}_{\alpha\beta}(\mu) = \frac{4e^2\hbar}{\pi\Omega a^2}\int_{-1}^{1} 

418 d\tilde\varepsilon\,\frac{f(\tilde\varepsilon)}{(1-\tilde\varepsilon^2)^2} 

419 \sum_{m,n}\Gamma_{nm}(\tilde\varepsilon)\,\mu^{\alpha\beta}_{nm}\, , 

420 

421 .. math:: 

422 

423 \mu^{\alpha\beta}_{mn} = \frac{g_mg_n}{(1+\delta_{m0})(1+\delta_{n0})} 

424 \mathrm{Tr}\left[v_\alpha T_m(\tilde H)\,v_\beta T_n(\tilde H)\right]\, , 

425 

426 .. math:: 

427 

428 \Gamma_{mn}(\tilde\varepsilon) = (\tilde\varepsilon - in\sqrt{1-\tilde\varepsilon^2})\, 

429 e^{in\theta}\,T_m(\tilde\varepsilon) 

430 + (\tilde\varepsilon + im\sqrt{1-\tilde\varepsilon^2})\,e^{-im\theta}\,T_n(\tilde\varepsilon)\, , 

431 

432 :math:`\theta = \arccos\tilde\varepsilon`, :math:`g_m` the kernel. The 

433 moments :math:`\mu_{mn}` (the expensive part: :math:`5MR` sparse 

434 products, :math:`O(MN)` memory) serve every Fermi level and temperature. 

435 The energy integral runs over :math:`|\tilde\varepsilon|\le 0.995` 

436 (the spectrum lies within :math:`\pm0.99`): at the ends, 

437 :math:`(1-\tilde\varepsilon^2)^{-2}` would only amplify rounding errors. 

438 

439 **Hall part.** The value is computed from the antisymmetric moments 

440 :math:`(\mu^{xy}_{mn} - \mu^{yx}_{mn})/2`, i.e. it is the Hall 

441 conductivity proper, :math:`(\sigma^B_{xy} - \sigma^B_{yx})/2`, the part 

442 that the Berry curvature gives (*KSpace.hall_conductivity*). The 

443 symmetric part :math:`(\sigma^B_{xy} + \sigma^B_{yx})/2` is a 

444 Fermi-surface term, like :math:`\sigma_{xx}` (see *conductivity*): it 

445 vanishes by symmetry in many lattices (e.g. with a :math:`C_3` axis), 

446 but in a clean metal of lower symmetry it grows as the kernel's 

447 broadening :math:`\pi a/M` shrinks (the Drude weight), and with random 

448 vectors it is the main source of noise. Leaving it out removes that 

449 noise too. In a clean metal the random-vector estimate is still noisy 

450 inside the bands (increase *n_random*, or the size of the sample); 

451 disorder, which makes the Fermi-surface terms finite, and gaps, where 

452 they vanish, are much quieter. 

453 

454 **Sign and units.** The value returned is :math:`-(\sigma^B_{xy}-\sigma^B_{yx})/2` in units 

455 of :math:`e^2/h` (:math:`\hbar = e = 1`), the sign of 

456 *KSpace.hall_conductivity*: :math:`C` in the gap of a Chern insulator 

457 of Chern number :math:`C` (*KSpace.chern_number*). Bastin's 

458 :math:`\sigma^B_{xy}` is the Ohm's-law tensor, :math:`j_x = \sigma^B_{xy}E_y` 

459 (see *KSpace.hall_conductivity*). 

460 

461 **Sample.** The trace must run over a sample without edges -- a torus 

462 (*KSpace.finite_ham* and *KSpace.finite_velocity* with 

463 ``periodic=True``): over a whole open flake, the edge currents cancel 

464 the bulk and the trace vanishes in a gap. 

465 

466 Parameters 

467 ---------- 

468 ham : Square sparse Hermitian matrix 

469 vx : Square sparse (or dense) Hermitian matrix, like *ham* 

470 Velocity 

471 :math:`v_x = i[H, x]` (see *KSpace.finite_velocity*). For a spin 

472 Hall conductivity, pass the spin current :math:`\{s, v_x\}/2` 

473 instead (units :math:`e/2\pi`, see *KSpace.spin_hall_conductivity*). 

474 vy : Square sparse (or dense) Hermitian matrix 

475 Velocity :math:`v_y`. 

476 n_moments : Positive integer, default 256 

477 Number of 

478 Chebyshev moments :math:`M` (energy resolution about :math:`\pi a/M`). 

479 n_random : Positive integer, or None, default 10 

480 See *dos*. 

481 e_grid : Real array 

482 Default value None: 1001 Chebyshev nodes over 

483 the spectrum. Fermi energies :math:`\mu`. 

484 kernel : String, default 'jackson' 

485 See *dos*. 

486 seed 

487 See *dos*. 

488 bounds 

489 See *dos*. 

490 area : Positive real 

491 Default value None (the number of orbitals). 

492 Area :math:`\Omega` of the sample (e.g. number of cells times the 

493 cell area). 

494 temperature : Positive real or zero, default 0 

495 In energy units. 

496 

497 Returns 

498 ------- 

499 e_grid : Real ndarray 

500 sigma : Real ndarray, same shape, in units of :math:`e^2/h` 

501 ''' 

502 ham_s, e_grid, _, a, b = _setup(ham, n_moments, kernel, bounds, e_grid) 

503 n = ham_s.shape[0] 

504 error_handling.velocity(vx, n, 'vx') 

505 error_handling.velocity(vy, n, 'vy') 

506 vx = sparse.csr_matrix(vx, dtype='c16') 

507 vy = sparse.csr_matrix(vy, dtype='c16') 

508 error_handling.hermitian(vx) 

509 error_handling.hermitian(vy) 

510 if area is None: 

511 area = float(n) 

512 error_handling.positive_real(area, 'area') 

513 error_handling.positive_real_zero(temperature, 'temperature') 

514 g = jackson_kernel(n_moments) if kernel == 'jackson' else lorentz_kernel(n_moments) 

515 w = g / np.where(np.arange(n_moments) == 0, 2., 1.) 

516 mu = np.zeros((n_moments, n_moments), 'c16') 

517 for r in _vectors(n, n_random, seed).T: 

518 # <r| v_x T_m = (T_m v_x |r>)^dagger and v_y T_n |r>, for mu^xy; 

519 # the same with x and y swapped, for mu^yx 

520 t_r = list(_chebyshev(ham_s, r, n_moments)) 

521 left_x = np.array(list(_chebyshev(ham_s, vx @ r, n_moments))) 

522 left_y = np.array(list(_chebyshev(ham_s, vy @ r, n_moments))) 

523 right_y = np.array([vy @ t for t in t_r]) 

524 right_x = np.array([vx @ t for t in t_r]) 

525 mu += (left_x.conj() @ right_y.T - left_y.conj() @ right_x.T) / 2 

526 if n_random is not None: 

527 mu = mu / n_random 

528 mu = w[:, None] * mu * w[None, :] 

529 # the energy integrand on a grid uniform in theta = arccos(eps) 

530 n_int = max(2001, 8 * n_moments + 1) 

531 theta = np.linspace(np.arccos(-0.995), np.arccos(0.995), n_int) 

532 eps = np.cos(theta) 

533 root = np.sin(theta) 

534 m = np.arange(n_moments)[:, None] 

535 cheb = np.cos(m * theta[None, :]) 

536 plus = (eps[None, :] - 1j * m * root[None, :]) * np.exp(1j * m * theta[None, :]) 

537 minus = (eps[None, :] + 1j * m * root[None, :]) * np.exp(-1j * m * theta[None, :]) 

538 # sum_{n,m} Gamma_nm mu_nm, Gamma_nm = plus_m T_n + minus_n T_m 

539 gamma_mu = np.sum(cheb * (mu @ plus), axis=0) + np.sum(minus * (mu @ cheb), axis=0) 

540 integrand = (gamma_mu / (1. - eps ** 2) ** 2).real 

541 prefactor = -2 * PI * 4. / (PI * area * a ** 2) # e^2/hbar = 2 pi e^2/h, TKNN sign 

542 energies = a * eps + b 

543 if temperature == 0: 

544 cum = np.concatenate([[0.], np.cumsum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(eps))]) 

545 sigma = prefactor * np.interp(e_grid, energies, cum) 

546 else: 

547 f = np.array([occupation.fermi_dirac(energies, float(e), temperature) for e in e_grid]) 

548 sigma = prefactor * trapezoid(f * integrand[None, :], eps, axis=1) 

549 return e_grid, sigma 

550 

551 

552 

553def time_evolution( 

554 ham, psi_init: NDArray, times: ArrayLike, bounds: tuple[float, float] | None = None, 

555 tol: float = 1e-14, 

556) -> NDArray[np.complex128]: 

557 r''' 

558 Get the time evolution :math:`|\psi(t)\rangle = e^{-iHt}|\psi(0)\rangle` 

559 (:math:`\hbar = 1`) of a large sparse Hamiltonian from its Chebyshev 

560 expansion (Tal-Ezer and Kosloff, J. Chem. Phys. 81, 3967 (1984)), 

561 

562 .. math:: 

563 

564 e^{-iH\Delta t} = e^{-ib\Delta t}\sum_{m\ge0}(2-\delta_{m0})\,(-i)^m 

565 J_m(a\Delta t)\,T_m(\tilde H)\, ,\qquad \tilde H = (H-b)/a\, , 

566 

567 :math:`J_m` the Bessel functions of the first kind. The series converges 

568 exponentially once :math:`m > a\Delta t`: it is truncated where 

569 :math:`|J_m(a\Delta t)|` falls below *tol*, so the result is exact to 

570 machine precision and unitary, whatever the time step, at the cost of 

571 about :math:`a\Delta t` sparse matrix-vector products per interval 

572 (:math:`2a` the spectral width). Nothing is factorized or stored but a 

573 few vectors: unlike the Crank-Nicolson step of 

574 *tbkit.propagation.Propagation* (a sparse LU factorization, whose 

575 fill-in grows quickly in 2D and 3D, and an :math:`O(\Delta t^2)` 

576 error), it reaches millions of sites at machine precision. 

577 

578 Parameters 

579 ---------- 

580 ham : Square sparse Hermitian matrix (e.g. *System.ham*) 

581 psi_init : Complex ndarray, shape (N,) 

582 Initial state. 

583 times : Real array, non-decreasing 

584 Times at which the state is returned, counted from the initial 

585 state (at :math:`t = 0`). Each interval between two of them is one 

586 Chebyshev expansion. 

587 bounds : Pair of reals 

588 Default value None (Gershgorin bounds, see *spectral_bounds*). 

589 Bounds enclosing the whole spectrum. 

590 tol : Positive real, default 1e-14 

591 Truncation of the Bessel coefficients. 

592 

593 Returns 

594 ------- 

595 psi : Complex ndarray, shape (N, len(times)) 

596 The states :math:`\psi(t)`, one column per time. 

597 ''' 

598 ham_s, a, b = _rescale(ham, bounds) 

599 n = ham_s.shape[0] 

600 error_handling.ndarray(psi_init, 'psi_init', n) 

601 times = np.atleast_1d(np.asarray(times, dtype='f8')) 

602 error_handling.kpm_times(times) 

603 error_handling.positive_real(tol, 'tol') 

604 psi = np.empty((n, len(times)), 'c16') 

605 cur = np.asarray(psi_init, dtype='c16').ravel() 

606 for i, dt in enumerate(np.diff(np.concatenate([[0.], times]))): 

607 if dt != 0: 

608 x = a * dt 

609 n_terms = int(abs(x) + 10. * abs(x) ** (1. / 3.) + 20.) 

610 coef = jv(np.arange(n_terms), x) * (-1j) ** np.arange(n_terms) 

611 coef[1:] *= 2. 

612 n_terms = int(np.nonzero(np.abs(coef) > tol)[0][-1]) + 1 

613 nxt = np.zeros(n, 'c16') 

614 for c, t in zip(coef[:n_terms], _chebyshev(ham_s, cur, n_terms)): 

615 nxt += c * t 

616 cur = np.exp(-1j * b * dt) * nxt 

617 psi[:, i] = cur 

618 return psi 

619 

620 

621def spectral_function( 

622 ham, positions: ArrayLike, k: ArrayLike, orbitals: ArrayLike | None = None, 

623 n_moments: int = 256, e_grid: ArrayLike | None = None, kernel: str = 'jackson', 

624 bounds: tuple[float, float] | None = None, 

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

626 r''' 

627 Get the spectral function :math:`A(\mathbf{k}, E)` of a large sample 

628 (disordered, with vacancies, ...), what angle-resolved photoemission 

629 measures, from the Chebyshev moments of plane waves, 

630 

631 .. math:: 

632 

633 A(\mathbf{k}, E) = \sum_o\langle\mathbf{k}, o|\delta(E-H)|\mathbf{k}, o\rangle\, ,\qquad 

634 |\mathbf{k}, o\rangle = \frac{1}{\sqrt{N_o}}\sum_{i\in o} 

635 e^{i\mathbf{k}\cdot\mathbf{r}_i}|i\rangle\, , 

636 

637 the sum running over the :math:`N_o` sites of each sublattice (orbital) 

638 *o*: one recursion of *n_moments* products per k-point and sublattice, 

639 all of them done together. :math:`\int A\,dE` is the number of 

640 sublattices, and in a clean crystal :math:`A` is peaked on the bands 

641 :math:`E_n(\mathbf{k})`; disorder broadens and shifts the peaks. It is 

642 the spectral function that *tbkit.moire.spectral_function* unfolds from 

643 the eigenstates of a supercell (the same, for a torus of that 

644 supercell), without diagonalizing. On a torus, take :math:`\mathbf{k}` 

645 on its mesh (the plane waves are then periodic); in an open flake the 

646 edges add a broadening of the order of the inverse size. 

647 

648 Parameters 

649 ---------- 

650 ham : Square sparse Hermitian matrix, N rows 

651 positions : Real array, shape (N,) or (N, dim) 

652 Position of each site (row), e.g. 

653 ``np.column_stack([lat.coor['x'], lat.coor['y']])``. Cell origins 

654 give the same result. 

655 k : Real array, shape (nk, dim) (or (nk,) in 1D) 

656 Cartesian wavevectors. 

657 orbitals : Array of N labels, default None 

658 The sublattice (orbital) of each row, e.g. ``lat.coor['tag']``; 

659 None: a single one (one orbital per cell). 

660 n_moments : Positive integer, default 256 

661 See *dos*. 

662 e_grid 

663 See *dos*. 

664 kernel 

665 See *dos*. 

666 bounds 

667 See *dos*. 

668 

669 Returns 

670 ------- 

671 e_grid : Real ndarray 

672 A : Real ndarray, shape (nk, len(e_grid)) 

673 ''' 

674 ham_s, e_grid, coef, _, _ = _setup(ham, n_moments, kernel, bounds, e_grid) 

675 n = ham_s.shape[0] 

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

677 if positions.ndim == 1: 

678 positions = positions[:, None] 

679 error_handling.ndarray(positions, 'positions', n) 

680 k = np.asarray(k, dtype='f8') 

681 if k.ndim == 1 and positions.shape[1] == 1: 

682 k = k[:, None] 

683 error_handling.ks(k, positions.shape[1]) 

684 if orbitals is None: 

685 orbitals = np.zeros(n, int) 

686 orbitals = np.asarray(orbitals) 

687 error_handling.ndarray(orbitals, 'orbitals', n) 

688 _, label = np.unique(orbitals, return_inverse=True) 

689 label = label.ravel() 

690 n_orb = label.max() + 1 

691 # one plane wave per (k, orbital): column k*n_orb + o 

692 mask = (label[:, None] == np.arange(n_orb)[None, :]) / np.sqrt(np.bincount(label))[None, :] 

693 waves = (np.exp(1j * positions @ k.T)[:, :, None] * mask[:, None, :]).reshape(n, -1) 

694 mu = _diagonal_moments(ham_s, waves, n_moments).reshape(n_moments, len(k), n_orb).sum(axis=2) 

695 return e_grid, mu.T @ coef 

696 

697 

698def optical_conductivity( 

699 ham, vel, omega: float | ArrayLike, e_fermi: float = 0., temperature: float = 0., 

700 n_moments: int = 256, n_random: int | None = 10, kernel: str = 'jackson', seed=None, 

701 bounds: tuple[float, float] | None = None, area: float | None = None, 

702 vel_b=None, part: str = 'real', 

703) -> NDArray[np.float64] | NDArray[np.complex128]: 

704 r''' 

705 Get the optical conductivity :math:`\sigma_{ab}(\omega)` of a large 

706 sample from the Kubo-Greenwood formula, 

707 

708 .. math:: 

709 

710 \sigma_{ab}(\omega) = \frac{ie^2}{\hbar\,\Omega}\int\!\!\int dE_1\,dE_2\, 

711 j_{ab}(E_1, E_2)\,\frac{f(E_1) - f(E_2)}{E_2 - E_1}\, 

712 \frac{1}{\hbar\omega - (E_1 - E_2) + i0}\, ,\qquad 

713 j_{ab}(E_1, E_2) = \mathrm{Tr}\left[v_a\,\delta(E_1-H)\,v_b\,\delta(E_2-H)\right]\, , 

714 

715 the trace expanded in two-index Chebyshev moments 

716 :math:`\mu_{mn} = \mathrm{Tr}[v_b T_m(\tilde H) v_a T_n(\tilde H)]` 

717 (Weisse et al., Sec. IV; those of *conductivity*, which is the 

718 :math:`\omega\to0` limit of :math:`\mathrm{Re}\,\sigma_{xx}` at zero 

719 temperature). It is *tbkit.optics.optical_conductivity* (the same 

720 tensor and sign: :math:`j_a = \sigma_{ab}E_b`, both inter- and 

721 intraband, the Drude peak broadened by the kernel to a width 

722 :math:`\sim\pi a/M` instead of :math:`\eta`), for a sample of any size, 

723 clean or disordered. The moments (the expensive part, :math:`O(MR)` 

724 sparse products, :math:`O(MN)` memory) serve every frequency, Fermi 

725 level and temperature. 

726 

727 With the spectral function of the transitions, 

728 :math:`S_{ab}(\nu) = \frac1\Omega\int dE\,j_{ab}(E+\nu, E)\, 

729 \frac{f(E) - f(E+\nu)}{\nu}`, it is 

730 :math:`\sigma_{ab}(\omega) = \frac{e^2}{\hbar}\left[\pi S_{ab}(\omega) 

731 + i\,\mathrm{P}\!\!\int d\nu\,\frac{S_{ab}(\nu)}{\omega - \nu}\right]`: 

732 the absorptive part :math:`\pi S_{ab}(\omega)` (the vertical 

733 transitions at :math:`\hbar\omega`, for ``part='real'`` and 

734 :math:`a = b`) and the reactive part, a principal value over all 

735 :math:`\nu`, positive and negative (Kramers-Kronig). The principal 

736 value needs :math:`S_{ab}` on a grid of :math:`8M` frequencies; it is 

737 skipped when only :math:`\mathrm{Re}\,\sigma_{aa}` is asked for. 

738 

739 * :math:`\mathrm{Re}\,\sigma_{xx}`: for graphene at neutrality, the 

740 universal :math:`\pi/4\,e^2/h` (spinless, two valleys) for 

741 :math:`\pi a/M \ll \omega \ll t`. 

742 * :math:`\mathrm{Im}\,\sigma_{xx}`: the reactive response, negative 

743 below the gap of an insulator (in the sign convention of 

744 *tbkit.optics*). 

745 * Hall components (*vel* = :math:`v_y`, *vel_b* = :math:`v_x`): in the 

746 gap of a Chern insulator, :math:`\mathrm{Re}\,\sigma_{yx}(\omega\to0)` 

747 is its Chern number :math:`C`, the value of *hall_conductivity* and 

748 *KSpace.hall_conductivity*; at finite frequency, the Faraday and Kerr 

749 rotations. 

750 

751 The random trace is noisier than that of *dos*: its relative error 

752 falls as :math:`1/\sqrt{RN}` but from a larger prefactor, about 10% for 

753 :math:`R = 4` random vectors on 45,000 orbitals of graphene at 

754 :math:`\omega \sim 0.3t`, 2% for :math:`R = 16`. 

755 

756 The trace must run over a sample without edges, a torus 

757 (*KSpace.finite_ham* and *KSpace.finite_velocity* with 

758 ``periodic=True``), or over one large enough for its edges not to matter. 

759 

760 Parameters 

761 ---------- 

762 ham : Square sparse Hermitian matrix 

763 vel : Square sparse (or dense) Hermitian matrix, like *ham* 

764 Velocity :math:`v_a = i[H, r_a]` (*KSpace.finite_velocity*), or any 

765 current operator. 

766 omega : Positive real, or array of positive reals 

767 Photon energies :math:`\hbar\omega`. 

768 e_fermi : Real number, default 0 

769 Fermi energy, inside the spectral bounds. 

770 temperature : Positive real or zero, default 0 

771 In energy units. 

772 n_moments : Positive integer, default 256 

773 Number of Chebyshev moments :math:`M` (energy resolution about 

774 :math:`\pi a/M`). 

775 n_random : Positive integer, or None, default 10 

776 See *dos*. 

777 kernel 

778 See *dos*. 

779 seed 

780 See *dos*. 

781 bounds 

782 See *dos*. 

783 area : Positive real 

784 Default value None (the number of orbitals). Area (volume) 

785 :math:`\Omega` of the sample. 

786 vel_b : Square sparse (or dense) Hermitian matrix, like *ham* 

787 Default value None (*vel*: :math:`\sigma_{aa}`). Velocity 

788 :math:`v_b`, for an off-diagonal (Hall) component :math:`\sigma_{ab}`. 

789 part : String, default 'real' 

790 'real' (:math:`\mathrm{Re}\,\sigma_{ab}`), 'imag' 

791 (:math:`\mathrm{Im}\,\sigma_{ab}`) or 'complex' (both). 

792 

793 Returns 

794 ------- 

795 sigma 

796 Real ndarray (complex for ``part='complex'``), shape 

797 (len(omega),), in units of :math:`e^2/h`. 

798 ''' 

799 ham_s, _, _, a, b = _setup(ham, n_moments, kernel, bounds, [0.]) 

800 n = ham_s.shape[0] 

801 error_handling.velocity(vel, n, 'vel') 

802 vel = sparse.csr_matrix(vel, dtype='c16') 

803 error_handling.hermitian(vel) 

804 diagonal = vel_b is None 

805 if not diagonal: 

806 error_handling.velocity(vel_b, n, 'vel_b') 

807 vel_b = sparse.csr_matrix(vel_b, dtype='c16') 

808 error_handling.hermitian(vel_b) 

809 error_handling.frequencies(omega, 'omega') 

810 w_arr = np.atleast_1d(np.asarray(omega, dtype='f8')).ravel() 

811 error_handling.positive_frequencies(w_arr) 

812 error_handling.real_number(e_fermi, 'e_fermi') 

813 error_handling.kpm_grid(np.array([(e_fermi - b) / a]), 'e_fermi') 

814 error_handling.positive_real_zero(temperature, 'temperature') 

815 if area is None: 

816 area = float(n) 

817 error_handling.positive_real(area, 'area') 

818 error_handling.optical_part(part) 

819 # mu_mn = Tr[v_b T_m v_a T_n]: k(E1, E2) = Tr[v_b delta(E1 - H) v_a delta(E2 - H)] 

820 # = j_ab(E2, E1), so that j_ab(E + nu, E) = k(E, E + nu) 

821 mu = _two_index_moments(ham_s, vel if diagonal else vel_b, vel, _vectors(n, n_random, seed), n_moments) 

822 if n_random is not None: 

823 mu = mu / n_random 

824 # on a fine energy grid; j_aa is real (sum_nm |v_nm|^2 delta delta) 

825 n_grid = max(1001, 8 * n_moments + 1) 

826 eps = np.linspace(-0.995, 0.995, n_grid) 

827 energies = a * eps + b 

828 coef = _coefficients(eps, n_moments, kernel, a) 

829 joint = coef.T @ (mu.real if diagonal else mu) @ coef 

830 lo, hi = energies[0], energies[-1] 

831 step = (hi - lo) / (n_grid - 1) 

832 

833 def bilinear(x, y): 

834 # joint at (x, y), linear between the grid points in both directions 

835 fx = np.clip((x - lo) / step, 0., n_grid - 1.) 

836 fy = np.clip((y - lo) / step, 0., n_grid - 1.) 

837 i = np.minimum(fx.astype(int), n_grid - 2) 

838 j = np.minimum(fy.astype(int), n_grid - 2) 

839 tx, ty = fx - i, fy - j 

840 return ((1 - tx) * ((1 - ty) * joint[i, j] + ty * joint[i, j + 1]) 

841 + tx * ((1 - ty) * joint[i + 1, j] + ty * joint[i + 1, j + 1])) 

842 

843 def spectral(nu): 

844 # S(nu) = 1/Omega int dE j_ab(E + nu, E) [f(E) - f(E + nu)] / nu, for nu != 0 

845 if temperature == 0: 

846 e_lo = np.maximum(np.maximum(lo, lo - nu), e_fermi - np.maximum(nu, 0.)) 

847 e_hi = np.minimum(np.minimum(hi, hi - nu), e_fermi + np.maximum(-nu, 0.)) 

848 else: 

849 e_lo, e_hi = np.maximum(lo, lo - nu), np.minimum(hi, hi - nu) 

850 width = np.maximum(e_hi - e_lo, 0.) 

851 out = np.zeros(len(nu), 'c16') 

852 frac = np.linspace(0., 1., n_grid) 

853 rows = max(1, 2 ** 20 // n_grid) 

854 for c0 in range(0, len(nu), rows): 

855 sl = slice(c0, c0 + rows) 

856 e = e_lo[sl, None] + width[sl, None] * frac[None, :] 

857 if temperature == 0: 

858 occ = np.sign(nu[sl])[:, None] * np.ones_like(e) 

859 else: 

860 occ = (occupation.fermi_dirac(e, e_fermi, temperature) 

861 - occupation.fermi_dirac(e + nu[sl, None], e_fermi, temperature)) 

862 val = bilinear(e, e + nu[sl, None]) 

863 out[sl] = trapezoid(occ * val, dx=1., axis=1) * width[sl] / (n_grid - 1) 

864 return out / (area * nu) 

865 

866 s_w = spectral(w_arr) # the absorptive part, pi S(omega) 

867 if part == 'real' and diagonal: 

868 return 2 * PI * PI * s_w.real # e^2/hbar = 2 pi e^2/h 

869 # the reactive part, i P int S(nu) / (omega - nu), on a grid of 

870 # midpoints (never nu = 0) over the whole range of transition energies 

871 span = hi - lo 

872 n_half = max(512, 4 * n_moments) 

873 nu = -span + (np.arange(2 * n_half) + 0.5) * span / n_half 

874 s_nu = spectral(nu) 

875 reactive = np.zeros(len(w_arr), 'c16') 

876 for i, w in enumerate(w_arr): 

877 if w >= nu[-1]: # no transition: S(omega) = 0, and no singularity 

878 reactive[i] = trapezoid(s_nu / (w - nu), nu) 

879 continue 

880 s0 = np.interp(w, nu, s_nu.real) + 1j * np.interp(w, nu, s_nu.imag) 

881 # subtract the pole: (S(nu) - S(omega)) / (omega - nu) is smooth (0 at 

882 # a grid point nu = omega), and P int dnu / (omega - nu) is a log 

883 d = w - nu 

884 integrand = (s_nu - s0) / np.where(d == 0, 1., d) 

885 reactive[i] = trapezoid(integrand, nu) + s0 * np.log((w + span) / (span - w)) 

886 sigma = 2 * PI * (PI * s_w + 1j * reactive) 

887 if part == 'real': 

888 return sigma.real 

889 if part == 'imag': 

890 return sigma.imag 

891 return sigma 

892 

893 

894def _resolvent_coefficients(z: NDArray[np.complex128], n_moments: int) -> NDArray[np.complex128]: 

895 r''' 

896 Private function. The Chebyshev coefficients of the scaled resolvent, 

897 :math:`(z - \tilde H)^{-1} = \sum_n c_n(z)\,T_n(\tilde H)`, 

898 :math:`c_n = (2-\delta_{n0})\,w^n/\sqrt{z^2-1}`, :math:`w = z - \sqrt{z^2-1}` 

899 (:math:`|w| < 1`, the branch of the root that behaves as :math:`z` at 

900 infinity), at the complex scaled energies *z*, shape (n_moments, len(z)). 

901 ''' 

902 root = np.sqrt(z - 1.) * np.sqrt(z + 1.) 

903 w = z - root 

904 coef = w[None, :] ** np.arange(n_moments)[:, None] / root[None, :] 

905 coef[1:] *= 2. 

906 return coef 

907 

908 

909def _three_index_moments(ham_s, va, vb, vc, vec: NDArray[np.complex128], n_moments: int) -> NDArray[np.complex128]: 

910 ''' 

911 Private function. Gamma_mnp = sum_r <r| T_m(H~) v_a T_n(H~) v_b T_p(H~) v_c |r> 

912 over the columns r of vec (not divided by their number), for Hermitian 

913 v_a, v_b, v_c: O(M^2) sparse products and O(M^3 N) operations per vector. 

914 ''' 

915 gamma = np.zeros((n_moments, n_moments, n_moments), 'c16') 

916 for r in vec.T: 

917 left = np.array([va @ t for t in _chebyshev(ham_s, r, n_moments)]).conj() # (v_a T_m |r>)^* 

918 right = np.array(list(_chebyshev(ham_s, vc @ r, n_moments))).T # T_p v_c |r>, columns p 

919 for nn, t in enumerate(_chebyshev(ham_s, vb @ right, n_moments)): # T_n v_b T_p v_c |r> 

920 gamma[:, nn, :] += left @ t 

921 return gamma 

922 

923 

924def nonlinear_optical_conductivity( 

925 ham, derivatives: dict, omega1: float | ArrayLike, omega2: float | ArrayLike, 

926 component: str = 'xxx', e_fermi: float = 0., temperature: float = 0., eta: float = 0.05, 

927 n_moments: int = 128, n_random: int | None = 10, kernel: str = 'jackson', seed=None, 

928 bounds: tuple[float, float] | None = None, area: float | None = None, 

929) -> NDArray[np.complex128]: 

930 r''' 

931 Get the second-order optical conductivity :math:`\sigma^{abc}(\omega_1, \omega_2)` 

932 of a large sample, :math:`j^a(\omega_1+\omega_2) = \sum\sigma^{abc}(\omega_1,\omega_2) 

933 E^b(\omega_1)E^c(\omega_2)` (the sum running over the ordered pairs of 

934 frequencies of the field), from three-index Chebyshev moments, as KITE's 

935 ``conductivity_optical_nonlinear`` (Joao and Lopes, J. Phys.: Condens. 

936 Matter 32, 125901 (2020)). It covers second-harmonic generation 

937 (:math:`\omega_1 = \omega_2`), the shift and injection currents 

938 (:math:`\omega_2 = -\omega_1`) and optical rectification, in clean or 

939 disordered samples. 

940 

941 **Velocity gauge.** The field enters through the Peierls phases, 

942 :math:`H(\mathbf{A}) = H + A_bh^b + \frac12A_bA_ch^{bc} + \dots`, with 

943 the derivatives :math:`h^{b\dots}` of *KSpace.finite_derivatives* and 

944 :math:`\mathbf{E} = -\partial_t\mathbf{A}`; the current is 

945 :math:`j^a = -\frac1\Omega\langle\partial H/\partial A_a\rangle` (charge 

946 :math:`-e`, :math:`\hbar = e = 1`). The density matrix to second order 

947 gives, after the occupations are moved onto one state at a time, 

948 

949 .. math:: 

950 

951 \sigma^{abc}(\omega_1,\omega_2) = \frac{1}{2\Omega\,\omega_1\omega_2} 

952 \left[S^{abc}(\omega_1,\omega_2) + S^{acb}(\omega_2,\omega_1)\right]\, , 

953 

954 .. math:: 

955 

956 S^{abc}(\omega_1,\omega_2) = \int d\varepsilon\,f(\varepsilon)\Big\{ 

957 \tfrac12\mathrm{Tr}[\delta\,h^{abc}] 

958 + \tfrac12\mathcal{T}(h^{bc}, h^a; \omega_3) 

959 + \mathcal{T}(h^c, h^{ab}; \omega_2) 

960 + \mathrm{Tr}[\delta\,h^aG^R_{\omega_3}h^bG^R_{\omega_2}h^c] 

961 + \mathrm{Tr}[G^A_{-\omega_2}h^aG^R_{\omega_1}h^b\,\delta\,h^c] 

962 + \mathrm{Tr}[G^A_{-\omega_3}h^a\,\delta\,h^bG^A_{-\omega_1}h^c]\Big\}\, , 

963 

964 with :math:`\delta = \delta(\varepsilon - H)`, 

965 :math:`G^{R}_{\omega} = (\varepsilon + \omega + i\eta - H)^{-1}`, 

966 :math:`G^{A}_{-\omega} = (\varepsilon - \omega - i\eta - H)^{-1}`, 

967 :math:`\omega_3 = \omega_1 + \omega_2` (with :math:`2\eta`: each 

968 field is switched on as :math:`e^{\eta t}`) and 

969 :math:`\mathcal{T}(P, Q; \omega) = \mathrm{Tr}[P\,\delta\,Q\,G^R_\omega] 

970 + \mathrm{Tr}[Q\,\delta\,P\,G^A_{-\omega}]`. The delta functions are 

971 expanded with the kernel, the Green's functions with the broadening 

972 :math:`\eta`. The result tends to the sum over eigenstates with 

973 Lorentzian broadening :math:`\eta` as the width of the kernel, 

974 :math:`\pi a/M` (:math:`2a` the spectral width), becomes small next to 

975 :math:`\eta`, with a relative error of about :math:`(\pi a/M\eta)^2`: 

976 20% for :math:`\pi a/M\eta = 0.34`, 2-5% for 0.17, 0.6-1.3% for 0.085. 

977 The moments :math:`\mathrm{Tr}[T_m h^aT_n h^bT_p h^c]` cost 

978 :math:`O(M^2R)` sparse products and :math:`O(M^3RN)` operations, 

979 :math:`O(M^3)` memory; they serve every frequency, Fermi level and 

980 temperature, and each frequency pair then costs :math:`O(M^4)` 

981 operations (the energy integral). 

982 

983 In the tight-binding basis the velocity gauge is exact, and equal to 

984 the length gauge of *tbkit.optics* with ``positions=True``: for a 

985 linear polarization in a time-reversal-symmetric crystal, 

986 :math:`\mathrm{Re}\,\sigma^{abb}(\omega, -\omega)` is the shift 

987 conductivity of *tbkit.optics.shift_current* (up to the Lorentzian 

988 instead of the Gaussian broadening). The cancellations between the 

989 terms are exact only as :math:`\eta \to 0` and :math:`M \to \infty`; at 

990 low frequency, where the prefactor :math:`1/\omega_1\omega_2` grows, 

991 they need more moments. 

992 

993 The random trace is much noisier than that of *dos* or 

994 *optical_conductivity*: on gapped graphene, about 20% for 

995 :math:`RN \sim 10^4` (:math:`R` random vectors, :math:`N` orbitals), 

996 falling as :math:`1/\sqrt{RN}`. 

997 

998 The trace must run over a sample without edges, a torus 

999 (*KSpace.finite_ham* and *KSpace.finite_derivatives* with 

1000 ``periodic=True``). 

1001 

1002 Parameters 

1003 ---------- 

1004 ham : Square sparse Hermitian matrix 

1005 derivatives : Dict 

1006 The derivatives :math:`h^a, h^b, h^c, h^{ab}, h^{ac}, h^{bc}, h^{abc}` 

1007 of *ham*, Hermitian matrices of its shape, keyed by their axes in 

1008 alphabetical order, as *KSpace.finite_derivatives* returns them. 

1009 omega1, omega2 : Nonzero real numbers, or arrays of them (broadcast together) 

1010 Frequencies :math:`\hbar\omega_1`, :math:`\hbar\omega_2` (negative 

1011 for the conjugate field). 

1012 component : String, default 'xxx' 

1013 Three letters among 'x', 'y', 'z': :math:`a, b, c`. 

1014 e_fermi : Real number, default 0 

1015 Fermi energy, inside the spectral bounds. 

1016 temperature : Positive real or zero, default 0 

1017 In energy units. 

1018 eta : Positive real, default 0.05 

1019 Broadening of the Green's functions. 

1020 n_moments : Positive integer, default 128 

1021 Number of Chebyshev moments :math:`M`. 

1022 n_random : Positive integer, or None, default 10 

1023 See *dos*. 

1024 kernel 

1025 See *dos*. 

1026 seed 

1027 See *dos*. 

1028 bounds 

1029 See *dos*. 

1030 area : Positive real 

1031 Default value None (the number of orbitals). Area (volume) 

1032 :math:`\Omega` of the sample. 

1033 

1034 Returns 

1035 ------- 

1036 sigma 

1037 Complex ndarray, the broadcast shape of *omega1* and *omega2* 

1038 (raveled), in units of :math:`e^3/\hbar^2` times length per energy 

1039 (:math:`\hbar = e = 1`), the units of *tbkit.optics.shift_current*. 

1040 ''' 

1041 ham_s, _, _, a, b = _setup(ham, n_moments, kernel, bounds, [0.]) 

1042 n = ham_s.shape[0] 

1043 error_handling.cartesian_axes(component, 3, length=3) 

1044 ca, cb, cc = component[0], component[1], component[2] 

1045 key = lambda *letters: ''.join(sorted(letters)) # noqa: E731 

1046 keys = [key(ca), key(cb), key(cc), key(ca, cb), key(ca, cc), key(cb, cc), key(ca, cb, cc)] 

1047 error_handling.nonlinear_derivatives(derivatives, keys, n) 

1048 h = {k: sparse.csr_matrix(derivatives[k], dtype='c16') for k in keys} 

1049 for k in keys: 

1050 error_handling.hermitian(h[k]) 

1051 error_handling.nonzero_frequencies(omega1, 'omega1') 

1052 error_handling.nonzero_frequencies(omega2, 'omega2') 

1053 w1, w2 = np.broadcast_arrays(np.asarray(omega1, dtype='f8'), np.asarray(omega2, dtype='f8')) 

1054 w1, w2 = w1.ravel(), w2.ravel() 

1055 error_handling.real_number(e_fermi, 'e_fermi') 

1056 error_handling.kpm_grid(np.array([(e_fermi - b) / a]), 'e_fermi') 

1057 error_handling.positive_real_zero(temperature, 'temperature') 

1058 error_handling.positive_real(eta, 'eta') 

1059 if area is None: 

1060 area = float(n) 

1061 error_handling.positive_real(area, 'area') 

1062 vec = _vectors(n, n_random, seed) 

1063 # the moments: Tr[h^abc T_m]; Tr[P T_m Q T_n] for the pairs (P, Q) of 

1064 # the T terms; Tr[T_m h^a T_n h^b T_p h^c] (that of h^a, h^c, h^b is 

1065 # its conjugate with m and n exchanged) 

1066 mu1 = np.array([np.vdot(h[keys[6]] @ vec, t) for t in _chebyshev(ham_s, vec, n_moments)]) 

1067 pairs = {(p, q): _two_index_moments(ham_s, h[p], h[q], vec, n_moments) 

1068 for p, q in ((keys[2], keys[3]), (keys[1], keys[4]), (keys[5], keys[0]))} 

1069 gamma = _three_index_moments(ham_s, h[keys[0]], h[keys[1]], h[keys[2]], vec, n_moments) 

1070 if n_random is not None: 

1071 mu1 = mu1 / n_random 

1072 pairs = {pq: mu / n_random for pq, mu in pairs.items()} 

1073 gamma = gamma / n_random 

1074 gamma_swap = gamma.transpose(1, 0, 2).conj() 

1075 # the energy integral, on a grid uniform in theta = arccos(eps), where 

1076 # delta(eps - H~) d eps = sum_m (2 - delta_m0) g_m cos(m theta) T_m d theta / pi 

1077 n_int = max(201, 4 * n_moments + 1, int(4 * PI * a / eta) + 1) 

1078 if temperature == 0: 

1079 theta = np.linspace(np.arccos((e_fermi - b) / a), PI, n_int) 

1080 occ = np.ones(n_int) 

1081 else: 

1082 theta = np.linspace(0., PI, n_int) 

1083 occ = occupation.fermi_dirac(a * np.cos(theta) + b, e_fermi, temperature) 

1084 weights = occ * np.full(n_int, theta[1] - theta[0]) 

1085 weights[[0, -1]] /= 2. # trapezoid 

1086 g = jackson_kernel(n_moments) if kernel == 'jackson' else lorentz_kernel(n_moments) 

1087 m = np.arange(n_moments) 

1088 delta = (np.where(m == 0, 1., 2.) * g)[:, None] * np.cos(m[:, None] * theta[None, :]) / PI * weights[None, :] 

1089 eps = np.cos(theta) 

1090 

1091 def green(omega, n_eta=1): 

1092 # coefficients of G^R(eps + omega) = c(z)/a, z = eps~ + (omega + i n_eta eta)/a 

1093 # (G^A(eps - omega) is the conjugate of G^R at -omega); each field 

1094 # is switched on as exp(eta t), so omega_3 carries 2 eta 

1095 return _resolvent_coefficients(eps + (omega + 1j * n_eta * eta) / a, n_moments) / a 

1096 

1097 def pair(p, q, omega, n_eta): 

1098 # T(P, Q; omega) = Tr[P delta Q G^R_omega] + Tr[Q delta P G^A_-omega] 

1099 mu = pairs[(p, q)] 

1100 return np.sum(delta * (mu @ green(omega, n_eta) + mu.T @ green(-omega, n_eta).conj())) 

1101 

1102 def triple(gam, om1, om2): 

1103 # the three terms of Tr[. h^a . h^b . h^c] with G and delta in turn 

1104 om3 = om1 + om2 

1105 total = 0j 

1106 for x, y, z in ((delta, green(om3, 2), green(om2)), 

1107 (green(-om2).conj(), green(om1), delta), 

1108 (green(-om3, 2).conj(), delta, green(-om1).conj())): 

1109 for e0 in range(0, n_int, 64): # sum_p first, 64 energies at a time 

1110 sl = slice(e0, e0 + 64) 

1111 inner = (gam.reshape(-1, n_moments) @ z[:, sl]).reshape(n_moments, n_moments, -1) 

1112 total += np.einsum('mne,me,ne->', inner, x[:, sl], y[:, sl]) 

1113 return total 

1114 

1115 one = 0.5 * np.sum(delta * mu1.real[:, None]) # Tr[delta h^abc] is real 

1116 sigma = np.zeros(len(w1), 'c16') 

1117 for i, (om1, om2) in enumerate(zip(w1, w2)): 

1118 rect = 0.5 * pair(keys[5], keys[0], om1 + om2, 2) 

1119 s_abc = one + rect + pair(keys[2], keys[3], om2, 1) + triple(gamma, om1, om2) 

1120 s_acb = one + rect + pair(keys[1], keys[4], om1, 1) + triple(gamma_swap, om2, om1) 

1121 sigma[i] = (s_abc + s_acb) / (2. * area * om1 * om2) 

1122 return sigma