Coverage for tbkit/system.py: 100%

654 statements  

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

1from __future__ import annotations 

2 

3from typing import Callable 

4 

5from numpy.typing import ArrayLike 

6 

7import numpy as np 

8from numpy.typing import NDArray 

9import scipy.sparse as sparse 

10import scipy.linalg as LA 

11import scipy.sparse.linalg as SLA 

12from scipy.spatial import cKDTree 

13import numpy.random as rand 

14npc = np.char # `import numpy.char` needs NumPy >= 2.0 

15from itertools import product 

16from math import sin, cos 

17import tbkit.error_handling as error_handling 

18import tbkit.occupation as occupation 

19import tbkit.values as values 

20from tbkit.lattice import Lattice, COOR_DTYPE, TAG_LEN, _tag_pair 

21 

22 

23PI = np.pi 

24ATOL = 1e-3 

25HOP_DTYPE = [('n', 'u2'), ('i', 'u4'), ('j', 'u4'), 

26 ('ang', 'f8'), ('tag', 'U{}'.format(2 * TAG_LEN)), ('t', 'c16')] 

27 

28 

29def _upper(ang: NDArray) -> NDArray: 

30 ''' 

31 Private function. 

32 Mask of the bond angles (in degrees, from np.arctan2) that point into the 

33 half-plane :math:`[0, 180)`, within ATOL: a bond at -1e-14 degrees counts as 

34 horizontal (0), one at 179.99999 as pointing the other way. 

35 ''' 

36 return (ang >= -ATOL) & (ang < 180. - ATOL) 

37 

38 

39def _inertia(ham: sparse.csc_matrix, sigma: float) -> int: 

40 ''' 

41 Private function. The number of eigenvalues of the Hermitian *ham* below 

42 *sigma* (Sylvester's law of inertia): the negative pivots of the sparse 

43 LDL^dagger factorization of ham - sigma, from SuperLU with a symmetric 

44 permutation and diagonal pivots. Should SuperLU still exchange rows (or 

45 find an exactly zero pivot), the count comes from the dense spectrum. 

46 ''' 

47 shifted = (ham - sigma * sparse.identity(ham.shape[0], format='csc')).tocsc() 

48 try: 

49 lu = SLA.splu(shifted, permc_spec='MMD_AT_PLUS_A', diag_pivot_thresh=0., 

50 options={'SymmetricMode': True}) 

51 except RuntimeError: # exactly singular 

52 lu = None 

53 if lu is None or not np.array_equal(lu.perm_r, lu.perm_c): 

54 return int(np.sum(LA.eigvalsh(ham.toarray()) < sigma)) 

55 return int(np.sum(lu.U.diagonal().real < 0)) 

56 

57 

58def _slice_pairs( 

59 ham: sparse.csc_matrix, lo: float, hi: float, count: int, sigma: float, 

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

61 r''' 

62 Private function. The *count* eigenpairs of the Hermitian *ham* in 

63 [lo, hi), by shift-invert Lanczos about *sigma* with deflation: one 

64 factorization of ham - sigma, then passes of ARPACK on 

65 :math:`P(H - \sigma)^{-1}P`, *P* projecting out the eigenvectors already 

66 found. Lanczos from one start vector finds one vector of a degenerate 

67 eigenspace at a time (it may also return a vector twice); deflation 

68 makes the missing ones dominant. Every candidate is orthogonalized 

69 against those kept, and kept only if it is independent of them. 

70 ''' 

71 n = ham.shape[0] 

72 lu = SLA.splu((ham - sigma * sparse.identity(n, format='csc')).tocsc()) 

73 found = np.zeros((n, 0), 'c16') 

74 values: list[float] = [] 

75 rng = np.random.default_rng(0) 

76 for _ in range(count + 2): 

77 if len(values) == count: 

78 break 

79 

80 def solve(x, basis=found): 

81 x = np.asarray(x, dtype='c16') 

82 y = lu.solve(x - basis @ (basis.conj().T @ x)) 

83 return y - basis @ (basis.conj().T @ y) 

84 

85 op = SLA.LinearOperator((n, n), matvec=solve, dtype='c16') 

86 v0 = rng.standard_normal(n) + 0j 

87 v0 -= found @ (found.conj().T @ v0) 

88 k = min(count - len(values) + 2, n - found.shape[1] - 2) 

89 en, vec = SLA.eigsh(ham, k=k, sigma=sigma, OPinv=op, v0=v0) 

90 for e, v in zip(en, vec.T): 

91 if lo <= e < hi: 

92 v = v - found @ (found.conj().T @ v) 

93 norm = np.linalg.norm(v) 

94 if norm > 0.5: 

95 found = np.column_stack([found, v / norm]) 

96 values.append(float(e)) 

97 error_handling.slice_count(len(values), count, lo, hi) 

98 return np.array(values), found 

99 

100 

101class System(): 

102 r''' 

103 Solve the Tight-Binding eigenvalue problem of a lattice defined  

104 by the class **lattice**. 

105 

106 Parameters 

107 ---------- 

108 lat : **lattice** class instance 

109 periodic : Boolean, or tuple of booleans (one per primitive vector), default False 

110 Periodic boundary conditions along the 

111 primitive vectors :math:`\mathbf{a}_i`: the sample is then the 

112 :math:`n_1\mathbf{a}_1\times n_2\mathbf{a}_2\,(\times n_3\mathbf{a}_3)` 

113 box of *lat.get_lattice* wrapped into a torus (True), or a cylinder 

114 (e.g. ``(True, False)``, periodic along :math:`\mathbf{a}_1` only). 

115 *lat.get_lattice* must have been called; sites may be removed 

116 afterwards (vacancies), but not moved. Every distance and bond 

117 angle is then that of the shortest image, so the neighbour orders of 

118 *set_hopping* include the bonds that wrap around, with their short 

119 bond vector; a bond order reaching half-way around the torus is 

120 refused (it would be ambiguous). A uniform magnetic field 

121 (*set_magnetic_field*) and the local Chern marker need open 

122 boundaries; *get_bott_index* is the Chern number of a torus. 

123 

124 Notes 

125 ----- 

126 Up to *dense_max* sites (default 5000), the distances between all pairs 

127 of sites are computed (and kept in *vec_hop*). Larger lattices only look 

128 for the neighbours they need, with a k-d tree, up to the largest 

129 neighbour order a call asks for: memory and time then grow linearly 

130 with the number of sites (*vec_hop* stays empty). 

131 ''' 

132 

133 #: Largest lattice (number of sites) whose pairwise distances are all computed. 

134 dense_max = 5000 

135 

136 def __init__(self, lat: Lattice, periodic: bool | tuple[bool, ...] = False) -> None: 

137 error_handling.lat(lat) 

138 self.periodic = error_handling.periodic(periodic, len(lat.prim_vec)) 

139 if any(self.periodic): 

140 error_handling.torus_lattice(lat.n1) 

141 self.lat = lat 

142 self.sites = self.lat.sites # used to check if sites changes 

143 self.coor_hop = np.array([], dtype=COOR_DTYPE) 

144 self.vec_hop = np.array([], dtype=[('dis', 'f8'), ('ang', 'f8')]) # Hopping distances and angles 

145 self.dist_uni = np.array([], 'f8') # Different hopping distances 

146 self.store_hop: dict = {} # Store the relevant hoppings (dynamic programming) 

147 self.hop = np.array([], dtype=HOP_DTYPE) # Hoppings to build-up the Hamiltonian 

148 self.onsite = np.array([], 'c16') # Onsite energies 

149 # Value functions (see tbkit.values): (directed bond keys, function) 

150 # of the hoppings whose row of `hop` holds a factor 't', and (site 

151 # indices, function) of the onsite terms added to `onsite`. 

152 self._hop_values: list = [] 

153 self._onsite_values: list = [] 

154 self.ham = sparse.csr_matrix(([], ([], [])), shape=(self.lat.sites, self.lat.sites)) # Hamiltonian 

155 self.en = np.array([], 'c16') # Eigenenergies 

156 self.rn = np.array([], 'c16') # Right eigenvectors: H |rn> = en |rn> 

157 self.ln = np.array([], 'c16') # Left eigenvectors: <ln| H = en <ln| 

158 self.intensity = np.array([], 'f8') # Intensities (|rn|**2) 

159 self.pola = np.array([], 'f8') # sublattices polarisation (|rn^{(S)}|**2) 

160 self.ipr = np.array([], 'f8') # Inverse Participation Ratio 

161 self.petermann = np.array([], 'f8') # Petermann factors 

162 self.nmax = 0 # number of different hoppings 

163 

164 def clear_hopping(self) -> None: 

165 ''' 

166 Clear structured array *hop*. 

167 ''' 

168 self.hop = np.array([], dtype=HOP_DTYPE) 

169 self._hop_values = [] 

170 

171 def get_distances(self, n_orders: int = 1) -> None: 

172 ''' 

173 Private method. 

174 Get distances and angles of the edges. The angle is that of the 

175 bond's projection on the (x, y) plane; in 3D space, a vertical bond 

176 gets angle 0 pointing up (+z) and -180 pointing down. 

177 

178 Parameters 

179 ---------- 

180 n_orders : Positive integer, default 1 

181 Beyond *dense_max* 

182 sites, the number of neighbour orders (distinct distances) needed. 

183 ''' 

184 error_handling.sites(self.lat.sites) 

185 if self.lat.sites > self.dense_max: 

186 self._sparse_distances(n_orders) 

187 return 

188 self._pairs: NDArray | None = None 

189 if any(self.periodic): 

190 # shortest images, a block of rows at a time to bound the memory 

191 coords = self._coords() 

192 n = len(coords) 

193 d = np.empty((n, n, coords.shape[1])) 

194 step = max(1, 1000000 // n) 

195 for r0 in range(0, n, step): 

196 d[r0:r0 + step] = self._min_image(coords[None, :, :] - coords[r0:r0 + step, None, :]) 

197 dif = tuple(d[..., c] for c in range(d.shape[-1])) 

198 else: 

199 dif = self.lat.distances() 

200 dist = np.sqrt(sum(d ** 2 for d in dif)) 

201 ang = (180 / PI * np.arctan2(dif[1], dif[0])) 

202 if len(dif) == 3: 

203 # 'ang' is the angle of the bond's projection on the (x, y) plane. 

204 # A vertical bond has no such angle: orient it by dz instead, so 

205 # that the sign of 'ang' still tells the two directions apart. 

206 vertical = np.hypot(dif[0], dif[1]) < 1e-6 * np.maximum(dist, 1.) 

207 ang[vertical & (dif[2] > 0)] = 0. 

208 ang[vertical & (dif[2] <= 0)] = -180. 

209 self.vec_hop = np.zeros(dist.shape, dtype=[('dis', 'f8'), ('ang', 'f8')]) 

210 self.vec_hop['dis'] = dist 

211 self.vec_hop['ang'] = ang 

212 self.dist_uni = np.unique(self.vec_hop['dis'].round(4)) 

213 

214 def _coords(self) -> NDArray[np.float64]: 

215 ''' 

216 Private method. Site coordinates, shape (sites, space_dim). 

217 ''' 

218 return np.stack([self.lat.coor[f] for f in ('x', 'y', 'z')[:self.lat.space_dim]], axis=1) 

219 

220 def _box(self) -> NDArray[np.float64]: 

221 ''' 

222 Private method. The vectors n_i a_i of the sample of *get_lattice*, shape (dim, space_dim). 

223 ''' 

224 counts = np.array((self.lat.n1, self.lat.n2, self.lat.n3)[:len(self.lat.prim_vec)], dtype='f8') 

225 return counts[:, None] * np.array(self.lat.prim_vec, dtype='f8') 

226 

227 def _torus(self) -> NDArray[np.float64]: 

228 ''' 

229 Private method. The periodic vectors n_i a_i, shape (n_periodic, space_dim). 

230 ''' 

231 return self._box()[list(self.periodic)] 

232 

233 def _min_image(self, d: NDArray[np.float64]) -> NDArray[np.float64]: 

234 ''' 

235 Private method. Shortest images of displacements *d* (shape (..., space_dim)) 

236 under the periodic translations: the fractional coordinates along the 

237 periodic vectors are rounded, then the neighbouring images compared 

238 (rounding alone can miss the shortest one in a skewed cell). Only 

239 displacements longer than half the shortest period need that 

240 comparison: any other image of a shorter one is longer than it. 

241 ''' 

242 if not any(self.periodic): 

243 return d 

244 torus = self._torus() 

245 shape = d.shape 

246 d = d.reshape(-1, shape[-1]) # 2D, for fast matrix products 

247 frac = d @ np.linalg.pinv(self._box())[:, list(self.periodic)] 

248 d = d - np.rint(frac) @ torus 

249 sq = np.einsum('ij,ij->i', d, d) 

250 far = np.flatnonzero(sq > (self._shortest_period() / 2) ** 2) 

251 start = d[far] 

252 best, best_sq = start.copy(), sq[far] 

253 for m in product((-1, 0, 1), repeat=len(torus)): 

254 if any(m): 

255 cand = start + np.array(m, dtype='f8') @ torus 

256 cand_sq = np.einsum('ij,ij->i', cand, cand) 

257 shorter = cand_sq < best_sq - 1e-12 

258 best[shorter], best_sq[shorter] = cand[shorter], cand_sq[shorter] 

259 d[far] = best 

260 return d.reshape(shape) 

261 

262 def _bond_vectors(self, i: NDArray, j: NDArray) -> NDArray[np.float64]: 

263 ''' 

264 Private method. Bond vectors from sites *i* to sites *j*, shape 

265 (len(i), space_dim): the shortest image on a torus. 

266 ''' 

267 coords = self._coords() 

268 return self._min_image(coords[j] - coords[i]) 

269 

270 def _wrapped(self, i: NDArray, j: NDArray) -> NDArray: 

271 ''' 

272 Private method. Mask of the bonds i -> j that wrap around the torus 

273 (their shortest image is not the straight segment between the sites). 

274 ''' 

275 coords = self._coords() 

276 return np.linalg.norm(self._bond_vectors(i, j) - (coords[j] - coords[i]), axis=1) > ATOL 

277 

278 def _shortest_period(self) -> float: 

279 ''' 

280 Private method. Length of the shortest nonzero periodic translation 

281 (infinite with open boundaries). 

282 ''' 

283 if not any(self.periodic): 

284 return np.inf 

285 torus = self._torus() 

286 return min(np.linalg.norm(np.array(m, dtype='f8') @ torus) 

287 for m in product(range(-2, 3), repeat=len(torus)) if any(m)) 

288 

289 def _near_pairs(self, tree: cKDTree, coords: NDArray[np.float64], radius: float) -> NDArray: 

290 ''' 

291 Private method. Pairs i < j of sites closer than *radius* (shortest 

292 image on a torus, from the images of the sites under the periodic 

293 translations of -1, 0, +1 periods), sorted. 

294 ''' 

295 if not any(self.periodic): 

296 return tree.query_pairs(radius, output_type='ndarray') 

297 torus = self._torus() 

298 shifts = np.array(list(product((-1, 0, 1), repeat=len(torus))), dtype='f8') @ torus 

299 images = (coords[None, :, :] + shifts[:, None, :]).reshape(-1, coords.shape[1]) 

300 found = tree.sparse_distance_matrix(cKDTree(images), radius, output_type='ndarray') 

301 i, j = found['i'], found['j'] % len(coords) 

302 keep = i < j 

303 return np.unique(np.column_stack([i[keep], j[keep]]), axis=0).reshape(-1, 2) 

304 

305 def _sparse_distances(self, n_orders: int) -> None: 

306 ''' 

307 Private method. The pairs of sites up to the *n_orders*-th distinct 

308 distance (or all of them), from a k-d tree: the search radius grows 

309 until that many distinct distances are found, every pair within it 

310 being found. 

311 ''' 

312 coords = self._coords() 

313 tree = cKDTree(coords) 

314 near = tree.query(coords, k=2)[0][:, 1] 

315 radius = max(np.min(near[near > 1e-9]) if np.any(near > 1e-9) else 1., 1e-6) 

316 span = np.max(np.ptp(coords, axis=0)) * np.sqrt(coords.shape[1]) + radius 

317 while True: 

318 pairs = self._near_pairs(tree, coords, radius * (1. + 1e-6) + ATOL) 

319 dis = np.linalg.norm(self._bond_vectors(pairs[:, 0], pairs[:, 1]), axis=1) 

320 uni = np.unique(dis.round(4)) 

321 if len(uni) >= n_orders + 1 or radius > span: 

322 break 

323 radius *= 1.5 

324 self.vec_hop = np.array([], dtype=[('dis', 'f8'), ('ang', 'f8')]) 

325 self._pairs, self._pair_dis = pairs, dis 

326 # the (n+1)-th distance may be incomplete: keep the first n_orders 

327 self.dist_uni = np.concatenate([[0.], uni[:n_orders] if radius <= span else uni]) 

328 

329 def _angles(self, i: NDArray, j: NDArray) -> NDArray[np.float64]: 

330 ''' 

331 Private method. Angles (degrees) of the bonds from sites i to sites j, 

332 with the vertical-bond rule of *get_distances*. 

333 ''' 

334 d = self._bond_vectors(i, j) 

335 ang = 180 / PI * np.arctan2(d[:, 1], d[:, 0]) 

336 if d.shape[1] == 3: 

337 vertical = np.hypot(d[:, 0], d[:, 1]) < 1e-6 * np.maximum(np.linalg.norm(d, axis=1), 1.) 

338 ang[vertical & (d[:, 2] > 0)] = 0. 

339 ang[vertical & (d[:, 2] <= 0)] = -180. 

340 return ang 

341 

342 def print_distances(self, n: int = 1) -> None: 

343 r''' 

344 Print distances and positive angles (in degrees) :math:`\phi_+\in[0, 180)` 

345 of the nth shortest edges. Negative angles are given by: 

346 :math:`\phi_-= \phi_+-180` and :math:`\phi_-\in[-180, 0)`. 

347 

348 Parameters 

349 ---------- 

350 n : Positive integer 

351 Number of shortest edges. 

352 ''' 

353 error_handling.sites(self.lat.sites) 

354 error_handling.positive_int(n, 'n') 

355 self.get_distances(n) 

356 self.nmax = len(self.dist_uni) - 1 

357 error_handling.positive_int_lim(n, 'n', self.nmax) 

358 print('\n{} different distances between sites:'.format(self.nmax)) 

359 print('\nDistances between sites:') 

360 for i, d in enumerate(self.dist_uni[1: n+1]): 

361 if i == 0: 

362 hop_name = 'st' 

363 elif i == 1: 

364 hop_name = 'nd' 

365 elif i == 2: 

366 hop_name = 'rd' 

367 else: 

368 hop_name = 'th' 

369 print('{}{} hopping, length: {:.3f}'.format(i+1, hop_name, d)) 

370 print('\twith positive angles:') 

371 print('\t', np.unique(self.get_bonds(i + 1)[2].round(4))) 

372 

373 def set_onsite(self, dict_onsite: dict[str, complex]) -> None: 

374 ''' 

375 Set onsite energies. 

376 

377 Parameters 

378 ---------- 

379 dict_onsite : Dictionary 

380 key: sublattice tag, val: onsite 

381 energy, or a value function ``onsite(site, **params)``, evaluated 

382 by ``get_ham(**params)``. *site* is a structured array of the 

383 sites of that tag (fields 'x', 'y', ('z'), 'tag', 'index'); the 

384 function returns one energy, or one per site. *set_onsite_dis* 

385 adds to it. 

386 

387 Examples 

388 -------- 

389 Example usage:: 

390 

391 # Line-Centered Square lattice 

392 sys.set_onsite({'a': -1j, 'b': -2j}) 

393 # a gate voltage V across the sample, set by get_ham(V=...) 

394 sys.set_onsite({'a': lambda site, V: V * site['x'] / 10, 'b': 0.}) 

395 sys.get_ham(V=0.5) 

396 ''' 

397 error_handling.sites(self.lat.sites) 

398 error_handling.set_onsite(dict_onsite, self.lat.tags) 

399 self.onsite = np.zeros(self.lat.sites, 'c16') 

400 self._onsite_values = [] 

401 for tag, on in dict_onsite.items(): 

402 if callable(on): 

403 self._onsite_values.append((np.flatnonzero(self.lat.coor['tag'] == tag), on)) 

404 else: 

405 self.onsite[self.lat.coor['tag'] ==tag] = on 

406 

407 def get_bonds(self, n: int) -> tuple[NDArray, NDArray, NDArray]: 

408 ''' 

409 Private method. 

410 Get every bond of the nth shortest length once, oriented from *i* to *j* 

411 so that its angle lies in :math:`[0, 180)`. 

412 

413 The sign of *hop['ang']* is what marks a hopping as belonging to the 

414 upper or the lower part of the Hamiltonian (see *get_ham*). Sites sorted 

415 by (y, x), as *get_lattice* leaves them, give that orientation for 

416 :math:`i < j`, but *rotation*, *clean_coor*, *+=*, ... reorder the 

417 sites, so the orientation is taken from the angle itself. 

418 

419 Returns 

420 ------- 

421 i, j : Integer ndarrays 

422 Bond end points. 

423 ang : Real ndarray 

424 Bond angles, in degrees, in :math:`[0, 180)`. 

425 ''' 

426 error_handling.torus_size(self.dist_uni[n], self._shortest_period(), n) 

427 if self._pairs is not None: 

428 pairs = self._pairs[np.isclose(self.dist_uni[n], self._pair_dis, atol=ATOL)] 

429 pairs = pairs[np.lexsort((pairs[:, 1], pairs[:, 0]))] 

430 i, j = pairs[:, 0], pairs[:, 1] 

431 up = _upper(self._angles(i, j)) 

432 i, j = np.where(up, i, j), np.where(up, j, i) 

433 order = np.lexsort((j, i)) 

434 i, j = i[order], j[order] 

435 return i, j, np.maximum(self._angles(i, j), 0.) 

436 ind = np.argwhere(np.isclose(self.dist_uni[n], self.vec_hop['dis'], atol=ATOL)) 

437 ind = ind[_upper(self.vec_hop['ang'][ind[:, 0], ind[:, 1]])] 

438 ang = np.maximum(self.vec_hop['ang'][ind[:, 0], ind[:, 1]], 0.) 

439 return ind[:, 0], ind[:, 1], ang 

440 

441 def fill_store_hop(self, n: int) -> None: 

442 ''' 

443 Private method. 

444 

445 Store in *store_hop* indices, positive angles, and tags 

446 of a given type of hopping (see *get_bonds*). 

447 ''' 

448 i, j, ang = self.get_bonds(n) 

449 hop = np.zeros(len(i), dtype=HOP_DTYPE[:-1]) 

450 hop['i'] = i 

451 hop['j'] = j 

452 hop['ang'] = ang 

453 hop['tag'] = npc.add(self.lat.coor['tag'][i], self.lat.coor['tag'][j]) 

454 self.store_hop[n] = hop 

455 

456 def set_hopping(self, list_hop: list[dict], upper_part: bool = True) -> None: 

457 r''' 

458 Set lattice hoppings. 

459 

460 Parameters 

461 ---------- 

462 list_hop : List of Dictionaries 

463 Dictionary with keys ('n', 'ang', 'tag', 't') where: 

464 

465 * 'n' Positive integer, type of hoppings: 

466 

467 * 'n': 1 for nearest neighbours. 

468 * 'n': 2 for next-nearest neighbours.  

469 * 'n': 3 for next-next-nearest neighbours.  

470 * etc... 

471 

472 * 'ang' value, float, angle, in deg, of the hoppings. (optional). 

473 

474 Hopping angles are given by the method *print_distances*. 

475 

476 * If :math:`ang \in[0, 180)`, fill the Hamiltonian upper part. 

477 * If :math:`ang \in[-180, 0)`, fill the Hamiltonian lower part. 

478 

479 * 'tag' string of two one-character tags (``'ab'``), or a 

480 pair of tags (``('Mo', 'S')``) (optional). 

481 

482 Hopping tags: bonds from a site of the first sublattice 

483 to one of the second (stored as ``tag_i + tag_j``). 

484 

485 * 't' Complex number, or value function. 

486 

487 Hopping value. A value function ``t(site_i, site_j, **params)`` 

488 is evaluated by ``get_ham(**params)``: *site_i* and *site_j* 

489 are structured arrays of the bonds' end points (fields 'x', 

490 'y', ('z'), 'tag', 'index'), and it returns one value, or 

491 one per bond (see the example below). Modifiers applied 

492 afterwards (*set_peierls_phase*, *set_hopping_dis*, ...) 

493 multiply it. 

494 upper_part : Boolean, default True 

495 * True, get the hoppings with angles in :math:`[0, 180)`, *i.e.* fill 

496 the Hamiltonian upper part. 

497 * False, get the reversed hoppings, with angles in :math:`[-180, 0)`, 

498 *i.e.* fill the Hamiltonian lower part. 

499 

500 Examples 

501 -------- 

502 Example usage:: 

503 

504 # fill upper part: 

505 sys.set_hopping([{'n': 1, 't': 1.}]) 

506 # fill lower part: 

507 sys.set_hopping([{'n': 1, 't': 1.}], upper_part=False) 

508 # fill upper part: specifying the angles: 

509 sys.set_hopping([{'n': 1, 'ang': 0., 't': 1.}, {'n': 1, 'ang': 90., 't': 2.}]) 

510 # fill lower part: 

511 sys.set_hopping([{'n': 1, 'ang': -180., 't': 1.}, {'n': 1, 'ang': -90., 't': 2.}], 

512 upper_part=False) 

513 # fill upper part: specifying the tags: 

514 sys.set_hopping([{'n': 1, 'tag': 'ab', 't': 1.}, {'n': 1, 'tag': 'ba', 't': 2.}]) 

515 # fill lower part: 

516 sys.set_hopping([{'n': 1, 'tag': 'ab', 't': 1.}, {'n': 1, 'tag': 'ba', 't': 2.}], 

517 upper_part=False) 

518 # fill upper part: specifying the angles and tags: 

519 sys.set_hopping([{'n': 1, 'ang': 0., 'tag': 'ab', 't': 1.}, 

520 {'n': 1, 'ang': 0., 'tag': 'ba', 't': 2.}, 

521 {'n': 1, 'ang': 90., 'tag': 'ab', 't': 3.}, 

522 {'n': 1, 'ang': 90., 'tag': 'ba', 't': 4.}]) 

523 # fill lower part: 

524 sys.set_hopping([{'n': 1, 'ang': -180., 'tag': 'ab', 't': 1.}, 

525 {'n': 1, 'ang': -180., 'tag': 'ba', 't': 2.}, 

526 {'n': 1, 'ang': -90., 'tag': 'ab', 't': 3.}, 

527 {'n': 1, 'ang': -90., 'tag': 'ba', 't': 4.}], 

528 upper_part=False) 

529 # value function: a hopping that decays along x, swept without 

530 # rebuilding the model 

531 sys.set_hopping([{'n': 1, 't': lambda si, sj, t0, xi: t0 * np.exp(-si['x'] / xi)}]) 

532 for xi in (5., 10., 20.): 

533 sys.get_ham(t0=1., xi=xi) 

534 

535 .. note:: 

536 

537 A Hermitian hopping matrix can be built using only 

538 its upper part OR only its lower part. The full matrix is then 

539 built automatically by Hermitian conjugation. 

540 

541 If both the upper AND the lower parts are used to build the hopping 

542 matrix, no Hermitian conjugation is performed, *i.e.* a non-Hermitian 

543 hopping matrix can be built. 

544 ''' 

545 error_handling.sites(self.lat.sites) 

546 error_handling.boolean(upper_part, 'upper_part') 

547 self.get_distances(error_handling.max_order(list_hop)) 

548 self.nmax = len(self.dist_uni) - 1 

549 error_handling.set_hopping(list_hop, self.nmax) 

550 list_n = np.unique([dic['n'] for dic in list_hop]) 

551 # fill, if needed self.store_hop 

552 self.check_sites() 

553 for n in list_n: 

554 if n not in self.store_hop: 

555 self.fill_store_hop(n) 

556 # fill self.hop 

557 for dic in list_hop: 

558 if len(dic) == 2: 

559 size = len(self.store_hop[dic['n']]) 

560 if upper_part: 

561 mask = (self.hop['n'] == dic['n']) & (self.hop['ang'] >= 0) 

562 else: 

563 mask = (self.hop['n'] == dic['n']) & (self.hop['ang'] < 0) 

564 if np.sum(mask): 

565 self.hop = self.hop[np.logical_not(mask)] 

566 ind = np.ones(size, bool) 

567 hop = self.set_given_hopping(dic['n'], size, dic, ind, upper_part=upper_part) 

568 elif len(dic) == 3 and 'ang' in dic: 

569 error_handling.angle(dic['ang'], np.unique(self.store_hop[dic['n']]['ang']), upper_part) 

570 if dic['ang'] >= 0: 

571 ang_store = dic['ang'] 

572 else: 

573 ang_store = dic['ang'] + 180. 

574 size = np.sum(np.isclose(ang_store, self.store_hop[dic['n']]['ang'], atol=ATOL)) 

575 mask = (self.hop['n'] == dic['n']) & np.isclose(self.hop['ang'], dic['ang'], atol=ATOL) 

576 if np.sum(mask): 

577 self.hop = self.hop[np.logical_not(mask)] 

578 ind = np.isclose(ang_store, self.store_hop[dic['n']]['ang'], atol=ATOL) 

579 error_handling.index(ind, dic) 

580 hop = self.set_given_hopping(dic['n'], size, dic, ind, upper_part=upper_part) 

581 elif len(dic) == 3 and 'tag' in dic: 

582 pair = _tag_pair(dic['tag']) 

583 if upper_part: 

584 tag_store = pair 

585 else: 

586 tag_store = pair[::-1] 

587 size = np.sum(self._tag_mask(self.store_hop[dic['n']], tag_store)) 

588 mask = ((self.hop['n'] == dic['n']) & self._tag_mask(self.hop, pair)) 

589 if upper_part: 

590 mask &= self.hop['ang'] >= 0 

591 else: 

592 mask &= self.hop['ang'] < 0 

593 if np.sum(mask): 

594 self.hop = self.hop[np.logical_not(mask)] 

595 ind = self._tag_mask(self.store_hop[dic['n']], tag_store) 

596 error_handling.index(ind, dic) 

597 hop = self.set_given_hopping(dic['n'], size, dic, ind, upper_part=upper_part) 

598 else: 

599 error_handling.angle(dic['ang'], np.unique(self.store_hop[dic['n']]['ang']), upper_part=upper_part) 

600 pair = _tag_pair(dic['tag']) 

601 error_handling.tag(''.join(pair), np.unique(self.store_hop[dic['n']]['tag'])) 

602 if dic['ang'] >= 0: 

603 ang_store = dic['ang'] 

604 else: 

605 ang_store = dic['ang'] + 180. 

606 if upper_part: 

607 tag_store = pair 

608 else: 

609 tag_store = pair[::-1] 

610 size = np.sum(self._tag_mask(self.store_hop[dic['n']], tag_store) & 

611 (np.isclose(ang_store, self.store_hop[dic['n']]['ang'], atol=ATOL))) 

612 bool1 = (self.hop['n'] == dic['n']) & self._tag_mask(self.hop, pair) 

613 bool2 = np.isclose(self.hop['ang'], dic['ang'], atol=ATOL) 

614 mask = bool1 & bool2 

615 if np.sum(mask): 

616 self.hop = self.hop[np.logical_not(mask)] 

617 ind = (self._tag_mask(self.store_hop[dic['n']], tag_store) & 

618 (np.isclose(ang_store, self.store_hop[dic['n']]['ang'], atol=ATOL))) 

619 error_handling.index(ind, dic) 

620 hop = self.set_given_hopping(dic['n'], size, dic, ind, upper_part=upper_part) 

621 self.hop = np.concatenate([self.hop, hop]) 

622 self._assign_hopping(np.arange(len(self.hop) - len(hop), len(self.hop)), dic['t']) 

623 

624 def _tag_mask(self, hop: NDArray, pair: tuple[str, str]) -> NDArray: 

625 ''' 

626 Private method. Mask of the bonds of *hop* from a site tagged 

627 *pair[0]* to a site tagged *pair[1]* (exact for tags of any length, 

628 unlike a match on the concatenated ``hop['tag']``). 

629 ''' 

630 tags = self.lat.coor['tag'] 

631 return (tags[hop['i']] == pair[0]) & (tags[hop['j']] == pair[1]) 

632 

633 def check_sites(self) -> None: 

634 ''' 

635 Private method. 

636 Check if the number of sites was changed after calling the  

637 method system.set_hopping(). 

638 ''' 

639 if self.sites != self.lat.sites: 

640 self.store_hop = {} 

641 self.sites = self.lat.sites 

642 

643 def set_given_hopping( 

644 self, n: int, size: int, dic: dict, mask: NDArray, upper_part: bool, 

645 ) -> NDArray: 

646 ''' 

647 Private method. 

648 Fill self.hop.  

649 

650 Parameters 

651 ---------- 

652 n : Integer 

653 Hopping type. 

654 size : Integer 

655 Number of hoppings. 

656 dic : Dictionary 

657 Hopping dictionary. 

658 mask : np.ndarray 

659 Mask. 

660 upper_part : Boolean 

661 If True, keep the orientation of *store_hop* 

662 (angles in [0, 180)), else reverse it. 

663 ''' 

664 hop = np.empty(size, dtype=HOP_DTYPE) 

665 hop['n'] = dic['n'] 

666 hop['t'] = 1. if callable(dic['t']) else dic['t'] 

667 if upper_part: 

668 hop['i'] = self.store_hop[n]['i'][mask] 

669 hop['j'] = self.store_hop[n]['j'][mask] 

670 hop['ang'] = self.store_hop[n]['ang'][mask] 

671 hop['tag'] = self.store_hop[n]['tag'][mask] 

672 else: 

673 hop['i'] = self.store_hop[n]['j'][mask] 

674 hop['j'] = self.store_hop[n]['i'][mask] 

675 hop['ang'] = self.store_hop[n]['ang'][mask] - 180 

676 hop['tag'] = npc.add(self.lat.coor['tag'][hop['i']], 

677 self.lat.coor['tag'][hop['j']]) 

678 return hop 

679 

680 def set_hopping_manual(self, dict_hop: dict[tuple[int, int], complex], upper_part: bool = True) -> None: 

681 ''' 

682 Set hoppings manually. 

683 

684 Parameters 

685 ---------- 

686 dict_hop : Dictionary of hoppings 

687 key: hopping indices, val: hopping values. 

688 upper_part : Boolean, default True 

689 * True, fill the Hamiltonian upper part. 

690 * False, fill the Hamiltonian lower part. 

691 

692 Examples 

693 -------- 

694 Example usage:: 

695 

696 sys.set_hopping_manual({(0, 1): 1., (1, 2): 2.}) 

697 ''' 

698 error_handling.sites(self.lat.sites) 

699 error_handling.set_hopping_def(None, dict_hop, self.lat.sites, 'dict_hop', same_site=True) 

700 hop = np.zeros(len(dict_hop), dtype=HOP_DTYPE) 

701 i = [h[0] for h in dict_hop.keys()] 

702 j = [h[1] for h in dict_hop.keys()] 

703 t = [val for val in dict_hop.values()] 

704 hop['i'], hop['j']= i, j 

705 hop['t'] = t 

706 hop['tag'] = npc.add(self.lat.coor['tag'][i], 

707 self.lat.coor['tag'][j]) 

708 d = self._bond_vectors(np.array(i, int), np.array(j, int)) 

709 ang = 180 / PI * np.arctan2(d[:, 1], d[:, 0]) 

710 if upper_part: 

711 ang[ang < 0] += 180 

712 else: 

713 ang[ang >= 0] -= 180 

714 hop['ang'] = ang 

715 self.hop = np.concatenate([self.hop, hop]) 

716 self._assign_hopping(np.arange(len(self.hop) - len(hop), len(self.hop)), hop['t']) 

717 

718 def _assign_hopping(self, rows: NDArray, t) -> None: 

719 ''' 

720 Private method. Set the values of the rows *rows* (indices or mask) 

721 of *hop* to *t*: number(s), or a value function (the rows then hold 

722 the factor 1). It replaces any value function set on the same bonds. 

723 ''' 

724 keys = self._bond_keys(rows) 

725 self._hop_values = [(k[~np.isin(k, keys)], f) for k, f in self._hop_values] 

726 self._hop_values = [(k, f) for k, f in self._hop_values if k.size] 

727 if callable(t): 

728 self.hop['t'][rows] = 1. 

729 self._hop_values.append((keys, t)) 

730 else: 

731 self.hop['t'][rows] = t 

732 

733 def _bond_keys(self, rows: NDArray | slice) -> NDArray[np.int64]: 

734 ''' 

735 Private method. One integer per directed bond (i, j) of the rows *rows* of *hop*. 

736 ''' 

737 return (self.hop['i'][rows].astype('i8') << 32) | self.hop['j'][rows].astype('i8') 

738 

739 def _sites(self) -> NDArray: 

740 ''' 

741 Private method. All the sites, as passed to value functions (see *tbkit.values.sites*). 

742 ''' 

743 return values.sites(self._coords(), self.lat.coor['tag'], np.arange(self.lat.sites)) 

744 

745 def _hop_t(self, params: dict) -> NDArray[np.complex128]: 

746 ''' 

747 Private method. The hopping values of *hop*, value functions evaluated with *params*. 

748 ''' 

749 t = self.hop['t'].copy() 

750 if not self._hop_values: 

751 return t 

752 keys, sites = self._bond_keys(slice(None)), self._sites() 

753 for k, func in self._hop_values: 

754 rows = np.flatnonzero(np.isin(keys, k)) 

755 t[rows] *= values.evaluate(func, (sites[self.hop['i'][rows]], sites[self.hop['j'][rows]]), 

756 params, len(rows)) 

757 return t 

758 

759 def _onsite_e(self, params: dict) -> NDArray[np.complex128]: 

760 ''' 

761 Private method. The onsite energies, value functions evaluated with *params*. 

762 ''' 

763 onsite = self.onsite.copy() 

764 if self._onsite_values: 

765 sites = self._sites() 

766 for idx, func in self._onsite_values: 

767 onsite[idx] += values.evaluate(func, (sites[idx],), params, len(idx)) 

768 return onsite 

769 

770 def set_hopping_dis(self, alpha: complex) -> None: 

771 ''' 

772 Set uniform hopping disorder.  

773 

774 Parameters 

775 ---------- 

776 alpha : Complex or Real number 

777 Disorder strength. 

778 

779 Examples 

780 -------- 

781 Example usage:: 

782 

783 sys.set_hopping_dis(alpha=0.1) 

784 ''' 

785 error_handling.empty_hop(self.hop) 

786 error_handling.number(alpha, 'alpha') 

787 self.hop['t'] *= 1. + alpha * rand.uniform(-1., 1., len(self.hop)) 

788 

789 def set_peierls_phase(self, phase: Callable[..., NDArray]) -> None: 

790 r''' 

791 Apply the Peierls substitution to the existing hoppings, to 

792 capture the effect of an orbital magnetic field: 

793 

794 .. math:: 

795 

796 t_{ij} \to t_{ij}\, e^{i\phi_{ij}}\, ,\quad 

797 \phi_{ij} = \frac{2\pi}{\Phi_0}\int_{\mathbf{r}_i}^{\mathbf{r}_j} 

798 \mathbf{A}\cdot d\mathbf{l} 

799 

800 where :math:`\mathbf{A}` is the vector potential, integrated along 

801 the straight bond from site :math:`i` to site :math:`j`. 

802 

803 Must be called after *set_hopping* / *set_hopping_manual* (it 

804 rescales the existing hoppings *in place*) and before *get_ham*. 

805 For a uniform perpendicular field, use the convenience method 

806 *set_magnetic_field* instead. 

807 

808 Parameters 

809 ---------- 

810 phase : Callable 

811 ``phase(xi, yi, xj, yj)`` returns 

812 :math:`\phi_{ij}`, the (real-valued) Peierls phase for the bond 

813 from :math:`(x_i, y_i)` to :math:`(x_j, y_j)`. Called with 

814 Numpy arrays (one value per hopping in *sys.hop*). With periodic 

815 boundaries, :math:`(x_j, y_j)` is the end of the short bond, i.e. 

816 the image of site :math:`j` next to site :math:`i`, which lies 

817 outside the sample for a bond that wraps around. The vector 

818 potential must then be consistent with the torus: periodic (a 

819 field of zero net flux), or uniform (a flux threading the holes 

820 of the torus, i.e. twisted boundary conditions). 

821 

822 Notes 

823 ----- 

824 .. note:: 

825 

826 *get_ham* automatically assigns the reversed bond its complex 

827 conjugate, so the Hamiltonian stays Hermitian as long as 

828 *phase* is antisymmetric under swapping :math:`i` and 

829 :math:`j` -- true for the line integral of any vector 

830 potential, since reversing the integration path negates it. 

831 

832 Examples 

833 -------- 

834 Example usage:: 

835 

836 # Peierls phase from a uniform field via the Landau gauge 

837 # A = (0, B x): the same field as set_magnetic_field(alpha), 

838 # just in a different (equally valid) gauge. 

839 alpha = 0.01 

840 sys.set_peierls_phase(lambda xi, yi, xj, yj: 

841 2 * np.pi * alpha * (yj - yi) * (xi + xj) / 2) 

842 ''' 

843 error_handling.empty_hop(self.hop) 

844 error_handling.is_callable(phase, 'phase') 

845 xi = self.lat.coor['x'][self.hop['i']] 

846 yi = self.lat.coor['y'][self.hop['i']] 

847 d = self._bond_vectors(self.hop['i'].astype(int), self.hop['j'].astype(int)) 

848 xj, yj = xi + d[:, 0], yi + d[:, 1] 

849 self.hop['t'] = self.hop['t'] * np.exp(1j * phase(xi, yi, xj, yj)) 

850 

851 def set_magnetic_field(self, alpha: float) -> None: 

852 r''' 

853 Set a uniform perpendicular magnetic field via the Peierls 

854 substitution (see *set_peierls_phase*), using the symmetric gauge 

855 :math:`\mathbf{A} = \frac{B}{2}(-y, x)`: 

856 

857 .. math:: 

858 

859 \phi_{ij} = \pi\alpha\,(x_iy_j - x_jy_i) 

860 

861 Parameters 

862 ---------- 

863 alpha : Real number 

864 Flux density :math:`B/\Phi_0`, in flux 

865 quanta per unit area (in the lattice's length units) -- *i.e.* 

866 the flux through a region of area :math:`S` is 

867 :math:`\alpha S` flux quanta. 

868 

869 Examples 

870 -------- 

871 Example usage:: 

872 

873 # one flux quantum per 100 unit cells of a lattice with 

874 # lattice constant 1: 

875 sys.set_magnetic_field(alpha=0.01) 

876 

877 Open boundaries only: on a torus the symmetric gauge is not 

878 periodic, and a uniform field needs a quantized total flux and 

879 magnetic boundary conditions. 

880 ''' 

881 error_handling.not_periodic(self.periodic, 'set_magnetic_field') 

882 error_handling.real_number(alpha, 'alpha') 

883 self.set_peierls_phase(lambda xi, yi, xj, yj: PI * alpha * (xi*yj - xj*yi)) 

884 

885 def set_onsite_dis(self, alpha: complex) -> None: 

886 ''' 

887 Set uniform onsite disorder.  

888 

889 Parameters 

890 ---------- 

891 alpha : Complex or Real number 

892 Disorder strength. 

893 

894 Examples 

895 -------- 

896 Example usage:: 

897 

898 sys.set_onsite_dis(alpha=0.1) 

899 ''' 

900 error_handling.empty_onsite(self.onsite) 

901 error_handling.number(alpha, 'alpha') 

902 self.onsite += alpha * rand.uniform(-1., 1., self.lat.sites) 

903 

904 def set_onsite_def(self, onsite_def: dict[int, complex]) -> None: 

905 ''' 

906 Set specific onsite energies. 

907 

908 Parameters 

909 ---------- 

910 onsite_def : Dictionary 

911 key: site indices, val: onsite values. 

912 

913 Examples 

914 -------- 

915 Example usage:: 

916 

917 sys.set_onsite_def({0: 1., 1: -1j}) 

918 ''' 

919 error_handling.empty_onsite(self.onsite) 

920 error_handling.set_onsite_def(onsite_def, self.lat.sites) 

921 for i, o in onsite_def.items(): 

922 self.onsite[i] = o 

923 self._onsite_values = [(idx[~np.isin(idx, list(onsite_def))], f) for idx, f in self._onsite_values] 

924 

925 def set_hopping_def(self, hopping_def: dict[tuple[int, int], complex]) -> None: 

926 ''' 

927 Set specific hoppings.  

928 

929 Parameters 

930 ---------- 

931 hopping_def : Dictionary of hoppings 

932 key: hopping indices :math:`(i, j)`, val: hopping value :math:`t_{ij}`. 

933 If *sys.hop* stores the bond the other way round, as :math:`(j, i)` 

934 (only one direction is stored for a Hermitian Hamiltonian), that 

935 entry is set to :math:`t_{ij}^*`, so that :math:`H_{ij} = t_{ij}`. 

936 A pair that is not a hopping of *sys.hop* is ignored. 

937 

938 Examples 

939 -------- 

940 Example usage:: 

941 

942 sys.set_hopping_def({(0, 1): 1., (1, 2): -1j}) 

943 ''' 

944 error_handling.empty_hop(self.hop) 

945 error_handling.set_hopping_def(self.hop, hopping_def, self.lat.sites) 

946 for key, val in hopping_def.items(): 

947 cond = (self.hop['i'] == key[0]) & (self.hop['j'] == key[1]) 

948 if cond.any(): 

949 self._assign_hopping(cond, val) 

950 continue 

951 cond = (self.hop['i'] == key[1]) & (self.hop['j'] == key[0]) 

952 self._assign_hopping(cond, np.conj(val)) 

953 

954 def set_new_hopping(self, list_hop: list[dict], ind: NDArray) -> None: 

955 ''' 

956 Private method. 

957 Set new hoppings. 

958 

959 Parameters 

960 ---------- 

961 list_hop : List of Dictionary (see set_hopping definition) 

962 ind : List 

963 List of indices. 

964 ''' 

965 for dic in list_hop: 

966 if len(dic) == 2: 

967 self._assign_hopping(ind, dic['t']) 

968 elif len(dic) == 3 and 'ang' in dic: 

969 self._assign_hopping(ind & np.isclose(self.hop['ang'], dic['ang'], atol=ATOL), dic['t']) 

970 elif len(dic) == 3 and 'tag' in dic: 

971 self._assign_hopping(ind & self._tag_mask(self.hop, _tag_pair(dic['tag'])), dic['t']) 

972 else: 

973 self._assign_hopping(ind & self._tag_mask(self.hop, _tag_pair(dic['tag'])) 

974 & np.isclose(self.hop['ang'], dic['ang'], atol=ATOL), dic['t']) 

975 

976 def find_square(self, xlims: tuple[float, float], ylims: tuple[float, float]) -> NDArray: 

977 ''' 

978 Private method. 

979 Find hoppings within the square. 

980 

981 Parameters 

982 ---------- 

983 xlims : List or Tuple 

984 :math:`x` interval. 

985 ylims : List or Tuple 

986 :math:`y` interval. 

987 ''' 

988 error_handling.lims(xlims) 

989 error_handling.lims(ylims) 

990 in1 = (self.lat.coor['x'][self.hop['i']] >= xlims[0]) & \ 

991 (self.lat.coor['y'][self.hop['i']] >= ylims[0]) & \ 

992 (self.lat.coor['x'][self.hop['j']] >= xlims[0]) & \ 

993 (self.lat.coor['y'][self.hop['j']] >= ylims[0]) 

994 in2 = (self.lat.coor['x'][self.hop['i']] <= xlims[1]) & \ 

995 (self.lat.coor['y'][self.hop['i']] <= ylims[1]) & \ 

996 (self.lat.coor['x'][self.hop['j']] <= xlims[1]) & \ 

997 (self.lat.coor['y'][self.hop['j']] <= ylims[1]) 

998 return in1 * in2 

999 

1000 def find_ellipse(self, rx: float, ry: float, x0: float, y0: float) -> NDArray: 

1001 ''' 

1002 Private method. 

1003 Find hoppings within the ellipse. 

1004 

1005 Parameters 

1006 ---------- 

1007 rx : Positive Float 

1008 Radius along :math:`x`. 

1009 ry : Positive Float 

1010 Radius along :math:`y`. 

1011 x0 : Float, default 0 

1012 :math:`x` center. 

1013 y0 : Float, default 0 

1014 :math:`y` center. 

1015 ''' 

1016 in1 = (self.lat.coor['x'][self.hop['i']] - x0) ** 2 / rx ** 2 + \ 

1017 (self.lat.coor['y'][self.hop['i']] - y0) ** 2 / ry ** 2 <= 1. 

1018 in2 = (self.lat.coor['x'][self.hop['j']] - x0) ** 2 / rx ** 2 + \ 

1019 (self.lat.coor['y'][self.hop['j']] - y0) ** 2 / ry ** 2 <= 1. 

1020 return in1 * in2 

1021 

1022 def change_hopping_square( 

1023 self, list_hop: list[dict], xlims: tuple[float, float], ylims: tuple[float, float] = (-1., 1.), 

1024 ) -> None: 

1025 ''' 

1026 Change the values of the hoppings whose two sites both lie in 

1027 the rectangle *xlims* x *ylims*. 

1028 

1029 Parameters 

1030 ---------- 

1031 list_hop : List of Dictionary (see set_hopping definition) 

1032 xlims : List or Tuple 

1033 :math:`x` interval. 

1034 ylims : List or Tuple, default [-1, 1] 

1035 :math:`y` interval. 

1036 ''' 

1037 error_handling.empty_hop(self.hop) 

1038 error_handling.set_hopping(list_hop, self.nmax) 

1039 ind = self.find_square(xlims, ylims) 

1040 self.set_new_hopping(list_hop, ind) 

1041 

1042 def change_hopping_ellipse( 

1043 self, list_hop: list[dict], rx: float, ry: float, x0: float = 0., y0: float = 0., 

1044 ) -> None: 

1045 ''' 

1046 Change the values of the hoppings whose two sites both lie in 

1047 the ellipse of radii *rx*, *ry* centered at (*x0*, *y0*). 

1048 

1049 Parameters 

1050 ---------- 

1051 list_hop : List of Dictionary (see set_hopping definition) 

1052 rx : Positive Float 

1053 Radius along :math:`x`. 

1054 ry : Positive Float 

1055 Radius along :math:`y`. 

1056 x0 : Float, default 0 

1057 :math:`x` center. 

1058 y0 : Float, default 0 

1059 :math:`y` center. 

1060 ''' 

1061 error_handling.empty_hop(self.hop) 

1062 error_handling.set_hopping(list_hop, self.nmax) 

1063 error_handling.positive_real(rx, 'rx') 

1064 error_handling.positive_real(ry, 'ry') 

1065 error_handling.real_number(x0, 'x0') 

1066 error_handling.real_number(y0, 'y0') 

1067 ind = self.find_ellipse(rx, ry, x0, y0) 

1068 self.set_new_hopping(list_hop, ind) 

1069 

1070 def get_coor_hop(self) -> None: 

1071 ''' 

1072 Get the site coordinates in hopping space 

1073 only considering the nearest neighbours hoppings. 

1074 ''' 

1075 error_handling.empty_hop(self.hop) 

1076 visited = np.zeros(self.lat.sites, 'u2') 

1077 self.coor_hop = np.zeros(self.lat.sites, dtype=COOR_DTYPE) 

1078 self.coor_hop['tag'] = self.lat.coor['tag'] 

1079 hop = self.hop[self.hop['n'] == 1] 

1080 hop_down = np.copy(hop) 

1081 hop_down['i'] = hop['j'] 

1082 hop_down['j'] = hop[ 'i'] 

1083 hop_down['ang'] = -180 + hop['ang'] 

1084 hop = np.concatenate([hop, hop_down]) 

1085 i_visit = np.min(hop['i']) 

1086 while True: 

1087 hs = hop[hop['i'] == i_visit] 

1088 for h in hs: 

1089 if visited[h['j']] == 2: 

1090 continue 

1091 self.coor_hop['x'][h['j']] = self.coor_hop['x'][i_visit] + \ 

1092 h['t'].real*cos(PI / 180 * h['ang']) 

1093 self.coor_hop['y'][h['j']] = self.coor_hop['y'][i_visit] + \ 

1094 h['t'].real*sin(PI / 180 * h['ang']) 

1095 visited[h['j']] = 1 

1096 visited[i_visit] = 2 

1097 explored = np.argwhere(visited == 1) 

1098 if not explored.any(): 

1099 break 

1100 i_visit = explored[0, 0] 

1101 

1102 def get_ham(self, **params) -> None: 

1103 ''' 

1104 Get the Tight-Binding Hamiltonian using sys.hop. 

1105 

1106 Parameters 

1107 ---------- 

1108 params 

1109 Values of the parameters of the value functions given 

1110 to *set_hopping* / *set_onsite*: each function gets the ones its 

1111 signature names (all of them with ``**kwargs``); the others are 

1112 ignored. Only the values are recomputed: sweeping a parameter 

1113 costs one call per point, not a new model. 

1114 

1115 Examples 

1116 -------- 

1117 Example usage:: 

1118 

1119 for B in np.linspace(0., 0.1, 50): 

1120 sys.get_ham(B=B) 

1121 sys.get_eig() 

1122 ''' 

1123 error_handling.empty_hop(self.hop) 

1124 error_handling.hop_sites(self.hop, self.lat.sites) 

1125 t = self._hop_t(params) 

1126 if np.all(self.hop['ang'] >= 0) or np.all(self.hop['ang'] < 0): 

1127 self.ham = sparse.csr_matrix((t, (self.hop['i'], self.hop['j'])), 

1128 shape=(self.lat.sites, self.lat.sites)) \ 

1129 + sparse.csr_matrix((t.conj(), (self.hop['j'], self.hop['i'])), 

1130 shape=(self.lat.sites, self.lat.sites)) 

1131 else: 

1132 self.ham = sparse.csr_matrix((t, (self.hop['i'], self.hop['j'])), 

1133 shape=(self.lat.sites, self.lat.sites)) 

1134 if self.onsite.size == self.lat.sites: 

1135 self.ham += sparse.diags(self._onsite_e(params), 0) 

1136 

1137 def get_eig(self, eigenvec: bool = False, left: bool = False) -> None: 

1138 ''' 

1139 Get the eigenergies, eigenvectors and polarisation. 

1140 

1141 Parameters 

1142 ---------- 

1143 eigenvec : Boolean, default False 

1144 If True, get the eigenvectors. 

1145 left : Boolean, default False 

1146 If True, get the left eigenvectors too.  

1147 Relevant for non-Hermitian matrices. 

1148 ''' 

1149 error_handling.empty_ham(self.ham) 

1150 error_handling.boolean(eigenvec, 'eigenvec') 

1151 error_handling.boolean(left, 'left') 

1152 # Drop any left eigenvectors from a previous call: they belong to the 

1153 # previous diagonalization and must not be re-sorted with this one's 

1154 # ordering (get_petermann would then pair the wrong vectors). 

1155 self.ln = np.array([], 'c16') 

1156 if eigenvec: 

1157 if (self.ham.conj().T != self.ham).nnz: 

1158 if not left: 

1159 self.en, self.rn = LA.eig(self.ham.toarray()) 

1160 else: 

1161 # scipy.linalg.eig returns (w, vl, vr) -- the LEFT 

1162 # eigenvectors come back before the right ones. 

1163 self.en, self.ln, self.rn = LA.eig(self.ham.toarray(), left=left) 

1164 ind = np.argsort(self.en.real) 

1165 self.en = self.en[ind] 

1166 self.rn = self.rn[:, ind] 

1167 if self.ln.size: 

1168 self.ln = self.ln[:, ind] 

1169 else: 

1170 self.en, self.rn = LA.eigh(self.ham.toarray()) 

1171 self._set_states() 

1172 else: 

1173 if (self.ham.conj().T != self.ham).nnz: 

1174 self.en = LA.eigvals(self.ham.toarray()) 

1175 ind = np.argsort(self.en.real) 

1176 self.en = self.en[ind] 

1177 else: 

1178 ham = self.ham.toarray() 

1179 # A real symmetric matrix (no fluxes, no spin-orbit) has the same 

1180 # eigenvalues from the real solver, about twice as fast. 

1181 if not ham.imag.any(): 

1182 ham = ham.real 

1183 self.en = LA.eigvalsh(ham) 

1184 

1185 def _set_states(self) -> None: 

1186 ''' 

1187 Private method. Intensities and sublattice polarizations of the 

1188 eigenvectors *rn*. 

1189 ''' 

1190 self.intensity = np.abs(self.rn) ** 2 

1191 self.pola = np.zeros((self.rn.shape[1], len(self.lat.tags))) 

1192 for i, tag in enumerate(self.lat.tags): 

1193 self.pola[:, i] = np.sum(self.intensity[self.lat.coor['tag'] == tag, :], axis=0) 

1194 

1195 def get_eig_sparse(self, n_eig: int = 10, sigma: complex = 0., eigenvec: bool = False) -> None: 

1196 r''' 

1197 Get the *n_eig* eigenenergies closest to *sigma*, and optionally 

1198 their eigenvectors, with the sparse shift-invert Lanczos (Hermitian) 

1199 or Arnoldi (non-Hermitian) solver of ARPACK. Unlike *get_eig*, it 

1200 never builds the dense matrix, so it reaches lattices of 

1201 :math:`10^5` sites and more -- e.g. the states near a band centre, or 

1202 the zero modes of a large flake. The results replace *en* (sorted by 

1203 real part) and, with *eigenvec*, *rn*, *intensity* and *pola*, as for 

1204 *get_eig*. 

1205 

1206 Parameters 

1207 ---------- 

1208 n_eig : Positive integer, default 10 

1209 Number of eigenpairs 

1210 (at most sites - 2). 

1211 sigma : Real or complex number, default 0 

1212 Target energy. 

1213 The factorization uses *sigma* shifted by about 1e-9 (relative to 

1214 the largest matrix element), so that it may be exactly an 

1215 eigenvalue, e.g. zero modes at the default *sigma* = 0; the 

1216 eigenvalues themselves are not shifted. 

1217 eigenvec : Boolean, default False 

1218 ''' 

1219 error_handling.empty_ham(self.ham) 

1220 error_handling.n_eig(n_eig, self.lat.sites) 

1221 error_handling.number(sigma, 'sigma') 

1222 error_handling.boolean(eigenvec, 'eigenvec') 

1223 self.ln = np.array([], 'c16') 

1224 ham = self.ham.tocsc() 

1225 hermitian = not (self.ham.conj().T != self.ham).nnz 

1226 # Never factorize H - sigma at sigma itself: when sigma is exactly an 

1227 # eigenvalue, SuperLU usually raises, but with a two-fold one it 

1228 # passes a negative size to BLAS, and Apple's Accelerate then aborts 

1229 # the whole process (no exception to catch). 

1230 target = sigma + 1e-9 * (1. + abs(sigma) + abs(ham).max()) 

1231 if hermitian: 

1232 out = SLA.eigsh(ham, k=n_eig, sigma=float(np.real(target)), return_eigenvectors=eigenvec) 

1233 else: 

1234 out = SLA.eigs(ham, k=n_eig, sigma=target, return_eigenvectors=eigenvec) 

1235 en, vec = out if eigenvec else (out, None) 

1236 ind = np.argsort(en.real, kind='stable') 

1237 self.en = en[ind] 

1238 if vec is not None: 

1239 self.rn = vec[:, ind] 

1240 self._set_states() 

1241 

1242 def get_eig_window( 

1243 self, e_min: float, e_max: float, eigenvec: bool = False, n_slice: int = 50, 

1244 ) -> None: 

1245 r''' 

1246 Get all the eigenenergies in the window :math:`[E_\mathrm{min}, 

1247 E_\mathrm{max}]` of a Hermitian Hamiltonian, and optionally their 

1248 eigenvectors, by spectrum slicing: the window is cut into slices of 

1249 at most *n_slice* eigenvalues, and each slice is solved by 

1250 shift-invert Lanczos about its centre, as *get_eig_sparse* does. 

1251 

1252 The number of eigenvalues below an energy :math:`\sigma` comes from 

1253 Sylvester's law of inertia: the sparse factorization 

1254 :math:`P(H - \sigma)P^T = LDL^\dagger` (SuperLU with a symmetric 

1255 permutation and diagonal pivots) has as many negative pivots 

1256 :math:`D_{ii}` as :math:`H` has eigenvalues below :math:`\sigma`. 

1257 This count is exact, so it says how many eigenvalues each slice must 

1258 give, and the slices are bisected until each holds at most 

1259 *n_slice* of them. Nothing is dense: the cost is one factorization 

1260 per count and per slice, so all the states of a band, or of an 

1261 energy window around a gap, of a flake of :math:`10^5` sites are 

1262 within reach. The results replace *en* (sorted) and, with 

1263 *eigenvec*, *rn*, *intensity* and *pola*, as for *get_eig*. 

1264 

1265 Parameters 

1266 ---------- 

1267 e_min, e_max : Real numbers 

1268 The window. Eigenvalues within about 1e-9 (relative to the 

1269 largest matrix element) of its ends count as inside. 

1270 eigenvec : Boolean, default False 

1271 n_slice : Positive integer, default 50 

1272 Largest number of eigenvalues solved together (a degenerate 

1273 level that holds more is solved in one slice). 

1274 ''' 

1275 error_handling.empty_ham(self.ham) 

1276 error_handling.energy_window((e_min, e_max), '(e_min, e_max)') 

1277 error_handling.boolean(eigenvec, 'eigenvec') 

1278 error_handling.positive_int(n_slice, 'n_slice') 

1279 error_handling.hermitian(self.ham) 

1280 self.ln = np.array([], 'c16') 

1281 ham = sparse.csc_matrix(self.ham, dtype='c16') 

1282 n = ham.shape[0] 

1283 # the ends move out by delta, so that no count factorizes H - sigma 

1284 # at an eigenvalue (see get_eig_sparse), and the split points by 

1285 # delta from the midpoints, where symmetric spectra have levels 

1286 delta = 1e-9 * (1. + max(abs(e_min), abs(e_max)) + abs(ham).max()) 

1287 lo, hi = e_min - delta, e_max + delta 

1288 counts = {lo: _inertia(ham, lo), hi: _inertia(ham, hi)} 

1289 total = counts[hi] - counts[lo] 

1290 if total + 2 > n - 2: # the window holds (almost) the whole spectrum 

1291 if eigenvec: 

1292 en, vec = LA.eigh(ham.toarray()) 

1293 else: 

1294 en, vec = LA.eigvalsh(ham.toarray()), None 

1295 keep = (en >= lo) & (en < hi) 

1296 self.en = en[keep] 

1297 if vec is not None: 

1298 self.rn = vec[:, keep] 

1299 self._set_states() 

1300 return 

1301 slices, todo = [], [(lo, hi)] 

1302 while todo: 

1303 a, b = todo.pop() 

1304 count = counts[b] - counts[a] 

1305 if count > n_slice and b - a > 1e3 * delta: 

1306 mid = (a + b) / 2. + delta 

1307 counts[mid] = _inertia(ham, mid) 

1308 todo += [(mid, b), (a, mid)] 

1309 elif count: 

1310 slices.append((a, b, count)) 

1311 values, vectors = [], [] 

1312 for a, b, count in sorted(slices): 

1313 en, vec = _slice_pairs(ham, a, b, count, (a + b) / 2. + delta) 

1314 values.append(en) 

1315 vectors.append(vec) 

1316 en = np.concatenate(values) if values else np.zeros(0) 

1317 ind = np.argsort(en, kind='stable') 

1318 self.en = en[ind] 

1319 if eigenvec: 

1320 self.rn = np.concatenate(vectors, axis=1)[:, ind] if vectors else np.zeros((n, 0), 'c16') 

1321 self._set_states() 

1322 

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

1324 r''' 

1325 Get the retarded Green's function (resolvent) 

1326 

1327 .. math:: 

1328 

1329 G(E) = \left[(E + i\eta) - H\right]^{-1}\, . 

1330 

1331 Parameters 

1332 ---------- 

1333 energy : Real (or complex) number 

1334 Energy :math:`E`. 

1335 eta : Positive real or zero, default 1e-6 

1336 Broadening :math:`\eta`. 

1337 

1338 Returns 

1339 ------- 

1340 G : Complex ndarray, shape (sites, sites) 

1341 ''' 

1342 error_handling.empty_ham(self.ham) 

1343 error_handling.number(energy, 'energy') 

1344 error_handling.positive_real_zero(eta, 'eta') 

1345 z = (energy + 1j * eta) * np.eye(self.ham.shape[0]) 

1346 return LA.inv(z - self.ham.toarray()) 

1347 

1348 def get_ldos(self, energies: ArrayLike, eta: float = 0.05) -> NDArray[np.float64]: 

1349 r''' 

1350 Get the local density of states 

1351 

1352 .. math:: 

1353 

1354 \rho_i(E) = -\frac{1}{\pi}\,\mathrm{Im}\,G_{ii}(E) 

1355 = \sum_n |\psi_n(i)|^2\,\frac{\eta/\pi}{(E - E_n)^2 + \eta^2} 

1356 

1357 (the second form, from the eigenvectors, for a Hermitian 

1358 Hamiltonian). Summed over sites it is the Lorentzian-broadened 

1359 density of states. 

1360 

1361 Parameters 

1362 ---------- 

1363 energies : Real array 

1364 Energies. 

1365 eta : Positive real, default 0.05 

1366 Broadening. 

1367 

1368 Returns 

1369 ------- 

1370 ldos : Real ndarray, shape (len(energies), sites) 

1371 ''' 

1372 error_handling.empty_ham(self.ham) 

1373 error_handling.positive_real(eta, 'eta') 

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

1375 error_handling.ndarray_empty(energies, 'energies') 

1376 ham = self.ham.toarray() 

1377 if np.allclose(ham, ham.conj().T, atol=1e-14): 

1378 en, vec = LA.eigh(ham) 

1379 lor = (eta / PI) / ((energies[:, None] - en[None, :]) ** 2 + eta ** 2) 

1380 return lor @ (np.abs(vec) ** 2).T 

1381 eye = np.eye(len(ham)) 

1382 return np.array([-np.diag(LA.inv((e + 1j * eta) * eye - ham)).imag / PI 

1383 for e in energies]) 

1384 

1385 def get_fermi_level(self, n_electrons: float, temperature: float = 0.) -> float: 

1386 ''' 

1387 Get the Fermi level holding *n_electrons* electrons in the spectrum 

1388 *en* (one electron per state; see *tbkit.occupation.fermi_level*). 

1389 

1390 Parameters 

1391 ---------- 

1392 n_electrons : Positive real or zero 

1393 Number of electrons. 

1394 temperature : Positive real or zero, default 0 

1395 

1396 Returns 

1397 ------- 

1398 e_fermi : Real number 

1399 ''' 

1400 error_handling.empty_ndarray(self.en, 'sys.get_eig') 

1401 return occupation.fermi_level(self.en, n_electrons, temperature) 

1402 

1403 def get_occupations(self, e_fermi: float, temperature: float = 0.) -> NDArray[np.float64]: 

1404 ''' 

1405 Get the Fermi-Dirac occupation of every eigenstate of *en*. 

1406 

1407 Parameters 

1408 ---------- 

1409 e_fermi : Real number 

1410 Fermi level (see *get_fermi_level*). 

1411 temperature : Positive real or zero, default 0 

1412 

1413 Returns 

1414 ------- 

1415 f : Real ndarray, same length as *en* 

1416 ''' 

1417 error_handling.empty_ndarray(self.en, 'sys.get_eig') 

1418 return occupation.fermi_dirac(self.en, e_fermi, temperature) 

1419 

1420 def get_charge_density(self, e_fermi: float, temperature: float = 0.) -> NDArray[np.float64]: 

1421 r''' 

1422 Get the electron density on every site, 

1423 :math:`n_i = \sum_n f(E_n)\,|\psi_n(i)|^2`. 

1424 

1425 Parameters 

1426 ---------- 

1427 e_fermi : Real number 

1428 Fermi level. 

1429 temperature : Positive real or zero, default 0 

1430 

1431 Returns 

1432 ------- 

1433 density : Real ndarray, shape (sites,) 

1434 ''' 

1435 error_handling.empty_ndarray(self.rn, 'sys.get_eig(eigenvec=True)') 

1436 return self.intensity @ self.get_occupations(e_fermi, temperature) 

1437 

1438 def get_total_energy(self, e_fermi: float, temperature: float = 0.) -> float: 

1439 r''' 

1440 Get the band energy :math:`E = \sum_n f(E_n)\,E_n`. 

1441 

1442 Parameters 

1443 ---------- 

1444 e_fermi : Real number 

1445 Fermi level. 

1446 temperature : Positive real or zero, default 0 

1447 

1448 Returns 

1449 ------- 

1450 energy : Real number 

1451 ''' 

1452 return float(np.sum(self.get_occupations(e_fermi, temperature) * self.en.real)) 

1453 

1454 def get_ipr(self) -> None: 

1455 r''' 

1456 Get the Inverse Participation Ratio:  

1457 

1458 .. math::  

1459 

1460 IPR_n = \sum_i|\psi_i^{n}|^4\, . 

1461 ''' 

1462 error_handling.empty_ndarray(self.rn, 'sys.get_eig(eigenvec=True)') 

1463 self.ipr = np.sum(self.intensity ** 2, axis=0) 

1464 

1465 def get_petermann(self) -> None: 

1466 r''' 

1467 Get the Petermann factor:  

1468  

1469 .. math:: 

1470 

1471 K_n = \frac{\langle\psi_L^{n}|\psi_L^{n}\rangle\langle\psi_R^{n}|\psi_R^{n}\rangle}{|\langle\psi_L^{n}|\psi_R^{n}\rangle|^2}\, . 

1472 

1473 .. note:: 

1474 

1475 LA.eig fixes the norm such that :math:`\langle\psi_L^{n}|\psi_L^{n}\rangle = 1` and :math:`\langle\psi_R^{n}|\psi_R^{n}\rangle = 1`. 

1476 ''' 

1477 if not (self.ham.conj().T != self.ham).nnz: 

1478 self.petermann = np.ones(self.lat.sites) 

1479 return 

1480 error_handling.empty_ndarray(self.ln, 'sys.get_eig(eigenvec=True, left=True)') 

1481 # LA.eig fixes each eigenvector's norm but not the relative phase 

1482 # between the left and right ones, so the overlap carries an 

1483 # arbitrary phase: take its modulus, not its real part. 

1484 left_right = np.abs(np.sum(self.ln * np.conjugate(self.rn), axis=0)) 

1485 self.petermann = 1. / left_right ** 2 

1486 

1487 def get_intensity_pola_max(self, tag_pola: str) -> NDArray[np.float64]: 

1488 ''' 

1489 Get the state with largest polarization on one sublattice. 

1490 

1491 Parameters 

1492 ---------- 

1493 tag_pola : String 

1494 Sublattice tag. 

1495 

1496 Returns 

1497 ------- 

1498 intensity 

1499 Intensity of max polarized state on *tag*. 

1500 ''' 

1501 error_handling.empty_ndarray(self.rn, 'sys.get_eig(eigenvec=True)') 

1502 error_handling.tag(tag_pola, self.lat.tags) 

1503 i_tag = self.lat.tags == tag_pola 

1504 ind = np.argmax(self.pola[:, i_tag]) 

1505 print('State with polarization: {:.5f}'.format(self.pola[ind, i_tag].item())) 

1506 return self.intensity[:, ind] 

1507 

1508 def get_intensity_pola_min(self, tag_pola: str) -> NDArray[np.float64]: 

1509 ''' 

1510 Get the state with smallest polarization on one sublattice. 

1511 

1512 Parameters 

1513 ---------- 

1514 tag_pola : String 

1515 Sublattice tag. 

1516 

1517 Returns 

1518 ------- 

1519 intensity 

1520 Intensity of min polarized state on *tag*. 

1521 ''' 

1522 error_handling.empty_ndarray(self.rn, 'sys.get_eig(eigenvec=True)') 

1523 error_handling.tag(tag_pola, self.lat.tags) 

1524 i_tag = self.lat.tags == tag_pola 

1525 ind = np.argmin(self.pola[:, i_tag]) 

1526 print('State with polarization: {:.5f}'.format(self.pola[ind, i_tag].item())) 

1527 return self.intensity[:, ind] 

1528 

1529 def get_intensity_en(self, lims: tuple[float, float]) -> NDArray[np.float64]: 

1530 ''' 

1531 Get, if any, the intensity of the sum of the states whose 

1532 energies (real part) lie between *lims[0]* and *lims[1]*. 

1533 

1534 Parameters 

1535 ---------- 

1536 lims : List 

1537 lims[0] energy min, lims[1] energy max. 

1538 

1539 Returns 

1540 ------- 

1541 intensity 

1542 Sum of the intensities between (lims[0], lims[1]). 

1543 ''' 

1544 error_handling.empty_ndarray(self.rn, 'sys.get_eig(eigenvec=True)') 

1545 error_handling.lims(lims) 

1546 ind = np.ravel(np.where((self.en.real > lims[0]) & (self.en.real < lims[1]))) 

1547 print('{} states between {} and {}'.format(len(ind), lims[0], lims[1])) 

1548 return np.sum(self.intensity[:, ind], axis=1) 

1549 

1550 

1551 def get_local_chern_marker(self, e_fermi: float = 0., area: float | None = None) -> NDArray[np.float64]: 

1552 r''' 

1553 Get the local Chern marker of the states below *e_fermi* (Bianco and 

1554 Resta, Phys. Rev. B 84, 241106 (2011)), 

1555 

1556 .. math:: 

1557 

1558 C(\mathbf{r}_i) = -\frac{4\pi}{a}\,\mathrm{Im}\, 

1559 \langle i|\,P\,x\,Q\,y\,P\,|i\rangle\, , 

1560 

1561 with :math:`P` the projector on the occupied states, :math:`Q = 1-P`, 

1562 and :math:`a` the area per site. Averaged over the bulk of a finite 

1563 flake -- even a disordered or amorphous one, where no Brillouin zone 

1564 exists -- it gives the Chern number, in the sign convention of 

1565 *KSpace.chern_number*; it sums to zero over the whole flake, the 

1566 edges carrying the opposite value. 

1567 

1568 Parameters 

1569 ---------- 

1570 e_fermi : Real number, default 0 

1571 Fermi energy: the states 

1572 with energies below it are occupied. 

1573 area : Positive real number 

1574 Default value None: the area of 

1575 the unit cell of *lat* divided by its number of sites. 

1576 

1577 Returns 

1578 ------- 

1579 marker : Real ndarray, shape (sites,) 

1580 ''' 

1581 error_handling.not_periodic(self.periodic, 'get_local_chern_marker') 

1582 error_handling.empty_ham(self.ham) 

1583 error_handling.real_number(e_fermi, 'e_fermi') 

1584 error_handling.hermitian(self.ham) 

1585 if area is None: 

1586 error_handling.planar_cell(self.lat.prim_vec) 

1587 (a1x, a1y), (a2x, a2y) = self.lat.prim_vec 

1588 area = abs(a1x * a2y - a1y * a2x) / len(self.lat.unit_cell) 

1589 error_handling.positive_real(area, 'area') 

1590 en, vec = LA.eigh(self.ham.toarray()) 

1591 occ = vec[:, en < e_fermi] 

1592 proj = occ @ occ.conj().T 

1593 rows = self._row_sites() 

1594 x = self.lat.coor['x'][rows] 

1595 y = self.lat.coor['y'][rows] 

1596 # P x Q y P = P x y P - P x P y P, diagonal only 

1597 pxq = proj * x[None, :] - (proj * x[None, :]) @ proj 

1598 qyp = y[:, None] * proj - proj @ (y[:, None] * proj) 

1599 per_row = -4 * PI / area * np.imag(np.sum(proj * (pxq @ qyp).T, axis=1)) 

1600 marker = np.zeros(self.lat.sites) 

1601 np.add.at(marker, rows, per_row) 

1602 return marker 

1603 

1604 def get_bott_index(self, e_fermi: float = 0.) -> float: 

1605 r''' 

1606 Get the Bott index of the states below *e_fermi* of a 2D lattice 

1607 with periodic boundaries along both primitive vectors (Loring and 

1608 Hastings, EPL 92, 67004 (2010); see *tbkit.topology.bott_index*): 

1609 the Chern number of a torus, in the sign convention of 

1610 *KSpace.chern_number*, and an integer for any disordered sample 

1611 whose occupied states are gapped or localized. 

1612 

1613 Parameters 

1614 ---------- 

1615 e_fermi : Real number, default 0 

1616 Fermi energy. 

1617 

1618 Returns 

1619 ------- 

1620 bott : Real number, close to an integer 

1621 

1622 Examples 

1623 -------- 

1624 Example usage:: 

1625 

1626 lat = lattices.honeycomb() 

1627 lat.get_lattice(12, 12) 

1628 sys = System(lat, periodic=True) 

1629 sys.set_hopping([{'n': 1, 't': 1.}]) 

1630 ... 

1631 sys.get_ham() 

1632 sys.get_bott_index() 

1633 ''' 

1634 from tbkit.topology import bott_index 

1635 error_handling.empty_ham(self.ham) 

1636 error_handling.torus_2d(self.periodic) 

1637 return bott_index(self.ham, self._coords()[self._row_sites()], self._box(), e_fermi) 

1638 

1639 def _row_sites(self) -> NDArray: 

1640 ''' 

1641 Private method. Site of every row of the Hamiltonian (one row per site here). 

1642 ''' 

1643 return np.arange(self.lat.sites) 

1644 

1645 

1646# Backward-compatible lowercase alias (pre-0.2 API). 

1647system = System