Coverage for tbkit/kspace.py: 100%
1530 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 11:05 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 11:05 +0000
1from __future__ import annotations
3from concurrent.futures import ThreadPoolExecutor
4from itertools import combinations, product
5from typing import Literal, Sequence, overload
7import numpy as np
8from numpy.typing import ArrayLike, NDArray
9import matplotlib.pyplot as plt
10from matplotlib.figure import Figure
11from matplotlib.collections import LineCollection, PolyCollection
12from matplotlib.colors import LogNorm, Normalize
13from mpl_toolkits.mplot3d.art3d import Poly3DCollection
14import scipy.linalg as LA
15import scipy.sparse as sp
16from scipy.integrate import cumulative_trapezoid
17from scipy.special import expit, spence
18import tbkit.error_handling as error_handling
19import tbkit.dos as dos
20import tbkit.occupation as occupation
21import tbkit.neighbours as neighbours
22import tbkit.values as values
23from tbkit.lattice import Lattice
24from tbkit.transport import _green_surface_bulk
27PI = np.pi
29#: Pauli matrices (plus the identity, key ``'0'``), for building spinful
30#: hoppings/onsite terms (spin-orbit coupling, Zeeman splitting, ...) when
31#: :class:`KSpace` is constructed with ``spin=True``.
32PAULI = {
33 '0': np.eye(2, dtype='c16'),
34 'x': np.array([[0., 1.], [1., 0.]], dtype='c16'),
35 'y': np.array([[0., -1j], [1j, 0.]], dtype='c16'),
36 'z': np.array([[1., 0.], [0., -1.]], dtype='c16'),
37}
39# The symmetry kinds of KSpace.non_hermitian_class, in its argument order:
40# (complex conjugation, transposition, minus sign) of U op(H(k)) U^dagger =
41# +-H(+-k). TRS, PHS, CS, TRS^dagger, PHS^dagger, SLS, pseudo-Hermiticity.
42_NH_KINDS = ((1, 0, 0), (0, 1, 1), (1, 1, 1), (0, 1, 0), (1, 0, 1), (0, 0, 1), (1, 1, 0))
44# Names of KSpace.non_hermitian_class equivalent under H -> iH (Kawabata et
45# al. 2019, Tables XII and XIV), mapped to the representative of the 38 classes.
46_NH_CANONICAL = {
47 'D†': 'AI', 'C†': 'AII', 'AII + S-': 'AI + S-', 'DIII + S-+': 'BDI + S-+',
48 'DIII + S--': 'BDI + S--', 'CI + S-+': 'CII + S-+', 'CI + S--': 'CII + S--',
49 'A + η': 'AIII', 'AI + η+': 'BDI†', 'AI + η-': 'DIII†', 'AII + η+': 'CII†',
50 'AII + η-': 'CI†', 'D + η+': 'BDI', 'D + η-': 'DIII', 'C + η+': 'CII', 'C + η-': 'CI',
51}
54#################################
55# CLASS KSPACE
56#################################
59def reciprocal_vectors(prim_vec: Sequence[tuple[float, ...]]) -> list[tuple[float, ...]]:
60 r'''
61 Get the reciprocal lattice vectors :math:`\mathbf{b}_i` such that
62 :math:`\mathbf{a}_i\cdot\mathbf{b}_j = 2\pi\delta_{ij}`, lying in the
63 span of the :math:`\mathbf{a}_i`.
65 Parameters
66 ----------
67 prim_vec : List of one/two/three tuples
68 Primitive vectors (see class **lattice**).
70 Returns
71 -------
72 rec_vec : List of one/two/three tuples
73 Reciprocal vectors, with
74 as many components as the primitive vectors.
75 '''
76 if len(prim_vec[0]) == 3:
77 # b = 2 pi (A^+)^T: the dual basis within the span of the a_i
78 rec = 2 * PI * np.linalg.pinv(np.array(prim_vec, dtype='f8')).T
79 return [tuple(float(c) for c in b) for b in rec]
80 if len(prim_vec) == 1:
81 ax, ay = prim_vec[0]
82 norm2 = ax ** 2 + ay ** 2
83 return [(2*PI*ax/norm2, 2*PI*ay/norm2)]
84 (a1x, a1y), (a2x, a2y) = prim_vec
85 area = a1x * a2y - a1y * a2x
86 b1 = (2*PI*a2y/area, -2*PI*a2x/area)
87 b2 = (-2*PI*a1y/area, 2*PI*a1x/area)
88 return [b1, b2]
91class KSpace():
92 r'''
93 Build and solve the Tight-Binding Bloch Hamiltonian :math:`H(\mathbf{k})`
94 of a periodic lattice defined by the class **lattice**.
96 Hoppings are defined between orbitals of the unit cell, separated by a
97 lattice vector :math:`\mathbf{R} = n_1\mathbf{a}_1+n_2\mathbf{a}_2`:
99 .. math::
101 H_{ij}(\mathbf{k}) = \sum_{\mathbf{R}} t_{ij}(\mathbf{R})\,
102 e^{i\mathbf{k}\cdot\mathbf{R}}
104 Parameters
105 ----------
106 lat : **lattice** class instance
107 Only *unit_cell* and *prim_vec*
108 are used (the instance need not call *get_lattice*).
109 spin : Boolean, default False
110 If True, every site of
111 *unit_cell* carries a spin-1/2 degree of freedom (*norb* doubles to
112 ``2*len(unit_cell)``, ordered site-major: orbitals ``2*i, 2*i+1``
113 are the up/down components of site *i*). *set_onsite* and
114 *set_hopping* then accept 2x2 (spin) matrices in addition to plain
115 numbers, to build spin-orbit coupling or Zeeman terms -- see
116 :data:`PAULI` for ready-made Pauli matrices.
118 Examples
119 --------
120 Example usage::
122 # graphene, nearest-neighbor hopping t
123 DX, DY = 0.5 * 3 ** 0.5, 0.5
124 unit_cell = [{'tag': 'a', 'r0': (0., 0.)}, {'tag': 'b', 'r0': (DX, DY)}]
125 prim_vec = [(2*DX, 0.), (DX, 1.5)]
126 lat = Lattice(unit_cell=unit_cell, prim_vec=prim_vec)
127 gra = KSpace(lat)
128 gra.set_hopping([{'i': 0, 'j': 1, 'R': (0, 0), 't': 1.},
129 {'i': 0, 'j': 1, 'R': (-1, 0), 't': 1.},
130 {'i': 0, 'j': 1, 'R': (0, -1), 't': 1.}])
131 '''
133 workers = 1 # threads diagonalizing over k, see set_workers
134 # _bloch_sum groups the hoppings by lattice vector when they fill at
135 # least this fraction of the dense (n_R, norb, norb) blocks; sparser
136 # models (large supercells) are summed hopping by hopping
137 group_fill = 0.01
139 def __init__(self, lat: Lattice, spin: bool = False) -> None:
140 error_handling.lat(lat)
141 error_handling.boolean(spin, 'spin')
142 error_handling.independent(lat.prim_vec)
143 self.lat = lat
144 self.dim = len(lat.prim_vec)
145 self.space_dim = len(lat.prim_vec[0])
146 self.spin = spin
147 self.n_sites = len(lat.unit_cell)
148 self.norb = 2*self.n_sites if spin else self.n_sites
149 self.tags = np.array([dic['tag'] for dic in lat.unit_cell])
150 self.onsite = np.zeros(self.norb, 'c16')
151 # spin-off-diagonal onsite terms (in-plane Zeeman, onsite Rashba):
152 # they have no place on the diagonal `onsite` array.
153 self._onsite_offdiag = np.zeros((self.norb, self.norb), 'c16')
154 self._hop_const: list = [] # list of (i, j, R_cartesian (np.ndarray), t)
155 # value functions (see tbkit.values): (i, j, R_cartesian, function,
156 # hermitian), with arrays of sites i, j and bond vectors R
157 self._hop_values: list = []
158 #: Parameters of the value functions (see *set_params*).
159 self.params: dict = {}
160 self._nonreciprocal = False # set_hopping(hermitian=False) was used
161 self._overlap_hop: list = [] # overlaps, as _hop: list of (i, j, R_cartesian, s)
162 # position matrix elements <i,0|r|j,R> other than the orbital
163 # positions (a Wannier90 _tb.dat file, see io.read_wannier90_tb):
164 # list of (i, j, R_cartesian, r), r a complex vector of space_dim
165 self._position_hop: list = []
166 self.rec_vec = reciprocal_vectors(lat.prim_vec)
167 # Orthonormal basis (columns) of the span of prim_vec, in which k is
168 # given: the identity when the lattice fills its space, a1/|a1| for a
169 # chain, the Gram-Schmidt basis of (a1, a2) for a 2D lattice in 3D.
170 self.k_basis = np.linalg.qr(np.array(lat.prim_vec, dtype='f8').T)[0]
171 if self.dim == self.space_dim:
172 self.k_basis = np.eye(self.space_dim)
173 elif self.dim == 1:
174 a1 = np.asarray(lat.prim_vec[0], dtype='f8')
175 self.k_basis = (a1 / np.linalg.norm(a1))[:, None]
176 else:
177 # keep the first axis along a1 (QR may flip signs)
178 signs = np.sign(np.diag(np.array(lat.prim_vec, dtype='f8') @ self.k_basis))
179 self.k_basis = self.k_basis * np.where(signs == 0, 1., signs)[None, :]
180 #: Reciprocal vectors in the k coordinates used by *get_ham* (rows).
181 self.rec_vec_k = np.array(self.rec_vec, dtype='f8') @ self.k_basis
182 self.ks = np.array([]) # k-points of the last band-structure calculation
183 self.ks_dist = np.array([]) # cumulative distance along the k-path
184 self.nodes = np.array([]) # positions, along ks_dist, of the k-path nodes
185 self.en = np.array([]) # bands, shape (len(ks), norb)
187 @property
188 def _hop(self) -> list:
189 '''
190 Private. The hoppings, as a list of (i, j, R_cartesian, t): those
191 given as numbers, then the value functions evaluated with *params*.
192 Assigning it replaces both.
193 '''
194 return self._hops(self.params)
196 @_hop.setter
197 def _hop(self, hops: list) -> None:
198 self._hop_const = list(hops)
199 self._hop_values = []
201 def _hops(self, params: dict) -> list:
202 '''
203 Private method. *_hop*, with the value functions evaluated with *params*.
204 '''
205 hops = list(self._hop_const)
206 if not self._hop_values:
207 return hops
208 tau = np.array([dic['r0'] for dic in self.lat.unit_cell], dtype='f8').reshape(self.n_sites, -1)
209 for i, j, R, func, hermitian in self._hop_values:
210 site_i = values.sites(tau[i], self.tags[i], i)
211 site_j = values.sites(tau[j] + R, self.tags[j], j)
212 t = values.evaluate(func, (site_i, site_j), params, len(i), self.spin)
213 if self.spin:
214 pairs = [(2*ii + a, 2*jj + b, RR, tt[a, b], np.conj(tt[a, b]))
215 for ii, jj, RR, tt in zip(i, j, R, t) for a in range(2) for b in range(2)]
216 else:
217 pairs = [(ii, jj, RR, tt, np.conj(tt)) for ii, jj, RR, tt in zip(i, j, R, t)]
218 for ii, jj, RR, tt, tc in pairs:
219 hops.append((int(ii), int(jj), RR, tt))
220 if hermitian:
221 hops.append((int(jj), int(ii), -RR, tc))
222 return hops
224 def set_params(self, **params) -> None:
225 '''
226 Set the parameters of the value functions of *set_hopping*: every
227 method (*get_bands*, *chern_number*, *finite_ham*, ...) then uses
228 these values. *get_ham* also takes them per call.
230 Parameters
231 ----------
232 params
233 Parameter values, added to (or replacing those of) *params*.
235 Examples
236 --------
237 Example usage::
239 ks.set_params(m=0.5)
240 ks.chern_number()
241 '''
242 self.params.update(params)
244 def set_onsite(self, dict_onsite: dict[str, complex | Sequence[complex]]) -> None:
245 '''
246 Set the onsite energies, by sublattice tag.
248 Parameters
249 ----------
250 dict_onsite : Dictionary
251 key: tag, val: onsite energy
252 (a plain number), or, if ``spin=True``, a plain number (applied
253 equally to both spins), a pair ``(E_up, E_down)`` of numbers (a
254 spin splitting along z), or a 2x2 complex matrix (a general spin
255 structure, e.g. an in-plane Zeeman field built from :data:`PAULI`).
256 A complex onsite energy (gain/loss), or a non-Hermitian 2x2
257 block, makes :math:`H(\\mathbf{k})` non-Hermitian: *get_bands*
258 then returns complex energies, sorted by their real part.
260 Examples
261 --------
262 Example usage::
264 kag.set_onsite({'a': 1., 'b': -1.})
265 # spinful: same onsite energy for both spins on 'a', a Zeeman
266 # splitting along z on 'b':
267 kag_spin.set_onsite({'a': 1., 'b': (1., -1.)})
268 # spinful: an in-plane Zeeman field on 'a':
269 kag_spin.set_onsite({'a': Bx*PAULI['x']})
270 '''
271 error_handling.set_onsite_kspace(dict_onsite, self.lat.tags, self.spin)
272 for tag, val in dict_onsite.items():
273 sites = np.where(self.tags == tag)[0]
274 if self.spin:
275 if np.ndim(val) == 0:
276 block = val * PAULI['0']
277 elif np.ndim(val) == 2:
278 block = np.asarray(val, 'c16')
279 else:
280 block = np.diag(np.asarray(val, 'c16'))
281 self.onsite[2*sites] = block[0, 0]
282 self.onsite[2*sites + 1] = block[1, 1]
283 for site in sites:
284 self._onsite_offdiag[2*site, 2*site + 1] = block[0, 1]
285 self._onsite_offdiag[2*site + 1, 2*site] = block[1, 0]
286 else:
287 self.onsite[sites] = val
289 def set_hopping(self, list_hop: list[dict], hermitian: bool = True) -> None:
290 r'''
291 Set the hoppings between orbitals of the unit cell.
293 Only one representative of each hopping needs to be given: its
294 Hermitian conjugate (:math:`j\to i`, :math:`\mathbf{R}\to-\mathbf{R}`)
295 is added automatically (unless ``hermitian=False``).
297 Parameters
298 ----------
299 list_hop
300 List of dictionaries with keys ('i', 'j', 'R', 't'):
302 * 'i', 'j': Positive integers. Site indices within the unit cell
303 (following the order of *unit_cell*).
304 * 'R': Tuple of one/two integers :math:`(n_1, n_2)`. Lattice vector
305 :math:`\mathbf{R}=n_1\mathbf{a}_1+n_2\mathbf{a}_2` separating the
306 two sites.
307 * 't': Complex number, or, if ``spin=True``, either a complex
308 number (spin-independent hopping) or a 2x2 complex matrix (a
309 general, possibly spin-mixing, hopping -- e.g. built from
310 :data:`PAULI` for Rashba or intrinsic spin-orbit coupling).
311 Or a value function ``t(site_i, site_j, **params)``,
312 evaluated by ``get_ham(k, **params)`` (and by every other
313 method, with the parameters of *set_params*): *site_i* and
314 *site_j* are structured arrays of the bonds' end points,
315 *site_i* in the home cell and *site_j* in cell
316 :math:`\mathbf{R}` (fields 'x', 'y', ('z'), 'tag', 'index' --
317 the site index within *unit_cell*). It is called once with
318 every bond of the dictionaries that share it, and returns one
319 value, or one per bond (or, if ``spin=True``, a 2x2 matrix,
320 or one per bond).
322 *list_hop* may instead use the neighbour-order form of
323 *System.set_hopping*: dictionaries with keys ('n', 't') and
324 optionally 'ang' and/or 'tag' -- 'n' the neighbour order (1st,
325 2nd, ... shortest distance between orbitals of the infinite
326 lattice), 'ang' a bond angle in degrees, 'tag' a sublattice pair
327 such as ``'ab'``. The bonds are found from *unit_cell* and
328 *prim_vec* (in 1D, 2D and 3D) and turned into the explicit form
329 by *tbkit.neighbours.neighbour_hoppings* (see there for the bond
330 orientations; a negative angle addresses the reversed bonds).
331 A list uses one form or the other, not both.
332 hermitian : Boolean, default True
333 If False, the Hermitian
334 conjugates are *not* added: each dictionary is one matrix element
335 :math:`H_{ij}(\mathbf{R})` only, so that non-reciprocal
336 (non-Hermitian) hoppings can be built -- give the reverse hopping
337 explicitly, with its own amplitude.
339 Examples
340 --------
341 Example usage::
343 # graphene, by neighbour order: nearest (t) and next-nearest
344 # (t2) neighbours, as in System.set_hopping
345 gra.set_hopping([{'n': 1, 't': t}, {'n': 2, 't': t2}])
346 # square lattice, anisotropic nearest neighbours
347 sq.set_hopping([{'n': 1, 'ang': 0., 't': tx}, {'n': 1, 'ang': 90., 't': ty}])
349 # 1D chain, nearest-neighbor hopping t between the only orbital
350 # and its right neighbor:
351 chain.set_hopping([{'i': 0, 'j': 0, 'R': (1,), 't': 1.}])
352 # spinful: spin-independent hopping t, plus a Rashba-like
353 # spin-flip term of strength alpha:
354 chain_spin.set_hopping([{'i': 0, 'j': 0, 'R': (1,),
355 't': t*PAULI['0'] + 1j*alpha*PAULI['y']}])
356 # value function: a staggered hopping, swept without rebuilding
357 chain.set_hopping([{'n': 1, 't': lambda si, sj, t, d: t + d * (-1) ** si['index']}])
358 ham = chain.get_ham((0.,), t=1., d=0.2)
359 '''
360 error_handling.boolean(hermitian, 'hermitian')
361 if error_handling.hopping_form(list_hop):
362 list_hop = neighbours.neighbour_hoppings(self.lat, list_hop, self.spin, hermitian)
363 error_handling.set_hopping_kspace(list_hop, self.n_sites, self.dim, self.spin, values=True)
364 if not hermitian:
365 self._nonreciprocal = True
366 funcs: dict = {} # the bonds of each value function: id -> (function, [(i, j, R_cart)])
367 for dic in list_hop:
368 R_cart = np.zeros(self.space_dim)
369 for n, vec in zip(dic['R'], self.lat.prim_vec):
370 R_cart += n * np.array(vec)
371 i, j, t = dic['i'], dic['j'], dic['t']
372 if callable(t):
373 funcs.setdefault(id(t), (t, []))[1].append((i, j, R_cart))
374 elif self.spin:
375 block = t*PAULI['0'] if np.ndim(t) == 0 else np.asarray(t, 'c16')
376 for a in range(2):
377 for b in range(2):
378 self._hop_const.append((2*i+a, 2*j+b, R_cart, block[a, b]))
379 if hermitian:
380 self._hop_const.append((2*j+b, 2*i+a, -R_cart, np.conj(block[a, b])))
381 else:
382 self._hop_const.append((i, j, R_cart, t))
383 if hermitian:
384 self._hop_const.append((j, i, -R_cart, np.conj(t)))
385 for func, bonds in funcs.values():
386 i, j, R = zip(*bonds)
387 self._hop_values.append((np.array(i), np.array(j), np.array(R), func, hermitian))
389 def set_overlap(self, list_hop: list[dict]) -> None:
390 r'''
391 Set the overlaps :math:`s_{ij}(\mathbf{R}) = \langle i,\mathbf{0}|j,\mathbf{R}\rangle`
392 of a non-orthogonal basis, in the format of *set_hopping* (key 't'
393 for the overlap; the Hermitian conjugates are added):
395 .. math::
397 S(\mathbf{k}) = \mathbb{1} + \sum_{\mathbf{R}} s(\mathbf{R})\,e^{i\mathbf{k}\cdot\mathbf{R}}\, ,
399 after which the bands solve :math:`H(\mathbf{k})v = E\,S(\mathbf{k})v`.
400 (With graphene's nearest-neighbour overlap :math:`s`, the
401 :math:`\pi` bands become :math:`E = (\epsilon \pm t|f|)/(1 \pm s|f|)`:
402 no longer symmetric about :math:`\epsilon`.) The topological tools use
403 the Lowdin-orthonormalized states :math:`S^{1/2}v`.
405 Parameters
406 ----------
407 list_hop
408 List of dictionaries ('i', 'j', 'R', 't'), or by
409 neighbour order ('n', 't', optionally 'ang', 'tag'), see
410 *set_hopping* (numbers only, no value functions).
411 '''
412 if error_handling.hopping_form(list_hop):
413 list_hop = neighbours.neighbour_hoppings(self.lat, list_hop, self.spin)
414 error_handling.set_hopping_kspace(list_hop, self.n_sites, self.dim, self.spin)
415 saved = self._hop_const, self._hop_values, self._nonreciprocal
416 self._hop = []
417 self.set_hopping(list_hop)
418 self._overlap_hop += self._hop_const
419 self._hop_const, self._hop_values, self._nonreciprocal = saved
421 def get_overlap(self, k: ArrayLike) -> NDArray[np.complex128]:
422 r'''
423 Get the overlap matrix :math:`S(\mathbf{k})` (the identity for an
424 orthogonal basis), see *set_overlap*.
426 Parameters
427 ----------
428 k : k point (see *get_ham*)
430 Returns
431 -------
432 S : Complex ndarray, shape (norb, norb)
433 '''
434 error_handling.k_vector(k, 'k', self.dim)
435 k_cart = self.k_basis @ np.asarray(k, dtype='f8')
436 return np.eye(self.norb) + self._bloch_sum(self._overlap_hop, k_cart[None])[0][0]
438 def clear_hopping(self) -> None:
439 '''
440 Clear the hoppings set by *set_hopping* (and the overlaps of *set_overlap*).
441 '''
442 self._hop = []
443 self._nonreciprocal = False
444 self._overlap_hop = []
446 def get_ham(self, k: ArrayLike, **params) -> NDArray[np.complex128]:
447 r'''
448 Get the dense Bloch Hamiltonian :math:`H(\mathbf{k})`.
450 Parameters
451 ----------
452 k : Tuple/list/ndarray of *dim* real numbers
453 When the lattice
454 fills its space (2D in the plane, 3D in space), the
455 :math:`\mathbf{k}` point in the same Cartesian frame as *prim_vec*.
456 In 1D, the crystal momentum *along* the primitive vector (so the
457 Brillouin zone spans :math:`2\pi/|\mathbf{a}_1|`), which
458 coincides with :math:`k_x` for a chain aligned with :math:`x`.
459 For a 2D lattice in 3D space (a slab), the components along the
460 orthonormal basis *k_basis* of its plane (the first along
461 :math:`\mathbf{a}_1`). *rec_vec_k* holds the reciprocal vectors in
462 these coordinates.
463 params
464 Values of the parameters of the value functions of
465 *set_hopping*, for this call only: they override those of
466 *set_params*. Each function gets the ones its signature names
467 (all of them with ``**kwargs``); the others are ignored.
469 Returns
470 -------
471 ham : Complex ndarray, shape (norb, norb)
473 Examples
474 --------
475 Example usage::
477 hams = [ks.get_ham((0., 0.), m=m) for m in np.linspace(-1., 1., 21)]
478 '''
479 error_handling.k_vector(k, 'k', self.dim)
480 return self._bloch_ham((self.k_basis @ np.asarray(k, dtype='f8'))[None],
481 params={**self.params, **params})[0]
483 def get_ham_peierls(self, k: ArrayLike, A: ArrayLike) -> NDArray[np.complex128]:
484 r'''
485 Get the Bloch Hamiltonian in a uniform vector potential
486 :math:`\mathbf{A}` (:math:`\hbar = e = 1`): every hopping picks up the
487 Peierls phase :math:`e^{i\mathbf{A}\cdot\mathbf{d}}` of its bond
488 vector :math:`\mathbf{d} = \mathbf{R} + \boldsymbol\tau_j - \boldsymbol\tau_i`
489 (see *System.set_peierls_phase*). A time-dependent :math:`\mathbf{A}(t)`
490 is a uniform electric field :math:`-\partial_t\mathbf{A}`, e.g. light
491 (see *tbkit.floquet*).
493 Parameters
494 ----------
495 k : k point (see *get_ham*)
496 A : Tuple/ndarray of space_dim real numbers
497 Vector potential.
499 Returns
500 -------
501 ham : Complex ndarray, shape (norb, norb)
502 '''
503 error_handling.k_vector(k, 'k', self.dim)
504 A = np.asarray(A, dtype='f8')
505 error_handling.ndarray(A, 'A', self.space_dim)
506 return self._bloch_ham((self.k_basis @ np.asarray(k, dtype='f8'))[None], A)[0]
508 def _bloch_ham(
509 self, k_cart: NDArray[np.float64], A: NDArray[np.float64] | None = None, params: dict | None = None,
510 ) -> NDArray[np.complex128]:
511 '''
512 Private method. *get_ham* (or, with a vector potential *A*,
513 *get_ham_peierls*) at many k-points at once: *k_cart* has shape
514 (nk, space_dim) and the result (nk, norb, norb). The value functions
515 take *params* (default: *self.params*).
516 '''
517 hops = self._hops(self.params if params is None else params)
518 return self._bloch_sum(hops, k_cart, A=A)[0] + (np.diag(self.onsite) + self._onsite_offdiag)[None]
520 def get_bands(
521 self, ks: ArrayLike, eigenvec: bool = False,
522 ) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.complex128]]:
523 r'''
524 Diagonalize :math:`H(\mathbf{k})` over a set of k-points, and keep
525 the result for *plot_bands* (plotted against the cumulative distance
526 between consecutive k-points).
528 Parameters
529 ----------
530 ks : ndarray, shape (nk, dim)
531 k-points.
532 eigenvec : Boolean, default False
533 If True, also return
534 the eigenvectors.
536 Returns
537 -------
538 en : Real ndarray, shape (nk, norb)
539 Band energies, sorted ascending.
540 Complex, and sorted by real part, if :math:`H(\mathbf{k})` is
541 non-Hermitian (complex onsite energies, see *set_onsite*).
542 vn : Complex ndarray, shape (nk, norb, norb), only if *eigenvec* is True
543 vn[k, :, n] is the nth (right) eigenvector at ks[k].
544 '''
545 ks = np.atleast_2d(np.asarray(ks, dtype='f8'))
546 error_handling.ks(ks, self.dim)
547 out = self._diagonalize(ks, eigenvec)
548 self.ks = ks
549 self.en = out[0] if isinstance(out, tuple) else out
550 steps = np.linalg.norm(np.diff(ks, axis=0), axis=1)
551 self.ks_dist = np.concatenate([[0.], np.cumsum(steps)])[:len(ks)]
552 self.nodes = np.array([])
553 return out
555 @overload
556 def _diagonalize(
557 self, ks: NDArray[np.float64], eigenvec: Literal[False] = ...,
558 ) -> NDArray[np.float64]: ...
559 @overload
560 def _diagonalize(
561 self, ks: NDArray[np.float64], eigenvec: Literal[True],
562 ) -> tuple[NDArray[np.float64], NDArray[np.complex128]]: ...
563 @overload
564 def _diagonalize(
565 self, ks: NDArray[np.float64], eigenvec: bool,
566 ) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.complex128]]: ...
568 def _diagonalize(
569 self, ks: NDArray[np.float64], eigenvec: bool = False,
570 ) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.complex128]]:
571 r'''
572 Private method. Diagonalize :math:`H(\mathbf{k})` over the k-points
573 *ks* (shape (nk, dim)), without touching the stored band structure.
574 '''
575 return self._eigs(ks, eigenvec)
577 def set_workers(self, workers: int) -> None:
578 r'''
579 Set the number of threads that diagonalize :math:`H(\mathbf{k})`
580 over many k-points (*get_bands*, *mesh_bands*, *berry_curvature*,
581 the Wilson loops, ...). The k-points are split into chunks, each
582 diagonalized by one stacked LAPACK call, which releases the GIL, so
583 the chunks run in parallel. *surface_spectral_function* spreads its
584 k-points (and, with fewer k-points than threads, chunks of its
585 energies) over the threads in the same way. The results depend on
586 *workers* only up to rounding (and the phases of the eigenvectors).
588 Parameters
589 ----------
590 workers : Positive integer
591 Number of threads (default 1, no threads).
593 Examples
594 --------
595 Example usage::
597 ks.set_workers(4)
598 curv = ks.berry_curvature(0, nk=400)
599 '''
600 error_handling.positive_int(workers, 'workers')
601 self.workers = workers
603 def _hams(self, ks: NDArray[np.float64]) -> NDArray[np.complex128]:
604 '''
605 Private method. *get_ham* at the k-points *ks* (shape (nk, dim)),
606 shape (nk, norb, norb): one Bloch sum, unless a subclass overrides
607 *get_ham*, which is then called per k-point (a Floquet model
608 overrides *_hams* too, see *floquet.DrivenKSpace._hams*).
609 '''
610 if type(self).get_ham is KSpace.get_ham:
611 return self._bloch_ham(ks @ self.k_basis.T)
612 return np.array([self.get_ham(k) for k in ks], dtype='c16')
614 def _overlaps(self, ks: NDArray[np.float64]) -> NDArray[np.complex128]:
615 '''
616 Private method. *get_overlap* at the k-points *ks*, shape (nk, norb, norb).
617 '''
618 return np.eye(self.norb) + self._bloch_sum(self._overlap_hop, ks @ self.k_basis.T)[0]
620 @overload
621 def _eigs(self, ks: NDArray[np.float64], eigenvec: Literal[False] = ...) -> NDArray: ...
622 @overload
623 def _eigs(
624 self, ks: NDArray[np.float64], eigenvec: Literal[True],
625 ) -> tuple[NDArray, NDArray[np.complex128]]: ...
626 @overload
627 def _eigs(
628 self, ks: NDArray[np.float64], eigenvec: bool,
629 ) -> NDArray | tuple[NDArray, NDArray[np.complex128]]: ...
631 def _eigs(
632 self, ks: NDArray[np.float64], eigenvec: bool = False,
633 ) -> NDArray | tuple[NDArray, NDArray[np.complex128]]:
634 '''
635 Private method. *_eig* at the k-points *ks* (shape (nk, dim)): the
636 eigenvalues, shape (nk, norb), and the eigenvectors, shape
637 (nk, norb, norb). The k-points go in chunks of bounded memory,
638 spread over *workers* threads (see *set_workers*).
639 '''
640 chunk = max(1, min(400000 // self.norb ** 2, -(-len(ks) // self.workers)))
641 parts = [ks[c0:c0 + chunk] for c0 in range(0, len(ks), chunk)] or [ks]
642 if self.workers > 1 and len(parts) > 1:
643 with ThreadPoolExecutor(self.workers) as pool:
644 out = list(pool.map(lambda part: self._eig_chunk(part, eigenvec), parts))
645 else:
646 out = [self._eig_chunk(part, eigenvec) for part in parts]
647 if eigenvec:
648 return np.concatenate([o[0] for o in out]), np.concatenate([o[1] for o in out])
649 return np.concatenate(out)
651 def _eig_chunk(
652 self, ks: NDArray[np.float64], eigenvec: bool,
653 ) -> NDArray | tuple[NDArray, NDArray[np.complex128]]:
654 r'''
655 Private method. One chunk of *_eigs*: the Hermitian solver when
656 *is_hermitian*, otherwise the general one, with the eigenvalues
657 sorted by real part, both stacked over the k-points. With an overlap
658 (see *set_overlap*), the generalized problem :math:`Hv = ES(\mathbf{k})v`:
659 the Hermitian one is reduced by the Cholesky factor
660 :math:`S = LL^\dagger` to :math:`L^{-1}HL^{-\dagger}` (eigenvectors
661 :math:`L^{-\dagger}v`, normalized to :math:`v^\dagger Sv = 1` as by
662 *scipy.linalg.eigh*); the non-Hermitian one has no stacked solver,
663 and is solved one k-point at a time.
664 '''
665 ham = self._hams(ks)
666 hermitian = self.is_hermitian()
667 en: NDArray
668 vn: NDArray
669 if self._overlap_hop and hermitian:
670 l_inv = np.linalg.inv(np.linalg.cholesky(self._overlaps(ks)))
671 l_inv_h = l_inv.conj().transpose(0, 2, 1)
672 ham = l_inv @ ham @ l_inv_h
673 if hermitian:
674 if not eigenvec:
675 return np.linalg.eigvalsh(ham)
676 en, vn = np.linalg.eigh(ham)
677 return en, (l_inv_h @ vn if self._overlap_hop else vn)
678 if self._overlap_hop:
679 solved = [LA.eig(h, s) for h, s in zip(ham, self._overlaps(ks))]
680 en = np.array([w for w, _ in solved], dtype='c16').reshape(len(ks), self.norb)
681 vn = np.array([v for _, v in solved], dtype='c16').reshape(ham.shape)
682 elif eigenvec:
683 en, vn = np.linalg.eig(ham)
684 else:
685 en = np.linalg.eigvals(ham)
686 ind = np.argsort(en.real, axis=1, kind='stable')
687 if not eigenvec:
688 return np.take_along_axis(en, ind, axis=1)
689 return np.take_along_axis(en, ind, axis=1), np.take_along_axis(vn, ind[:, None, :], axis=2)
691 def is_hermitian(self) -> bool:
692 '''
693 Check whether :math:`H(\\mathbf{k})` is Hermitian: it is, unless an
694 onsite term is not, or *set_hopping* was called with
695 ``hermitian=False`` (such a model is always treated as
696 non-Hermitian, and diagonalized with the general solver).
698 Returns
699 -------
700 hermitian : Boolean
701 '''
702 return bool(not self._nonreciprocal and np.all(self.onsite.imag == 0.)
703 and np.array_equal(self._onsite_offdiag, self._onsite_offdiag.conj().T))
705 def k_path(
706 self, points: list[ArrayLike], nk: int,
707 ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
708 r'''
709 Build a k-path through a list of high-symmetry points, and get the
710 associated bands.
712 Parameters
713 ----------
714 points
715 List of at least two k-points (each a tuple/list of
716 *dim* real numbers), e.g. from *high_symmetry_path*.
717 nk : Positive integer
718 Number of k-points per path segment.
720 Returns
721 -------
722 ks_dist : Real ndarray
723 Cumulative distance along the path,
724 to be used as the x-axis of a band-structure plot.
725 en : Real ndarray, shape (len(ks_dist), norb)
726 Band energies.
727 '''
728 error_handling.k_path_points(points, self.dim)
729 error_handling.positive_int(nk, 'nk')
730 ks, _, nodes = _path(points, nk)
731 self.get_bands(ks)
732 self.nodes = np.array(nodes)
733 return self.ks_dist, self.en
735 def mesh_grid(
736 self, nk: int | tuple[int, ...], monkhorst_pack: bool = False,
737 ) -> tuple[list[NDArray[np.float64]], NDArray[np.float64]]:
738 r'''
739 Build a uniform grid of fractional coordinates spanning the
740 Brillouin zone, and the corresponding Cartesian k-points. By
741 default the grid contains :math:`\Gamma`: :math:`r/q`,
742 :math:`r = 0, \dots, q-1` (each in [0, 1)). With *monkhorst_pack*,
743 it is the grid of Monkhorst and Pack (Phys. Rev. B 13, 5188 (1976)),
744 :math:`(2r - q - 1)/2q`, :math:`r = 1, \dots, q` (each in
745 (-1/2, 1/2)), symmetric about :math:`\Gamma`: the same points for
746 odd :math:`q`, shifted by half a step (off :math:`\Gamma` and the
747 zone boundary) for even :math:`q`. Both integrate exactly every
748 Fourier component :math:`e^{i\mathbf{k}\cdot\mathbf{R}}` with
749 :math:`|R_i| < q`.
751 Parameters
752 ----------
753 nk : Positive integer, or tuple of *dim* positive integers
754 Number of k-points along each reciprocal lattice vector.
755 monkhorst_pack : Boolean, default False
756 If True, the
757 Monkhorst-Pack grid.
759 Returns
760 -------
761 fracs
762 List of *dim* real ndarrays, shape (nk1, nk2) each
763 (or (nk1,) in 1D): fractional coordinates of the grid.
764 ks : Real ndarray, shape (nk1*nk2, dim) (or (nk1, dim) in 1D)
765 '''
766 error_handling.nk(nk, self.dim)
767 error_handling.boolean(monkhorst_pack, 'monkhorst_pack')
768 if isinstance(nk, int):
769 nk = (nk,) * self.dim
770 if monkhorst_pack:
771 axes = [(2 * np.arange(1, n + 1) - n - 1) / (2 * n) for n in nk]
772 else:
773 axes = [np.arange(n) / n for n in nk]
774 fracs = np.meshgrid(*axes, indexing='ij')
775 ks = sum(f.ravel()[:, None] * b[None, :] for f, b in zip(fracs, self.rec_vec_k))
776 if self.dim == 1:
777 return [fracs[0]], ks
778 return list(fracs), ks
780 def mesh_bands(self, nk: int | tuple[int, ...], monkhorst_pack: bool = False) -> NDArray[np.float64]:
781 '''
782 Diagonalize :math:`H(\\mathbf{k})` over a uniform mesh spanning the
783 Brillouin zone. Unlike *get_bands*, it leaves the band structure kept
784 for *plot_bands* untouched.
786 Parameters
787 ----------
788 nk : Positive integer, or tuple of *dim* positive integers
789 Number of k-points along each reciprocal lattice vector.
790 monkhorst_pack : Boolean, default False
791 If True, the
792 Monkhorst-Pack grid (see *mesh_grid*).
794 Returns
795 -------
796 en : Real ndarray, shape (nk1*nk2, norb)
797 Band energies
798 over the mesh (flattened).
799 '''
800 _, ks = self.mesh_grid(nk, monkhorst_pack)
801 return self._diagonalize(ks)
803 def get_fermi_level(
804 self, n_electrons: float, nk: int | tuple[int, ...] = 30, temperature: float = 0.,
805 ) -> float:
806 '''
807 Get the Fermi level holding *n_electrons* electrons per unit cell
808 (one electron per band and k-point), from the bands over a uniform
809 Brillouin-zone mesh (see *tbkit.occupation.fermi_level*).
811 Parameters
812 ----------
813 n_electrons : Positive real or zero, at most norb
814 Electrons per unit cell.
815 nk : Positive integer, or tuple, default 30
816 k-mesh.
817 temperature : Positive real or zero, default 0
819 Returns
820 -------
821 e_fermi : Real number
822 '''
823 en = self.mesh_bands(nk)
824 return occupation.fermi_level(en, n_electrons, temperature,
825 weights=np.full(en.shape, 1. / len(en)))
827 def berry_curvature(
828 self, bands: int | list[int], nk: int | tuple[int, int] = 30,
829 plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
830 ) -> NDArray[np.float64]:
831 r'''
832 Get the Berry curvature of a group of bands over a uniform
833 Brillouin-zone mesh, using the gauge-invariant lattice method of
834 Fukui, Hatsugai and Suzuki (J. Phys. Soc. Jpn. 74, 1674 (2005)):
835 the flux through each mesh plaquette is minus the phase of the
836 product of the (Slater-determinant) overlaps between the occupied
837 subspaces at its four corners,
839 .. math::
841 \Omega_{\square} = -\arg\prod_{\langle\mathbf{k}\mathbf{k}'\rangle\in\partial\square}
842 \det\langle u(\mathbf{k})|u(\mathbf{k}')\rangle\, ,
844 the corners being visited counterclockwise. This is the discrete
845 version of :math:`\Omega = \partial_{k_x}A_y - \partial_{k_y}A_x`,
846 :math:`\mathbf{A} = i\langle u|\nabla_{\mathbf{k}}u\rangle`, and does
847 not depend on the orientation (handedness) of *prim_vec*. The local
848 curvature is that of the periodic gauge of *get_ham* (orbitals on the
849 cell origin), which differs point by point from the one with the
850 orbital positions included (see *quantum_geometric_tensor*); their
851 integral, the Chern number, is the same. For a
852 non-Hermitian :math:`H(\mathbf{k})` (see *set_onsite*), the bands
853 are ordered by the real part of their energy and the overlaps are
854 taken between right eigenvectors (the "RR" curvature of
855 *biorthogonal_berry_curvature*). That ordering follows the bands
856 continuously only if a real line gap separates *bands* from the
857 others over the whole zone: without one (an imaginary line gap,
858 or exceptional points), a ValueError is raised instead of a
859 meaningless result -- see *biorthogonal_berry_curvature*.
861 Parameters
862 ----------
863 bands : Positive integer, or list of positive integers
864 Band
865 index, or indices of a group of bands (e.g. all occupied bands
866 below a gap).
867 nk : Positive integer, or tuple of 2 positive integers, default 30
868 Number of k-points along each of the two
869 reciprocal lattice vectors spanning the plane.
870 plane : Tuple of two distinct integers
871 Default value (0, 1).
872 3D lattices only: the reciprocal vectors
873 :math:`\mathbf{b}_i, \mathbf{b}_j` spanning the plane of the
874 Brillouin zone. The flux is oriented along the remaining
875 primitive vector :math:`\mathbf{a}_l` (along +z in 2D).
876 k_fixed : Real number, default 0
877 3D lattices only: the
878 fractional coordinate of the plane along the remaining reciprocal
879 vector :math:`\mathbf{b}_l` (e.g. :math:`k_z` in units of
880 :math:`|\mathbf{b}_3|` for ``plane=(0, 1)``).
882 Returns
883 -------
884 curv : Real ndarray, shape (nk1, nk2)
885 Berry curvature
886 (flux through each plaquette, in radians). Summing *curv* and
887 dividing by :math:`2\pi` gives the Chern number, see
888 *chern_number*.
889 '''
890 error_handling.dim_min(self.dim, 2)
891 if isinstance(bands, int):
892 bands = [bands]
893 error_handling.band_indices(bands, self.norb)
894 if isinstance(nk, int):
895 nk = (nk, nk)
896 error_handling.nk(nk, 2)
897 error_handling.plane(plane, self.dim)
898 error_handling.real_number(k_fixed, 'k_fixed')
899 n1, n2 = nk
900 ks = self._plane_mesh(nk, plane, k_fixed)
901 if not self.is_hermitian():
902 # bands labelled by Re E are continuous only across a real line gap
903 en = self._eigs(ks.reshape(-1, self.dim))
904 error_handling.line_gap(en.real, bands, 'real')
905 error_handling.band_continuity(en.reshape(n1, n2, self.norb), bands)
906 v1 = self._subspaces(ks.reshape(-1, self.dim), bands).reshape(n1, n2, self.norb, len(bands))
907 return self._flux(v1, plane)
909 def _flux(self, v1: NDArray[np.complex128], plane: tuple[int, int]) -> NDArray[np.float64]:
910 '''
911 Private method. Fukui-Hatsugai-Suzuki flux through each plaquette of
912 the mesh of *_plane_mesh*, from orthonormal bases *v1* of a subspace
913 at its nodes (shape (n1, n2, norb, n)), oriented as in *berry_curvature*.
914 '''
915 # the other corners of each plaquette: k + b_i/n1, k + b_i/n1 + b_j/n2, k + b_j/n2
916 v2 = np.roll(v1, -1, axis=0)
917 v3 = np.roll(v2, -1, axis=1)
918 v4 = np.roll(v1, -1, axis=1)
920 def overlap(a, b):
921 return np.linalg.det(a.conj().swapaxes(-1, -2) @ b)
922 link = overlap(v1, v2) * overlap(v2, v3) * overlap(v3, v4) * overlap(v4, v1)
923 curv = -np.angle(link)
924 # The corners k, k+b_i/n1, k+b_i/n1+b_j/n2, k+b_j/n2 run
925 # counterclockwise about the normal only if (b_i x b_j).normal > 0;
926 # otherwise every flux comes out with the opposite sign.
927 return self._plane_orientation(plane) * curv
929 def _plane_mesh(
930 self, nk: tuple[int, int], plane: tuple[int, int], k_fixed: float,
931 ) -> NDArray[np.float64]:
932 '''
933 Private method. k-points, shape (n1, n2, dim), of the uniform mesh of
934 the Brillouin-zone plane spanned by b_i, b_j (plane = (i, j)), at
935 fractional coordinate k_fixed along the remaining reciprocal vector.
936 '''
937 n1, n2 = nk
938 i, j = plane
939 rest = [l for l in range(self.dim) if l not in plane]
940 fracs = np.zeros((n1, n2, self.dim))
941 fracs[:, :, i] = (np.arange(n1) / n1)[:, None]
942 fracs[:, :, j] = (np.arange(n2) / n2)[None, :]
943 for l in rest:
944 fracs[:, :, l] = k_fixed
945 return fracs @ self.rec_vec_k
947 def _plane_orientation(self, plane: tuple[int, int]) -> float:
948 '''
949 Private method. +1 if (b_i, b_j) is right-handed about the plane's
950 normal (+z in 2D; the remaining primitive vector in 3D), else -1.
951 '''
952 b = [np.zeros(3) for _ in range(2)]
953 for bb, idx in zip(b, plane):
954 bb[:self.space_dim] = self.rec_vec[idx]
955 if self.dim == 3:
956 normal = np.array(self.lat.prim_vec[3 - sum(plane)], dtype='f8')
957 else:
958 a = [np.zeros(3), np.zeros(3)]
959 for aa, vec in zip(a, self.lat.prim_vec):
960 aa[:self.space_dim] = vec
961 normal = np.cross(a[0], a[1])
962 if abs(normal[2]) > 1e-12:
963 normal = np.array([0., 0., 1.])
964 return float(np.sign(np.dot(np.cross(b[0], b[1]), normal)))
966 def _subspace(self, k: NDArray[np.float64], bands: list[int]) -> NDArray[np.complex128]:
967 '''
968 Private method. Orthonormal basis (columns) of the eigenvectors of
969 *bands* at *k* (in the periodic gauge, orbital positions ignored).
970 With an overlap S(k), the Lowdin-orthonormalized S^(1/2) v.
971 '''
972 return self._subspaces(np.asarray(k, dtype='f8')[None], bands)[0]
974 def _subspaces(self, ks: NDArray[np.float64], bands: list[int]) -> NDArray[np.complex128]:
975 '''
976 Private method. *_subspace* at the k-points *ks* (shape (nk, dim)),
977 shape (nk, norb, len(bands)). S^(1/2) comes from the eigenvalues of
978 the (Hermitian, positive) overlap.
979 '''
980 _, vn = self._eigs(ks, eigenvec=True)
981 if self._overlap_hop:
982 sv, us = np.linalg.eigh(self._overlaps(ks))
983 vn = (us * np.sqrt(sv)[:, None, :]) @ (us.conj().transpose(0, 2, 1) @ vn)
984 return vn[:, :, bands]
986 def biorthogonal_berry_curvature(
987 self, bands: int | list[int], nk: int | tuple[int, int] = 30, kind: str = 'LR',
988 gap: str = 'real', plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
989 ) -> NDArray[np.float64]:
990 r'''
991 Get the Berry curvature of a group of bands of a (non-Hermitian)
992 model from its right and left eigenvectors, :math:`H|R_n\rangle =
993 E_n|R_n\rangle` and :math:`H^\dagger|L_n\rangle = E_n^*|L_n\rangle`,
994 normalized by :math:`\langle L_m|R_n\rangle = \delta_{mn}` (Shen, Zhen
995 and Fu, Phys. Rev. Lett. 120, 146402 (2018)). The four connections
997 .. math::
999 \mathbf{A}^{\alpha\beta} = i\langle u^\alpha|\nabla_{\mathbf{k}}u^\beta\rangle\, ,
1000 \qquad \alpha, \beta \in \{L, R\}\, ,
1002 have different curvatures point by point, but their integrals, the
1003 Chern numbers :math:`C^{LR} = C^{RL} = C^{RR} = C^{LL}`, are the same
1004 integer. The flux through each plaquette is computed as in
1005 *berry_curvature* (Fukui-Hatsugai-Suzuki), with the links
1006 :math:`\det\langle u^\alpha(\mathbf{k})|u^\beta(\mathbf{k}')\rangle` (for
1007 RR and LL, the phase does not depend on the normalization). For a
1008 Hermitian model all four are the curvature of *berry_curvature*.
1010 The bands are ordered at every k-point by the real part of their
1011 energy (*gap* = 'real') or by its imaginary part ('imaginary'), and
1012 *bands* must be separated from the others by a line gap of that kind
1013 over the whole zone -- a line :math:`\mathrm{Re}\,E = E_0` (or
1014 :math:`\mathrm{Im}\,E = E_0`) that no band crosses. Otherwise a
1015 ValueError is raised: the gap closes at exceptional points (see
1016 *tbkit.exceptional.find_exceptional_points*), where the Chern number
1017 can change.
1019 Parameters
1020 ----------
1021 bands : Positive integer, or list of positive integers
1022 Band
1023 indices in the order set by *gap*.
1024 nk : Positive integer, or tuple of 2 positive integers, default 30
1025 See *berry_curvature*.
1026 kind : 'LR', 'RL', 'RR' or 'LL', default 'LR'
1027 :math:`\alpha\beta` above.
1028 gap : 'real' or 'imaginary', default 'real'
1029 Kind of line
1030 gap, and the order of the bands.
1031 plane : Tuple of two integers
1032 Default value (0, 1). 3D only, see
1033 *berry_curvature*.
1034 k_fixed : Real number, default 0
1035 3D only, see *berry_curvature*.
1037 Returns
1038 -------
1039 curv : Real ndarray, shape (nk1, nk2)
1040 Flux through each
1041 plaquette, in radians (sign convention of *berry_curvature*).
1042 '''
1043 error_handling.dim_min(self.dim, 2)
1044 if isinstance(bands, int):
1045 bands = [bands]
1046 error_handling.band_indices(bands, self.norb)
1047 if isinstance(nk, int):
1048 nk = (nk, nk)
1049 error_handling.nk(nk, 2)
1050 error_handling.biorthogonal_kind(kind)
1051 error_handling.gap_kind(gap)
1052 error_handling.plane(plane, self.dim)
1053 error_handling.real_number(k_fixed, 'k_fixed')
1054 error_handling.no_overlap(self._overlap_hop)
1055 n1, n2 = nk
1056 ks = self._plane_mesh(nk, plane, k_fixed)
1057 w, vr = np.linalg.eig(self._hams(ks.reshape(n1 * n2, -1)))
1058 order = np.argsort(w.real if gap == 'real' else w.imag, axis=1, kind='stable')
1059 en = np.take_along_axis(w, order, axis=1).reshape(n1, n2, self.norb)
1060 vr = np.take_along_axis(vr, order[:, None, :], axis=2)
1061 # biorthonormal: <L_m|R_n> = delta_mn, the rows of R^-1
1062 right = vr[:, :, bands].reshape(n1, n2, self.norb, len(bands))
1063 left = np.linalg.inv(vr).conj().transpose(0, 2, 1)[:, :, bands].reshape(right.shape)
1064 error_handling.line_gap(en.reshape(-1, self.norb).real if gap == 'real'
1065 else en.reshape(-1, self.norb).imag, bands, gap)
1066 error_handling.band_continuity(en, bands)
1067 bra, ket = {'LR': (left, right), 'RL': (right, left),
1068 'RR': (right, right), 'LL': (left, left)}[kind]
1069 # one link per oriented edge, U = det<u^alpha(k)|u^beta(k + dk)>, and
1070 # its inverse when the edge is run backwards: <L_a|R_b> and <L_b|R_a>
1071 # are not conjugate, so using both would spoil the exact
1072 # cancellation of the shared edges (for RR, 1/U has the phase of U*).
1073 bra_h = bra.conj().swapaxes(-1, -2)
1074 link = np.stack([np.linalg.det(bra_h @ np.roll(ket, -1, axis=0)),
1075 np.linalg.det(bra_h @ np.roll(ket, -1, axis=1))])
1076 flux = (link[0] * np.roll(link[1], -1, axis=0)
1077 / (np.roll(link[0], -1, axis=1) * link[1]))
1078 return self._plane_orientation(plane) * -np.angle(flux)
1080 def biorthogonal_chern_number(
1081 self, bands: int | list[int], nk: int | tuple[int, int] = 30, kind: str = 'LR',
1082 gap: str = 'real', plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
1083 ) -> float:
1084 r'''
1085 Get the Chern number of a line-gapped group of bands of a
1086 (non-Hermitian) model, :math:`C^{\alpha\beta} = \frac{1}{2\pi}\int_{BZ}
1087 \Omega^{\alpha\beta}\,d^2k`, the same integer for the four kinds
1088 LR, RL, RR, LL (see *biorthogonal_berry_curvature*). It equals the
1089 Hermitian Chern number of *chern_number* as long as the line gap stays
1090 open.
1092 Parameters
1093 ----------
1094 bands
1095 See *biorthogonal_berry_curvature*.
1096 nk
1097 See *biorthogonal_berry_curvature*.
1098 kind : 'LR', 'RL', 'RR' or 'LL', default 'LR'
1099 gap : 'real' or 'imaginary', default 'real'
1100 plane
1101 See *berry_curvature*.
1102 k_fixed
1103 See *berry_curvature*.
1105 Returns
1106 -------
1107 chern : Real number, close to an integer
1108 '''
1109 return self.biorthogonal_berry_curvature(bands, nk, kind, gap, plane, k_fixed).sum() / (2*PI)
1111 def chern_number(
1112 self, bands: int | list[int], nk: int | tuple[int, int] = 30,
1113 plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
1114 ) -> float:
1115 r'''
1116 Get the Chern number of a group of bands:
1118 .. math::
1120 C = \frac{1}{2\pi}\int_{BZ} \Omega(\mathbf{k})\, d^2k
1122 an integer (up to the numerical precision set by *nk*) for a group
1123 of bands that is isolated from the rest of the spectrum by a gap
1124 everywhere in the Brillouin zone. See *berry_curvature*. For a
1125 non-Hermitian model, *bands* (ordered by Re E) must be isolated by a
1126 real line gap, or a ValueError is raised; *biorthogonal_chern_number*
1127 also handles imaginary line gaps and the left eigenvectors.
1129 Parameters
1130 ----------
1131 bands : Positive integer, or list of positive integers
1132 Band
1133 index, or indices of a group of bands (e.g. all occupied bands
1134 below a gap).
1135 nk : Positive integer, or tuple of 2 positive integers, default 30
1136 Number of k-points along each reciprocal
1137 lattice vector.
1138 plane : Tuple of two integers
1139 Default value (0, 1). 3D lattices
1140 only, see *berry_curvature*.
1141 k_fixed : Real number, default 0
1142 3D lattices only, see
1143 *berry_curvature*: the Chern number of the plane at this
1144 fractional coordinate (it jumps across a Weyl point).
1146 Returns
1147 -------
1148 chern : Real number, close to an integer
1149 '''
1150 return self.berry_curvature(bands, nk, plane, k_fixed).sum() / (2*PI)
1152 def sector_chern_numbers(
1153 self, op, bands: int | list[int], nk: int | tuple[int, int] = 30,
1154 plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
1155 ) -> tuple[float, float]:
1156 r'''
1157 Get the Chern numbers of the two sectors into which a Hermitian
1158 operator :math:`O` splits a group of bands: at every k-point, the
1159 projected operator :math:`P(\mathbf{k})\,O\,P(\mathbf{k})`
1160 (:math:`P` the projector on *bands*) is diagonalized within the
1161 bands, and its eigenvectors with positive and negative eigenvalues
1162 span the two sectors, whose Chern numbers :math:`C_\pm` follow as in
1163 *berry_curvature*. They are well defined as long as the spectrum of
1164 :math:`POP` keeps a gap around zero over the whole plane, even if
1165 :math:`O` does not commute with :math:`H` (Prodan, Phys. Rev. B 80,
1166 125327 (2009)); otherwise a ValueError is raised. See
1167 *spin_chern_number* and *mirror_chern_number*.
1169 Parameters
1170 ----------
1171 op
1172 Complex ndarray, shape (norb, norb), or callable of k
1173 returning one: the Hermitian operator :math:`O`.
1174 bands : Band index, or list of band indices
1175 nk : Positive integer, or tuple of 2 positive integers, default 30
1176 plane : Tuple of two integers
1177 Default value (0, 1). 3D only, see *berry_curvature*.
1178 k_fixed : Real number, default 0
1179 3D only, see *berry_curvature*.
1181 Returns
1182 -------
1183 c_plus
1184 Real number, close to an integer: Chern number
1185 of the sector with :math:`POP > 0`.
1186 c_minus : Real number: that of the sector with :math:`POP < 0`
1187 :math:`C_+ + C_-` is the Chern number of *bands*.
1188 '''
1189 bands, nk, ks = self._check_sectors(bands, nk, plane, k_fixed)
1190 if callable(op):
1191 ops = np.array([self._operator(op, k) for k in ks])
1192 else:
1193 ops = self._operator(op, ks[0])[None]
1194 error_handling.hermitian_operator(ops)
1195 return self._sector_cherns(ops, bands, nk, ks, plane)
1197 def _check_sectors(
1198 self, bands, nk, plane, k_fixed,
1199 ) -> tuple[list[int], tuple[int, int], NDArray[np.float64]]:
1200 '''
1201 Private method. Validate the arguments of the sector Chern numbers;
1202 return them with the k-points of the plane mesh, shape (n1 n2, dim).
1203 '''
1204 error_handling.dim_min(self.dim, 2)
1205 if isinstance(bands, int):
1206 bands = [bands]
1207 error_handling.band_indices(bands, self.norb)
1208 if isinstance(nk, int):
1209 nk = (nk, nk)
1210 error_handling.nk(nk, 2)
1211 error_handling.plane(plane, self.dim)
1212 error_handling.real_number(k_fixed, 'k_fixed')
1213 error_handling.hermitian_kspace(self.is_hermitian(), self._overlap_hop)
1214 return bands, nk, self._plane_mesh(nk, plane, k_fixed).reshape(-1, self.dim)
1216 def _sector_cherns(
1217 self, ops: NDArray[np.complex128], bands: list[int], nk: tuple[int, int],
1218 ks: NDArray[np.float64], plane: tuple[int, int],
1219 ) -> tuple[float, float]:
1220 '''
1221 Private method. *sector_chern_numbers* with the Hermitian operator
1222 evaluated at the k-points *ks* (shape (n1 n2, norb, norb), or
1223 (1, norb, norb) if constant).
1224 '''
1225 n1, n2 = nk
1226 v = self._subspaces(ks, bands)
1227 w, u = np.linalg.eigh(v.conj().transpose(0, 2, 1) @ ops @ v)
1228 n_minus = error_handling.projected_gap(w)
1229 sectors = v @ u
1230 c_minus = self._flux(sectors[:, :, :n_minus].reshape(n1, n2, self.norb, -1), plane)
1231 c_plus = self._flux(sectors[:, :, n_minus:].reshape(n1, n2, self.norb, -1), plane)
1232 return float(c_plus.sum() / (2*PI)), float(c_minus.sum() / (2*PI))
1234 def spin_chern_number(
1235 self, bands: list[int], nk: int | tuple[int, int] = 30, s_z=None,
1236 plane: tuple[int, int] = (0, 1), k_fixed: float = 0.,
1237 ) -> float:
1238 r'''
1239 Get the spin Chern number of a group of bands (Prodan, Phys. Rev. B
1240 80, 125327 (2009); Sheng, Weng, Sheng and Haldane, Phys. Rev. Lett.
1241 97, 036808 (2006)),
1243 .. math::
1245 C_s = \frac{C_+ - C_-}{2}\, ,
1247 with :math:`C_\pm` the Chern numbers of the two sectors of the
1248 projected spin operator :math:`Ps_zP` (see *sector_chern_numbers*).
1249 When :math:`s_z` is conserved they are the Chern numbers of the two
1250 spins; Rashba coupling mixes the spins, but :math:`C_s` stays
1251 quantized, and unchanged, as long as the spectrum of :math:`Ps_zP`
1252 keeps a gap around zero. With time reversal, :math:`C_s` modulo 2 is
1253 the :math:`\mathbb{Z}_2` invariant of *z2_invariant*.
1255 Parameters
1256 ----------
1257 bands : List of band indices (e.g. the occupied bands)
1258 nk : Positive integer, or tuple of 2 positive integers, default 30
1259 s_z : Complex ndarray, shape (norb, norb), or callable of k
1260 Default value None: :math:`\sigma_z` on every site of a model
1261 built with ``spin=True``. The spin operator.
1262 plane : Tuple of two integers
1263 Default value (0, 1). 3D only, see *berry_curvature*.
1264 k_fixed : Real number, default 0
1265 3D only, see *berry_curvature*.
1267 Returns
1268 -------
1269 c_s : Real number, close to an integer
1270 '''
1271 if s_z is None:
1272 error_handling.spinful(self.spin)
1273 s_z = np.kron(np.eye(self.norb // 2), PAULI['z'])
1274 c_plus, c_minus = self.sector_chern_numbers(s_z, bands, nk, plane, k_fixed)
1275 return (c_plus - c_minus) / 2
1277 def mirror_chern_number(
1278 self, mirror, bands: list[int], nk: int | tuple[int, int] = 30,
1279 plane: tuple[int, int] = (0, 1), k_fixed: float = 0., tol: float = 1e-8,
1280 ) -> float:
1281 r'''
1282 Get the mirror Chern number of a group of bands on a mirror-invariant
1283 plane of the Brillouin zone (Teo, Fu and Kane, Phys. Rev. B 78,
1284 045426 (2008); Hsieh et al., Nat. Commun. 3, 982 (2012)),
1286 .. math::
1288 n_M = \frac{C_{+} - C_{-}}{2}\, ,
1290 with :math:`C_\pm` the Chern numbers of the bands of mirror
1291 eigenvalue :math:`+i` and :math:`-i` (:math:`M^2 = -1`, spinful
1292 electrons) or :math:`+1` and :math:`-1` (:math:`M^2 = +1`). The
1293 mirror must commute with :math:`H(\mathbf{k})` at every point of the
1294 plane: in 3D, the plane fixed by the reflection (e.g.
1295 :math:`k_z = 0` or :math:`\pi` for :math:`z\to-z`); in 2D, the whole
1296 zone, for a reflection of the third axis. A topological crystalline
1297 insulator such as SnTe has :math:`n_M = 2` and every
1298 :math:`\mathbb{Z}_2` index zero (:math:`\nu = n_M` modulo 2 on the plane).
1300 Parameters
1301 ----------
1302 mirror
1303 Complex ndarray, shape (norb, norb), or callable of k:
1304 the unitary mirror operator :math:`M`, with :math:`M^2 = \pm1`.
1305 bands : List of band indices (e.g. the occupied bands)
1306 nk : Positive integer, or tuple of 2 positive integers, default 30
1307 plane : Tuple of two integers
1308 Default value (0, 1). 3D only, see *berry_curvature*.
1309 k_fixed : Real number, default 0
1310 3D only: the
1311 mirror-invariant plane (0 or 0.5 for a reflection of the remaining axis).
1312 tol : Positive real, default 1e-8
1313 Tolerance of the
1314 checks :math:`M^2 = \pm1` and :math:`[M, H(\mathbf{k})] = 0`.
1316 Returns
1317 -------
1318 n_m : Real number, close to an integer
1319 '''
1320 bands, nk, ks = self._check_sectors(bands, nk, plane, k_fixed)
1321 error_handling.positive_real(tol, 'tol')
1322 if callable(mirror):
1323 mats = np.array([self._operator(mirror, k) for k in ks])
1324 else:
1325 mats = self._operator(mirror, ks[0])[None]
1326 sign = error_handling.mirror_square(mats @ mats, tol)
1327 hams = self._hams(ks)
1328 error_handling.commutes(float(np.max(np.abs(mats @ hams - hams @ mats))), tol)
1329 # Hermitian, with eigenvalue +1 on the sector M = +i (M = +1 if M^2 = 1)
1330 herm = mats if sign > 0 else -1j * mats
1331 c_plus, c_minus = self._sector_cherns(herm, bands, nk, ks, plane)
1332 return (c_plus - c_minus) / 2
1334 # ------------------------------------------------------------------
1335 # Anomalous and spin Hall conductivities (Kubo formula)
1336 # ------------------------------------------------------------------
1338 def _check_static(self) -> None:
1339 '''
1340 Private method. Methods that differentiate the stored hoppings call
1341 it first (a Floquet model overrides it to refuse).
1342 '''
1344 def _bloch_sum(
1345 self, hops: list, k_cart: NDArray[np.float64], directions: Sequence[NDArray[np.float64]] = (),
1346 positions: bool = False, A: NDArray[np.float64] | None = None,
1347 ) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]:
1348 r'''
1349 Private method. The Bloch sum :math:`\sum t\,e^{i\mathbf{k}\cdot\mathbf{d}}`
1350 of a hopping list over many k-points at once (*k_cart*, shape
1351 (nk, space_dim)), and its derivatives
1352 :math:`\sum i(\mathbf{u}\cdot\mathbf{d})\,t\,e^{i\mathbf{k}\cdot\mathbf{d}}`
1353 along the Cartesian unit vectors *directions*, with
1354 :math:`\mathbf{d} = \mathbf{R}` (plus :math:`\boldsymbol\tau_j-\boldsymbol\tau_i`
1355 with *positions*). A vector potential *A* multiplies each term by the
1356 Peierls phase :math:`e^{i\mathbf{A}\cdot(\mathbf{R}+\boldsymbol\tau_j-\boldsymbol\tau_i)}`
1357 (see *get_ham_peierls*). Shapes (nk, norb, norb) and
1358 (len(directions), nk, norb, norb). Every Bloch matrix of the model
1359 (*get_ham*, *get_overlap*, *get_ham_peierls*, *_bloch_derivatives*)
1360 is built here.
1362 When the hoppings fill at least *group_fill* of the blocks
1363 :math:`T_{\mathbf{R}}` (one norb x norb matrix per distinct
1364 :math:`\mathbf{R}`), the sum is one matrix product
1365 :math:`\sum_{\mathbf{R}} e^{i\mathbf{k}\cdot\mathbf{R}}\,T_{\mathbf{R}}`,
1366 with the orbital positions as the phases
1367 :math:`e^{-i\mathbf{k}\cdot\boldsymbol\tau_i}` and
1368 :math:`e^{i\mathbf{k}\cdot\boldsymbol\tau_j}` of its rows and
1369 columns. Otherwise, each hopping is summed on its own.
1370 '''
1371 n, nk = self.norb, len(k_cart)
1372 i = np.array([h[0] for h in hops], dtype=int)
1373 j = np.array([h[1] for h in hops], dtype=int)
1374 d = np.array([h[2] for h in hops], dtype='f8').reshape(len(hops), self.space_dim)
1375 t = np.array([h[3] for h in hops], dtype='c16')
1376 if positions or A is not None:
1377 tau = self.orbital_positions()
1378 bond = d + tau[j] - tau[i]
1379 if A is not None:
1380 # the Peierls phase of a bond does not depend on k
1381 t = t * np.exp(1j * (bond @ A))
1382 if len(hops):
1383 cells, cell = np.unique(d, axis=0, return_inverse=True)
1384 if len(hops) >= self.group_fill * len(cells) * n * n:
1385 return self._bloch_grouped(i, j, t, cells, cell.ravel(), k_cart, directions,
1386 tau if positions else None)
1387 if positions:
1388 d = bond
1389 w = np.exp(1j * (k_cart @ d.T)) * t[None, :]
1390 # accumulate term m of k-point p in entry (p, i_m, j_m): repeated
1391 # (i, j) pairs add up, as they must
1392 index = (np.arange(nk)[:, None] * n * n + i * n + j).ravel()
1394 def scatter(v):
1395 size = nk * n * n
1396 return (np.bincount(index, v.real.ravel(), size)
1397 + 1j * np.bincount(index, v.imag.ravel(), size)).reshape(nk, n, n)
1398 mat = scatter(w)
1399 dmat = np.array([scatter(w * (1j * (d @ u))[None, :]) for u in directions],
1400 dtype='c16').reshape(len(directions), nk, n, n)
1401 return mat, dmat
1403 def _bloch_grouped(
1404 self, i: NDArray[np.int_], j: NDArray[np.int_], t: NDArray[np.complex128],
1405 cells: NDArray[np.float64], cell: NDArray[np.int_], k_cart: NDArray[np.float64],
1406 directions: Sequence[NDArray[np.float64]], tau: NDArray[np.float64] | None,
1407 ) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]:
1408 r'''
1409 Private method. *_bloch_sum* as one matrix product over the distinct
1410 lattice vectors *cells* (hopping m connects to cells[cell[m]]), with
1411 the orbital positions *tau* in the phases (None: periodic gauge).
1412 The derivative along :math:`\mathbf{u}` weights each block by
1413 :math:`i\mathbf{u}\cdot\mathbf{R}`, plus
1414 :math:`i\mathbf{u}\cdot(\boldsymbol\tau_j-\boldsymbol\tau_i)` with *tau*.
1415 '''
1416 n, nk = self.norb, len(k_cart)
1417 blocks = np.zeros((len(cells), n * n), dtype='c16')
1418 np.add.at(blocks, (cell, i * n + j), t)
1419 phases = np.exp(1j * (k_cart @ cells.T))
1420 mat = (phases @ blocks).reshape(nk, n, n)
1421 dmat = np.empty((len(directions), nk, n, n), dtype='c16')
1422 for a, u in enumerate(directions):
1423 dmat[a] = ((phases * (1j * (cells @ u))[None, :]) @ blocks).reshape(nk, n, n)
1424 if tau is not None:
1425 x = tau @ u
1426 dmat[a] += 1j * (x[None, :] - x[:, None])[None] * mat
1427 if tau is not None:
1428 orb = np.exp(1j * (k_cart @ tau.T))
1429 row, col = orb.conj()[:, :, None], orb[:, None, :]
1430 mat = row * mat * col
1431 dmat = row[None] * dmat * col[None]
1432 return mat, dmat
1434 def _bloch_derivatives(
1435 self, ks: NDArray[np.float64], directions: list[NDArray[np.float64]], positions: bool,
1436 params: dict | None = None,
1437 ) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]:
1438 r'''
1439 Private method. :math:`H(\mathbf{k})` and its exact derivatives
1440 :math:`\partial H/\partial k_u` along the Cartesian unit vectors
1441 *directions*, at the k-points *ks* (shape (nk, dim), coordinates of
1442 *get_ham*). With an overlap, the Lowdin-orthogonalized
1443 :math:`H' = S^{-1/2}HS^{-1/2}` (the eigenvectors :math:`S^{1/2}v` of
1444 the topology tools) and its derivative, with
1445 :math:`\partial S^{-1/2}` from the Daleckii-Krein formula in the
1446 eigenbasis :math:`S = \sum_a s_a|a\rangle\langle a|`:
1447 :math:`\langle a|\partial S^{-1/2}|b\rangle = \langle a|\partial S|b\rangle
1448 (s_a^{-1/2}-s_b^{-1/2})/(s_a-s_b)`, :math:`-s_a^{-3/2}/2` when :math:`s_a = s_b`.
1449 The value functions take *params* (default: *self.params*).
1450 '''
1451 k_cart = ks @ self.k_basis.T
1452 hops = self._hop if params is None else self._hops(params)
1453 ham, dham = self._bloch_sum(hops, k_cart, directions, positions)
1454 ham = ham + (np.diag(self.onsite) + self._onsite_offdiag)[None]
1455 if positions and self._position_hop:
1456 # the velocity i[H, r] with the whole position operator: the
1457 # derivative in the gauge of the orbital positions, plus
1458 # i[H, A_u] with the connection of the other elements
1459 error_handling.no_overlap(bool(self._overlap_hop))
1460 conn = self._connection(k_cart, directions)[0]
1461 dham = dham + 1j * (ham[None] @ conn - conn @ ham[None])
1462 if not self._overlap_hop:
1463 return ham, dham
1464 s, ds = self._bloch_sum(self._overlap_hop, k_cart, directions, positions)
1465 s = s + np.eye(self.norb)[None]
1466 sv, vs = np.linalg.eigh(s)
1467 error_handling.positive_overlap(sv.min())
1468 r = sv ** -0.5
1469 diff = sv[:, :, None] - sv[:, None, :]
1470 close = np.abs(diff) < 1e-10
1471 lk = np.where(close, -0.5 * sv[:, :, None] ** -1.5,
1472 (r[:, :, None] - r[:, None, :]) / np.where(close, 1., diff))
1473 vh = vs.conj().transpose(0, 2, 1)
1474 s_inv = (vs * r[:, None, :]) @ vh
1475 ds_inv = vs @ ((vh @ ds @ vs) * lk) @ vh
1476 dham = ds_inv @ ham @ s_inv + s_inv @ dham @ s_inv + s_inv @ ham @ ds_inv
1477 return s_inv @ ham @ s_inv, dham
1479 def _connection(
1480 self, k_cart: NDArray[np.float64], directions: Sequence[NDArray[np.float64]],
1481 derivatives: bool = False,
1482 ) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]:
1483 r'''
1484 Private method. The Berry connection of the orbitals beyond their
1485 positions, :math:`A_u(\mathbf{k}) = \sum_{\mathbf{R}}(\mathbf{u}\cdot\mathbf{r}_{ij}(\mathbf{R}))\,
1486 e^{i\mathbf{k}\cdot(\mathbf{R}+\boldsymbol\tau_j-\boldsymbol\tau_i)}` with
1487 :math:`\mathbf{r}_{ij}(\mathbf{R}) = \langle i,\mathbf{0}|\mathbf{r}|j,\mathbf{R}\rangle`
1488 the position matrix elements of *_position_hop*, in the gauge of the
1489 orbital positions (*positions=True*), along each Cartesian unit
1490 vector *directions*: shape (len(directions), nk, norb, norb). With
1491 *derivatives*, also :math:`\partial_v A_u`, shape
1492 (len(directions), len(directions), nk, norb, norb) (u first).
1493 '''
1494 conn, dconn = [], []
1495 for u in directions:
1496 hops = [(i, j, R, complex(r @ u)) for i, j, R, r in self._position_hop]
1497 a, da = self._bloch_sum(hops, k_cart, directions if derivatives else (), True)
1498 conn.append(a)
1499 dconn.append(da)
1500 return np.array(conn), np.array(dconn)
1502 def _kubo(
1503 self, ks: NDArray[np.float64], e_fermi: NDArray[np.float64], temperature: float,
1504 directions: list[NDArray[np.float64]], pairs: list[tuple[int, int]], positions: bool,
1505 spin_op: NDArray[np.complex128] | None, response: str = 'hall',
1506 ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
1507 r'''
1508 Private method. The Kubo curvature
1509 :math:`F(\mathbf{k}) = \sum_{n\neq m}P_{nm}\,\mathrm{Im}[X_{nm}Y_{mn}]/(E_n-E_m)^2`
1510 at each k-point, Fermi energy and pair (X, Y) of velocities (X the
1511 spin current :math:`\{s, v\}/2` if *spin_op*), with the weights
1512 :math:`P_{nm}` of *response* (see *_response_weights*), e.g.
1513 :math:`P_{nm} = -(f_n-f_m)` for the Hall conductivity
1514 (:math:`F = \sum_n f_n\Omega_n`). Shape (nk, len(e_fermi), len(pairs)).
1515 Pairs of degenerate states (equal weights) are skipped, so :math:`F`
1516 stays finite at band crossings below or above the Fermi level. Also
1517 returns, per k-point, the occupation-independent size of the
1518 curvature, :math:`\sum_{n\neq m}|\mathrm{Im}[X_{nm}Y_{mn}]|/(E_n-E_m)^2`,
1519 which locates the hot spots of the adaptive refinement.
1521 With position matrix elements beyond the orbital positions
1522 (*_position_hop*, ``positions=True``), the velocities include
1523 :math:`i[H, A]` (see *_bloch_derivatives*) and the band curvature
1524 gains the curvature of the orbitals' own connection (Wang, Yates,
1525 Souza and Vanderbilt, Phys. Rev. B 74, 195118 (2006)):
1526 :math:`\Omega_n = -2\,\mathrm{Im}\sum_{m\neq n}v^a_{nm}v^b_{mn}/(E_n-E_m)^2
1527 + \langle n|\partial_aA_b-\partial_bA_a-i[A_a, A_b]|n\rangle`. Only the
1528 responses :math:`\sum_n w_n\Omega_n` take it ('hall', 'nernst',
1529 'thermal' without *spin_op*); the others are refused upstream.
1530 '''
1531 out = np.zeros((len(ks), len(e_fermi), len(pairs)))
1532 hot = np.zeros(len(ks))
1533 chunk = max(1, 400000 // self.norb ** 2)
1534 internal = positions and bool(self._position_hop)
1535 for c0 in range(0, len(ks), chunk):
1536 ham, dham = self._bloch_derivatives(ks[c0:c0 + chunk], directions, positions)
1537 en, vec = np.linalg.eigh(ham)
1538 vh = vec.conj().transpose(0, 2, 1)
1539 vel = [vh @ dh @ vec for dh in dham]
1540 de = en[:, :, None] - en[:, None, :]
1541 degenerate = np.abs(de) < 1e-9
1542 inv2 = np.where(degenerate, 0., 1. / np.where(degenerate, 1., de) ** 2)
1543 if spin_op is not None:
1544 s_e = vh @ spin_op @ vec
1545 if internal:
1546 conn, dconn = self._connection(ks[c0:c0 + chunk] @ self.k_basis.T, directions, True)
1547 for p, (a, b) in enumerate(pairs):
1548 x = vel[a] if spin_op is None else 0.5 * (s_e @ vel[a] + vel[a] @ s_e)
1549 w = np.imag(x * vel[b].transpose(0, 2, 1)) * inv2
1550 hot[c0:c0 + chunk] += np.abs(w).sum(axis=(1, 2))
1551 if internal:
1552 # the curvature of the connection, on the diagonal of the eigenbasis
1553 curv = dconn[b, a] - dconn[a, b] - 1j * (conn[a] @ conn[b] - conn[b] @ conn[a])
1554 omega = np.real(np.einsum('kni,kij,kjn->kn', vh, curv, vec))
1555 hot[c0:c0 + chunk] += np.abs(omega).sum(axis=1)
1556 for e, mu in enumerate(e_fermi):
1557 weights = _response_weights(en, float(mu), temperature, response)
1558 out[c0:c0 + chunk, e, p] = np.einsum('knm,knm->k', weights, w)
1559 if internal:
1560 occ = _response_occupations(en, float(mu), temperature, response)
1561 out[c0:c0 + chunk, e, p] += np.einsum('kn,kn->k', occ, omega)
1562 return out, hot
1564 def _hall(
1565 self, e_fermi, temperature, nk, plane, k_fixed, positions, refine, refine_fraction,
1566 spin_axis, response='hall',
1567 ):
1568 '''
1569 Private method. Validate, set the geometry and mesh, integrate the
1570 Kubo curvature (with the adaptive refinement), for
1571 *hall_conductivity* (spin_axis None) and *spin_hall_conductivity*,
1572 and, with the weights of *response*, for *orbital_magnetization*,
1573 *anomalous_nernst_conductivity* and *thermal_hall_conductivity*.
1574 '''
1575 self._check_static()
1576 error_handling.dim_min(self.dim, 2)
1577 error_handling.hermitian_model(self.is_hermitian())
1578 error_handling.fermi_energies(e_fermi)
1579 if response in ('nernst', 'thermal'):
1580 error_handling.positive_real(temperature, 'temperature')
1581 else:
1582 error_handling.positive_real_zero(temperature, 'temperature')
1583 error_handling.plane(plane, self.dim)
1584 error_handling.k_fixed_hall(k_fixed, self.dim, spin_axis is None)
1585 error_handling.boolean(positions, 'positions')
1586 if spin_axis is not None or response == 'magnetization':
1587 error_handling.no_position_elements(positions and bool(self._position_hop),
1588 'spin_hall_conductivity' if spin_axis is not None
1589 else 'orbital_magnetization')
1590 error_handling.positive_int(refine, 'refine')
1591 error_handling.refine_fraction(refine_fraction)
1592 full = self.dim == 3 and k_fixed is None
1593 axes = [0, 1, 2] if full else list(plane)
1594 if isinstance(nk, int):
1595 nk = (nk,) * len(axes)
1596 error_handling.nk(nk, len(axes))
1597 spin_op = None
1598 if spin_axis is not None:
1599 error_handling.spinful(self.spin)
1600 error_handling.spin_axis(spin_axis)
1601 spin_op = np.kron(np.eye(self.n_sites), PAULI[spin_axis] / 2.)
1602 # Directions (Cartesian unit vectors) of the velocities, the pairs
1603 # (u, w) whose curvature Omega_uw = Omega.(u x w) is integrated, and
1604 # the prefactor turning the mesh average into the conductivity.
1605 if full:
1606 directions = list(np.eye(3))
1607 pairs = [(1, 2), (2, 0), (0, 1)]
1608 volume = abs(np.linalg.det(np.array(self.lat.prim_vec, dtype='f8')))
1609 prefactor = 2 * PI / volume
1610 elif self.dim == 3:
1611 i, j = plane
1612 a_l = np.array(self.lat.prim_vec[3 - i - j], dtype='f8')
1613 b_i, b_j = (np.array(self.rec_vec[p], dtype='f8') for p in plane)
1614 u = b_i / np.linalg.norm(b_i)
1615 directions = [u, np.cross(a_l / np.linalg.norm(a_l), u)]
1616 pairs = [(0, 1)]
1617 prefactor = np.linalg.norm(np.cross(b_i, b_j)) / (2 * PI)
1618 else:
1619 directions = [self.k_basis[:, 0], self.k_basis[:, 1]]
1620 pairs = [(0, 1)]
1621 det = np.linalg.det(self.rec_vec_k)
1622 prefactor = self._plane_orientation((0, 1)) * np.sign(det) * abs(det) / (2 * PI)
1623 e_arr = np.atleast_1d(np.asarray(e_fermi, dtype='f8')).ravel()
1624 grids = np.meshgrid(*[np.arange(n) / n for n in nk], indexing='ij')
1625 fracs = np.zeros((grids[0].size, self.dim))
1626 for ax, g in zip(axes, grids):
1627 fracs[:, ax] = g.ravel()
1628 for ax in range(self.dim):
1629 if ax not in axes:
1630 fracs[:, ax] = k_fixed
1631 args = (e_arr, temperature, directions, pairs, positions, spin_op, response)
1632 coarse, size = self._kubo(fracs @ self.rec_vec_k, *args)
1633 total = coarse.sum(axis=0)
1634 if refine > 1:
1635 # Wang, Yates, Souza and Vanderbilt (2006): resample the cells
1636 # where the curvature peaks on a refine^d submesh (midpoints of
1637 # the sub-cells), and replace their coarse value by the average.
1638 # The cells are ranked by the size of the curvature whatever the
1639 # occupations, so that cells straddling the Fermi surface are
1640 # refined together with their neighbours.
1641 n_hot = int(np.ceil(refine_fraction * len(fracs)))
1642 hot = np.argsort(size)[::-1][:n_hot]
1643 sub = np.array(np.meshgrid(*[(np.arange(refine) + 0.5) / refine - 0.5] * len(axes),
1644 indexing='ij')).reshape(len(axes), -1).T
1645 offsets = np.zeros((len(sub), self.dim))
1646 for c, (ax, n) in enumerate(zip(axes, nk)):
1647 offsets[:, ax] = sub[:, c] / n
1648 fine = (fracs[hot][:, None, :] + offsets[None, :, :]).reshape(-1, self.dim)
1649 fine_val = self._kubo(fine @ self.rec_vec_k, *args)[0].reshape(n_hot, len(sub), len(e_arr), len(pairs))
1650 total = total + (fine_val.mean(axis=1) - coarse[hot]).sum(axis=0)
1651 sigma = prefactor * total / len(fracs)
1652 if not full:
1653 sigma = sigma[:, 0]
1654 if np.ndim(e_fermi) == 0:
1655 return sigma[0] if full else float(sigma[0])
1656 return sigma.reshape(np.shape(e_fermi) + sigma.shape[1:])
1658 def hall_conductivity(
1659 self, e_fermi: float | ArrayLike, temperature: float = 0., nk: int | tuple[int, ...] = 60,
1660 plane: tuple[int, int] = (0, 1), k_fixed: float | None = None, positions: bool = True,
1661 refine: int = 1, refine_fraction: float = 0.05,
1662 ) -> float | NDArray[np.float64]:
1663 r'''
1664 Get the intrinsic anomalous Hall conductivity at any Fermi level --
1665 in a gap, in a band, or at a band crossing -- from the Kubo formula
1666 over a uniform Brillouin-zone mesh,
1668 .. math::
1670 \sigma_{xy} = \frac{e^2}{\hbar}\int_{BZ}\frac{d^dk}{(2\pi)^d}\,
1671 F(\mathbf{k})\, ,\qquad
1672 F = -\sum_{n\neq m}(f_n - f_m)\,
1673 \frac{\mathrm{Im}\left[\langle n|\partial_x H|m\rangle\langle m|\partial_y H|n\rangle\right]}
1674 {(E_n - E_m)^2} = \sum_n f_n\,\Omega_n\, ,
1676 with :math:`f_n = f(E_n)` the Fermi-Dirac occupations and
1678 .. math::
1680 \Omega_n = -2\,\mathrm{Im}\sum_{m\neq n}
1681 \frac{\langle n|\partial_x H|m\rangle\langle m|\partial_y H|n\rangle}{(E_n-E_m)^2}
1682 = -2\,\mathrm{Im}\langle\partial_x u_n|\partial_y u_n\rangle
1684 the Berry curvature of band *n* (:math:`\partial_\mu H = \partial H/\partial k_\mu`,
1685 the convention :math:`\Omega = \partial_xA_y - \partial_yA_x`,
1686 :math:`\mathbf{A} = i\langle u|\nabla_{\mathbf{k}}u\rangle` of
1687 *berry_curvature*). The form with :math:`f_n - f_m` stays finite
1688 where bands touch: degenerate pairs have equal occupations and
1689 drop out, instead of cancelling between two diverging
1690 :math:`\Omega_n`. :math:`\partial H/\partial\mathbf{k}` is built
1691 analytically from the stored hoppings, :math:`\sum_{\mathbf{R}}
1692 i\mathbf{d}\,t\,e^{i\mathbf{k}\cdot\mathbf{d}}` with the Cartesian bond
1693 vector :math:`\mathbf{d}`.
1695 **Sign.** In a gap, :math:`\sigma_{xy} = C\,e^2/h` with :math:`C`
1696 the value *chern_number* returns for the occupied bands: this is the
1697 sign of TKNN (Phys. Rev. Lett. 49, 405 (1982)), whose
1698 :math:`\sigma_H = (e^2/h)\,\frac{i}{2\pi}\int d^2k\,(\langle\partial_1u|\partial_2u\rangle
1699 - \langle\partial_2u|\partial_1u\rangle)` has the same integrand,
1700 :math:`\Omega/2\pi`. The adiabatic (semiclassical) response of a
1701 charge :math:`q` of either sign, :math:`\dot{\mathbf{r}} = \partial_{\mathbf{k}}E
1702 - \dot{\mathbf{k}}\times\boldsymbol\Omega` with
1703 :math:`\hbar\dot{\mathbf{k}} = q\mathbf{E}`, gives the opposite sign
1704 for the tensor of Ohm's law :math:`j_x = \sigma^{\mathrm{Ohm}}_{xy}E_y`:
1705 :math:`\sigma^{\mathrm{Ohm}}_{xy} = -(q^2/\hbar)\int F\,d^dk/(2\pi)^d`,
1706 the convention of Wang, Yates, Souza and Vanderbilt (Phys. Rev. B
1707 74, 195118 (2006)) and of the Kubo-Bastin formula (*tbkit.kpm.hall_conductivity*
1708 returns, likewise, minus it). So the value returned is
1709 :math:`\sigma^{\mathrm{Ohm}}_{yx} = -\sigma^{\mathrm{Ohm}}_{xy}`; e.g. a
1710 massive Dirac cone :math:`v(k_x\sigma_x + k_y\sigma_y) + m\sigma_z`
1711 gives :math:`+\frac{e^2}{2h}\frac{m}{|E_F|}` outside its gap (the
1712 literature's :math:`\sigma_{xy} = -\frac{e^2}{2h}\frac{m}{|E_F|}`), and
1713 :math:`\frac{e^2}{2h}\mathrm{sgn}(m)` inside.
1715 **Orbital positions.** The velocity is :math:`\partial H/\partial\mathbf{k}`
1716 in the gauge of *positions*: with ``positions=True`` (the default)
1717 the bond vector is :math:`\mathbf{d} = \mathbf{R} + \boldsymbol\tau_j
1718 - \boldsymbol\tau_i`, the matrix of the physical velocity
1719 :math:`i[H, \mathbf{r}]` of a tight-binding model whose position
1720 operator is diagonal on its orbitals (the one *kpm.hall_conductivity*
1721 uses on a torus). With ``positions=False``, every orbital sits on
1722 its cell origin (the periodic gauge of *get_ham*). The two differ by
1723 :math:`i(E_n-E_m)\langle n|\boldsymbol\tau|m\rangle` in the
1724 velocity's matrix elements, so the band curvatures differ by
1725 :math:`\nabla\times\langle n|\boldsymbol\tau|n\rangle`, a total
1726 derivative: the conductivities agree whenever the bands below
1727 :math:`E_F` are all full (in a gap, at any temperature well below
1728 the gap) and differ in general at partial filling, by the circulation
1729 :math:`\frac{1}{2\pi}\oint_{FS}\langle n|\boldsymbol\tau|n\rangle\cdot d\mathbf{k}`
1730 around the Fermi surface. The default is the physical one. A model
1731 read from a Wannier90 ``_tb.dat`` file (*tbkit.io.read_wannier90_tb*)
1732 knows the other matrix elements of the position operator too, and
1733 ``positions=True`` then uses the whole operator: the velocity is
1734 :math:`i[H, \mathbf{r}]` with all of them, and each band's curvature
1735 gains that of the Wannier functions' own Berry connection (Wang,
1736 Yates, Souza and Vanderbilt, Phys. Rev. B 74, 195118 (2006)). The
1737 anomalous Nernst and thermal Hall conductivities do the same;
1738 *spin_hall_conductivity*, *orbital_magnetization* and *axion_angle*
1739 refuse such a model with ``positions=True``.
1741 **Units and dimensions.** In 2D, :math:`\sigma` is in units of
1742 :math:`e^2/h` (:math:`\frac{1}{2\pi}\int d^2k\,F`). In 3D, with
1743 *k_fixed* given, the value of the plane (the conductance of that
1744 slice of the Brillouin zone, in :math:`e^2/h`, oriented like
1745 *chern_number* along :math:`\mathbf{a}_l`); with ``k_fixed=None``,
1746 the full 3D conductivity as the Hall (pseudo)vector
1747 :math:`(\sigma_{yz}, \sigma_{zx}, \sigma_{xy}) = \frac{1}{(2\pi)^2}\int d^3k\,\mathbf{F}`
1748 in units of :math:`e^2/(h\cdot\mathrm{length})` (length the unit of
1749 *prim_vec*): :math:`\frac{1}{2\pi}\sum_l\bar C_l\,\mathbf{b}_l`, e.g.
1750 :math:`C/c` along :math:`z` for a stack of Chern layers :math:`c` apart.
1752 **Convergence.** The integrand peaks where bands nearly touch close
1753 to :math:`E_F` (hot spots), and jumps across the Fermi surface. A
1754 *temperature* smooths the latter. *refine* resamples the fraction
1755 *refine_fraction* of mesh cells with the largest :math:`|F|` on a
1756 finer submesh (*refine* points per direction), in the spirit of the
1757 adaptive mesh refinement of Wang, Yates, Souza and Vanderbilt
1758 (2006); the cells are ranked by the size of the curvature whatever
1759 the occupations. It is meant for metals: in a gap the plain uniform
1760 mesh already converges exponentially, and refining part of it
1761 costs a little accuracy (about :math:`4\cdot10^{-4}` for the
1762 Haldane model on a 60 x 60 mesh). With an overlap (*set_overlap*), :math:`H` is first
1763 Lowdin-orthogonalized, :math:`S^{-1/2}HS^{-1/2}`, as by the topology
1764 tools (exact derivatives of :math:`S^{-1/2}` included).
1766 Parameters
1767 ----------
1768 e_fermi : Real number, or array of real numbers
1769 Fermi energies
1770 (all of them are computed from one diagonalization of the mesh).
1771 temperature : Positive real or zero, default 0
1772 In
1773 energy units (:math:`k_B = 1`).
1774 nk
1775 Positive integer, or tuple (two integers for a plane,
1776 three for the full 3D conductivity). Default value 60. k-mesh.
1777 plane : Tuple of two integers
1778 Default value (0, 1). 3D only:
1779 the reciprocal vectors spanning the plane (see *berry_curvature*).
1780 k_fixed : Real number or None, default None
1781 3D only:
1782 the fractional coordinate of the plane along the remaining
1783 reciprocal vector; None for the full 3D conductivity. Ignored in 2D.
1784 positions : Boolean, default True
1785 Include the orbital
1786 positions in the bond vectors (see above).
1787 refine : Positive integer
1788 Default value 1 (no refinement).
1789 Submesh points per direction in the refined cells.
1790 refine_fraction : Real in (0, 1], default 0.05
1791 Fraction
1792 of the mesh cells that are refined.
1794 Returns
1795 -------
1796 sigma
1797 Real number (or ndarray shaped like *e_fermi*); in
1798 3D with ``k_fixed=None``, ndarray of shape (3,) (or
1799 ``e_fermi.shape + (3,)``).
1801 Examples
1802 --------
1803 Example usage::
1805 e_f = np.linspace(-3., 3., 301)
1806 sigma = hal.hall_conductivity(e_f, nk=120) # plateau at C in the gap
1807 '''
1808 return self._hall(e_fermi, temperature, nk, plane, k_fixed, positions, refine,
1809 refine_fraction, None)
1811 def spin_hall_conductivity(
1812 self, e_fermi: float | ArrayLike, temperature: float = 0., nk: int | tuple[int, int] = 60,
1813 plane: tuple[int, int] = (0, 1), k_fixed: float | None = None, positions: bool = True,
1814 spin_axis: str = 'z', refine: int = 1, refine_fraction: float = 0.05,
1815 ) -> float | NDArray[np.float64]:
1816 r'''
1817 Get the intrinsic spin Hall conductivity of a spinful model
1818 (``spin=True``): the Kubo formula of *hall_conductivity* with the
1819 charge current along :math:`x` replaced by the spin current
1820 (Sinova et al., Phys. Rev. Lett. 92, 126603 (2004))
1822 .. math::
1824 j^{s}_x = \tfrac12\{s, v_x\}\, ,\qquad s = \tfrac{\hbar}{2}\sigma_{a}\, ,
1826 i.e. :math:`\sigma^{s}_{xy} = \frac{e}{2\pi}\cdot\frac{1}{2\pi}\int d^2k\,F^s`,
1827 :math:`F^s = -\sum_{n\neq m}(f_n-f_m)\,\mathrm{Im}[\langle n|j^s_x|m\rangle\langle m|\partial_yH|n\rangle]/(E_n-E_m)^2`
1828 (:math:`j^s_x` with :math:`s = \sigma_a/2`, in units of :math:`\hbar`).
1829 The unit is :math:`e/2\pi`: one :math:`e/\hbar` from the electric
1830 field, one :math:`\hbar/2` from the spin, and :math:`1/2\pi` from the
1831 Brillouin-zone integral, as for :math:`e^2/h = (e^2/\hbar)/2\pi`.
1832 When :math:`s_z` is conserved, the two spins decouple and
1833 :math:`j^s_x = \pm\frac{\hbar}{2}v_x` in each, so in a gap
1834 :math:`\sigma^s_{xy} = \frac{e}{2\pi}\cdot\frac{C_\uparrow - C_\downarrow}{2}`,
1835 :math:`C_\sigma` the Chern number of each spin sector (the sign of
1836 *hall_conductivity* and *chern_number*): :math:`\pm e/2\pi` for the
1837 Kane-Mele quantum spin Hall insulator (Kane and Mele 2005). Rashba
1838 coupling breaks the conservation of :math:`s_z`, and the value is
1839 then no longer quantized (the :math:`\mathbb{Z}_2` invariant, see
1840 *z2_invariant*, still is).
1842 Parameters
1843 ----------
1844 e_fermi
1845 See *hall_conductivity*.
1846 temperature
1847 See *hall_conductivity*.
1848 nk : Positive integer, or tuple of 2 integers, default 60
1849 plane
1850 See *hall_conductivity*.
1851 k_fixed : Real number or None, default None
1852 3D only: the
1853 plane (required in 3D, where only planes are computed).
1854 positions : Boolean, default True
1855 See *hall_conductivity*.
1856 spin_axis : 'x', 'y' or 'z', default 'z'
1857 Spin component
1858 :math:`a` carried by the current.
1859 refine
1860 See *hall_conductivity*.
1861 refine_fraction
1862 See *hall_conductivity*.
1864 Returns
1865 -------
1866 sigma_s
1867 Real number (or ndarray shaped like *e_fermi*), in
1868 units of :math:`e/2\pi`.
1869 '''
1870 return self._hall(e_fermi, temperature, nk, plane, k_fixed, positions, refine,
1871 refine_fraction, spin_axis)
1873 # ------------------------------------------------------------------
1874 # Berry-phase response beyond the Hall conductivity
1875 # ------------------------------------------------------------------
1877 def orbital_magnetization(
1878 self, e_fermi: float | ArrayLike, temperature: float = 0., nk: int | tuple[int, ...] = 60,
1879 plane: tuple[int, int] = (0, 1), k_fixed: float | None = None, positions: bool = True,
1880 refine: int = 1, refine_fraction: float = 0.05,
1881 ) -> float | NDArray[np.float64]:
1882 r'''
1883 Get the orbital magnetization in the modern theory (Thonhauser,
1884 Ceresoli, Vanderbilt and Resta, Phys. Rev. Lett. 95, 137205 (2005);
1885 Xiao, Shi and Niu, Phys. Rev. Lett. 95, 137204 (2005); Ceresoli et
1886 al., Phys. Rev. B 74, 024408 (2006)), at any Fermi level and
1887 temperature:
1889 .. math::
1891 M = \frac{e}{h}\,\frac{1}{2\pi}\int_{BZ} d^2k\sum_n\left[f_n\,m_n
1892 + g_n\,\Omega_n\right],\qquad
1893 m_n = \mathrm{Im}\langle\partial_xu_n|(H-E_n)|\partial_yu_n\rangle\, ,
1895 with :math:`g = k_BT\ln(1+e^{-(E-\mu)/k_BT})` (:math:`\mu - E` below
1896 :math:`\mu` and 0 above, at :math:`T = 0`). The first term is the
1897 self-rotation of the wavepackets, the second the circulation of
1898 the Berry-curvature currents at the edges. At :math:`T = 0` both
1899 combine into :math:`\sum_nf_n\,\mathrm{Im}\langle\partial_xu_n|(H+E_n-2\mu)|\partial_yu_n\rangle`,
1900 the formula of Thonhauser et al. It is evaluated, like
1901 *hall_conductivity*, from :math:`\langle n|\partial H|m\rangle`
1902 (no derivatives of the eigenstates), so it is finite where bands
1903 touch.
1905 **Sign and units.** The sign is that of *hall_conductivity*, so
1906 that the Streda formula reads :math:`\partial M/\partial\mu = \sigma`:
1907 in a gap (:math:`T = 0`), :math:`M` is linear in :math:`\mu` with
1908 slope the Chern number :math:`C`. In 2D, :math:`M` (a magnetic
1909 moment per area, i.e. a current) is in units of :math:`e/h` times
1910 the energy unit; with ``k_fixed=None`` in 3D, the vector
1911 :math:`(M_x, M_y, M_z)` per length. *positions* matters as for
1912 *hall_conductivity*, and the physical choice is the default.
1914 Parameters
1915 ----------
1916 e_fermi
1917 See *hall_conductivity*.
1918 temperature
1919 See *hall_conductivity*.
1920 nk
1921 See *hall_conductivity*.
1922 plane
1923 See *hall_conductivity*.
1924 k_fixed
1925 See *hall_conductivity*.
1926 positions
1927 See *hall_conductivity*.
1928 refine
1929 See *hall_conductivity*.
1930 refine_fraction
1931 See *hall_conductivity*.
1933 Returns
1934 -------
1935 M
1936 Real number (or ndarray shaped like *e_fermi*); in 3D
1937 with ``k_fixed=None``, ndarray of shape (3,) (or ``e_fermi.shape + (3,)``).
1939 Examples
1940 --------
1941 Example usage::
1943 mu = np.linspace(-0.5, 0.5, 11) # in the gap of a Chern insulator
1944 M = hal.orbital_magnetization(mu) # slope C = hall_conductivity(mu)
1945 '''
1946 return self._hall(e_fermi, temperature, nk, plane, k_fixed, positions, refine,
1947 refine_fraction, None, 'magnetization')
1949 def anomalous_nernst_conductivity(
1950 self, e_fermi: float | ArrayLike, temperature: float, nk: int | tuple[int, ...] = 60,
1951 plane: tuple[int, int] = (0, 1), k_fixed: float | None = None, positions: bool = True,
1952 refine: int = 1, refine_fraction: float = 0.05,
1953 ) -> float | NDArray[np.float64]:
1954 r'''
1955 Get the intrinsic anomalous Nernst (transverse thermoelectric)
1956 conductivity :math:`\alpha_{xy}`, :math:`j_x = \alpha_{xy}(-\partial_yT)`,
1957 from the Berry curvature weighted by the entropy of each state
1958 (Xiao, Yao, Fang and Niu, Phys. Rev. Lett. 97, 026603 (2006)):
1960 .. math::
1962 \alpha_{xy} = \frac{ek_B}{h}\,\frac{1}{2\pi}\int_{BZ}d^2k\sum_n s_n\,\Omega_n\, ,
1963 \qquad s = -f\ln f - (1-f)\ln(1-f)\, .
1965 Only the states within a few :math:`k_BT` of :math:`\mu` carry
1966 entropy, so it vanishes in a gap at low temperature. It obeys the
1967 Mott relation exactly,
1968 :math:`\alpha_{xy}(\mu, T) = \frac{1}{eT}\int dE\,(E-\mu)\left(-\frac{\partial f}{\partial E}\right)\sigma_{xy}(E)`,
1969 with :math:`\sigma_{xy}(E)` the :math:`T = 0` *hall_conductivity*
1970 at Fermi energy :math:`E`, which fixes the sign. The pair form of
1971 *hall_conductivity* keeps it finite where bands touch.
1973 **Units.** :math:`ek_B/h` in 2D (:math:`k_B = 1`, temperatures in
1974 energy units), per length for the 3D vector (``k_fixed=None``).
1976 Parameters
1977 ----------
1978 e_fermi
1979 See *hall_conductivity*.
1980 temperature : Positive real number
1981 In energy units (:math:`k_B = 1`).
1982 nk
1983 See *hall_conductivity*.
1984 plane
1985 See *hall_conductivity*.
1986 k_fixed
1987 See *hall_conductivity*.
1988 positions
1989 See *hall_conductivity*.
1990 refine
1991 See *hall_conductivity*.
1992 refine_fraction
1993 See *hall_conductivity*.
1995 Returns
1996 -------
1997 alpha : Real number (or ndarray, as *hall_conductivity*)
1999 Examples
2000 --------
2001 Example usage::
2003 alpha = hal.anomalous_nernst_conductivity(np.linspace(-3, 3, 301), 0.05)
2004 '''
2005 return self._hall(e_fermi, temperature, nk, plane, k_fixed, positions, refine,
2006 refine_fraction, None, 'nernst')
2008 def thermal_hall_conductivity(
2009 self, e_fermi: float | ArrayLike, temperature: float, nk: int | tuple[int, ...] = 60,
2010 plane: tuple[int, int] = (0, 1), k_fixed: float | None = None, positions: bool = True,
2011 refine: int = 1, refine_fraction: float = 0.05,
2012 ) -> float | NDArray[np.float64]:
2013 r'''
2014 Get the intrinsic thermal Hall conductivity of the electrons
2015 :math:`\kappa_{xy}`, :math:`j^Q_x = \kappa_{xy}(-\partial_yT)`
2016 (Qin, Niu and Shi, Phys. Rev. Lett. 107, 236601 (2011)):
2018 .. math::
2020 \kappa_{xy} = \frac{k_B^2T}{h}\,\frac{1}{2\pi}\int_{BZ}d^2k
2021 \sum_n c_2(x_n)\,\Omega_n\, ,\qquad
2022 c_2(x) = \int_x^\infty y^2\left(-\frac{\partial f}{\partial y}\right)dy\, ,
2024 :math:`x_n = (E_n-\mu)/k_BT` (:math:`c_2 = \pi^2/3` deep below
2025 :math:`\mu`, 0 far above). Equivalently, exactly,
2026 :math:`\kappa_{xy}(\mu, T) = \frac{1}{e^2T}\int dE\,(E-\mu)^2\left(-\frac{\partial f}{\partial E}\right)\sigma_{xy}(E)`
2027 with the :math:`T = 0` *hall_conductivity*. In a gap at low
2028 temperature it is the Wiedemann-Franz value
2029 :math:`\kappa_{xy} = \frac{\pi^2k_B^2}{3e^2}T\sigma_{xy}`: for a Chern
2030 insulator the quantized :math:`C\,\pi^2k_B^2T/3h`.
2032 **Units.** :math:`k_B^2/h` times the temperature (in energy units,
2033 :math:`k_B = 1`) in 2D, so that :math:`\kappa/T = \pi^2C/3` on a
2034 Chern plateau; per length for the 3D vector (``k_fixed=None``).
2035 The sign is that of *hall_conductivity*.
2037 Parameters
2038 ----------
2039 e_fermi
2040 See *hall_conductivity*.
2041 temperature : Positive real number
2042 In energy units (:math:`k_B = 1`).
2043 nk
2044 See *hall_conductivity*.
2045 plane
2046 See *hall_conductivity*.
2047 k_fixed
2048 See *hall_conductivity*.
2049 positions
2050 See *hall_conductivity*.
2051 refine
2052 See *hall_conductivity*.
2053 refine_fraction
2054 See *hall_conductivity*.
2056 Returns
2057 -------
2058 kappa : Real number (or ndarray, as *hall_conductivity*)
2060 Examples
2061 --------
2062 Example usage::
2064 kappa = hal.thermal_hall_conductivity(0., 0.01) # = pi^2/3 C T in the gap
2065 '''
2066 return self._hall(e_fermi, temperature, nk, plane, k_fixed, positions, refine,
2067 refine_fraction, None, 'thermal')
2069 def _axion_rate(
2070 self, ks: NDArray[np.float64], bands: list[int], params: dict, param: str,
2071 positions: bool,
2072 ) -> float:
2073 r'''
2074 Private method. The mesh average, over *ks*, of
2075 :math:`\mathrm{tr}[F_{\lambda x}F_{yz} + F_{\lambda y}F_{zx} + F_{\lambda z}F_{xy}]`
2076 for the bands *bands* at the parameters *params*, the derivative
2077 along *param* by central differences. The non-Abelian curvature is
2078 :math:`F_{\mu\nu} = i(X_\mu^\dagger X_\nu - X_\nu^\dagger X_\mu)`,
2079 :math:`(X_\mu)_{lm} = \langle l|\partial_\mu H|m\rangle/(E_m-E_l)`
2080 (:math:`m` in *bands*, :math:`l` not), i.e.
2081 :math:`Q|\partial_\mu u_m\rangle` in the eigenbasis: gauge covariant.
2082 '''
2083 value = params[param]
2084 step = 1e-5 * max(1., abs(value))
2085 others = [b for b in range(self.norb) if b not in bands]
2086 total, gap = 0., np.inf
2087 chunk = max(1, 400000 // self.norb ** 2)
2088 for c0 in range(0, len(ks), chunk):
2089 k = ks[c0:c0 + chunk]
2090 ham, dham = self._bloch_derivatives(k, list(np.eye(3)), positions, params)
2091 plus = self._bloch_derivatives(k, [], positions, dict(params, **{param: value + step}))[0]
2092 minus = self._bloch_derivatives(k, [], positions, dict(params, **{param: value - step}))[0]
2093 en, vec = np.linalg.eigh(ham)
2094 occ, emp = vec[:, :, bands], vec[:, :, others]
2095 de = en[:, others][:, :, None] - en[:, bands][:, None, :]
2096 gap = min(gap, np.abs(de).min())
2097 emp_h = emp.conj().transpose(0, 2, 1)
2098 x = [-(emp_h @ d @ occ) / de for d in [(plus - minus) / (2 * step), *dham]]
2099 f = {}
2100 for a, b in ((0, 1), (0, 2), (0, 3), (1, 2), (2, 3), (3, 1)):
2101 xa_h = x[a].conj().transpose(0, 2, 1)
2102 xb_h = x[b].conj().transpose(0, 2, 1)
2103 f[a, b] = 1j * (xa_h @ x[b] - xb_h @ x[a])
2104 trace = (np.einsum('kab,kba->k', f[0, 1], f[2, 3]) + np.einsum('kab,kba->k', f[0, 2], f[3, 1])
2105 + np.einsum('kab,kba->k', f[0, 3], f[1, 2]))
2106 total += trace.real.sum()
2107 error_handling.path_gap(gap, param, value)
2108 return total / len(ks)
2110 def axion_angle(
2111 self, bands: list[int], param: str, values: ArrayLike, nk: int | tuple[int, int, int] = 16,
2112 theta0: float = 0., positions: bool = True,
2113 ) -> NDArray[np.float64]:
2114 r'''
2115 Get the axion angle :math:`\theta` of a 3D insulator along a path of
2116 a parameter of its value functions (*set_hopping*), from the second
2117 Chern form (Qi, Hughes and Zhang, Phys. Rev. B 78, 195424 (2008);
2118 Essin, Moore and Vanderbilt, Phys. Rev. Lett. 102, 146805 (2009)):
2120 .. math::
2122 \frac{d\theta}{d\lambda} = \frac{1}{2\pi}\int_{BZ}d^3k\;
2123 \mathrm{tr}\left[F_{\lambda x}F_{yz} + F_{\lambda y}F_{zx} + F_{\lambda z}F_{xy}\right],
2125 :math:`F_{\mu\nu}` the non-Abelian Berry curvature of the bands
2126 *bands* in :math:`(\lambda, k_x, k_y, k_z)` space, so that
2127 :math:`\theta(\lambda) = \theta_0 + \int_{\lambda_0}^{\lambda}\frac{d\theta}{d\lambda'}d\lambda'`.
2128 This is the variation of the Chern-Simons axion coupling, computed
2129 from gauge-invariant quantities only (no smooth gauge is needed),
2130 and :math:`\theta_0` is its value at ``values[0]``: e.g. 0
2131 for a path starting from an atomic insulator. A closed path (a
2132 pumping cycle) changes :math:`\theta` by :math:`2\pi C_2`, with
2133 :math:`C_2` the second Chern number of the 4D family. At a point
2134 with time-reversal or inversion symmetry, :math:`\theta` is 0 or
2135 :math:`\pi` (mod :math:`2\pi`): :math:`\pi` for a strong topological
2136 insulator, cf. *z2_indices_3d*. The sign of :math:`\theta` follows
2137 the orientation :math:`(\lambda, k_x, k_y, k_z)` above.
2139 The path must stay gapped: the bands *bands* must be separated
2140 from the others at every k-point and every value (a ValueError
2141 names the value where they touch). The integrand is smooth, so the
2142 uniform k-mesh converges exponentially; the :math:`\lambda`
2143 integral is a trapezoid over *values* (error :math:`O(\Delta\lambda^2)`).
2144 :math:`\partial H/\partial\lambda` is a central difference, and
2145 :math:`\partial H/\partial\mathbf{k}` is exact (see
2146 *hall_conductivity*, whose *positions* convention applies).
2148 Parameters
2149 ----------
2150 bands : List of integers
2151 The occupied bands (e.g. the lower
2152 half of the spectrum).
2153 param : String
2154 Name of the parameter of the value functions
2155 that the path varies (see *set_params*; the other parameters keep
2156 their values in *params*).
2157 values : 1D array of at least two real numbers, increasing or decreasing
2158 The parameter values along the path.
2159 nk : Positive integer, or tuple of 3 positive integers, default 16
2160 k-mesh.
2161 theta0 : Real number, default 0
2162 :math:`\theta` at ``values[0]``.
2163 positions : Boolean, default True
2164 See *hall_conductivity*.
2166 Returns
2167 -------
2168 theta
2169 ndarray, shape ``(len(values),)``: :math:`\theta`
2170 at each value, not reduced modulo :math:`2\pi`.
2172 Examples
2173 --------
2174 Example usage::
2176 phi = np.linspace(0., 2 * np.pi, 41)
2177 theta = ks.axion_angle([0, 1], 'phi', phi) # theta[-1] = 2 pi C2
2178 '''
2179 self._check_static()
2180 error_handling.dim_exact(self.dim, 3)
2181 error_handling.hermitian_model(self.is_hermitian())
2182 error_handling.band_indices(bands, self.norb)
2183 error_handling.path_parameter(param)
2184 error_handling.path_values(values)
2185 if isinstance(nk, int):
2186 nk = (nk,) * 3
2187 error_handling.nk(nk, 3)
2188 error_handling.real_number(theta0, 'theta0')
2189 error_handling.boolean(positions, 'positions')
2190 error_handling.no_position_elements(positions and bool(self._position_hop), 'axion_angle')
2191 values = np.asarray(values, dtype='f8')
2192 fracs = np.array(np.meshgrid(*[np.arange(n) / n for n in nk], indexing='ij')).reshape(3, -1).T
2193 ks = fracs @ self.rec_vec_k
2194 volume = abs(np.linalg.det(self.rec_vec_k))
2195 rates = [self._axion_rate(ks, bands, dict(self.params, **{param: float(v)}), param, positions)
2196 for v in values]
2197 return theta0 + cumulative_trapezoid(np.array(rates) * volume / (2 * PI), values, initial=0.)
2199 # ------------------------------------------------------------------
2200 # Finite samples and non-Hermitian band theory
2201 # ------------------------------------------------------------------
2203 def _hop_cells(self) -> list[tuple[int, int, tuple[int, ...], complex]]:
2204 r'''
2205 Private method. The stored hoppings with their lattice vector as
2206 integers :math:`(n_1, ...)` (from :math:`\mathbf{R}\cdot\mathbf{b}_i/2\pi`).
2207 '''
2208 rec = np.array(self.rec_vec, dtype='f8')
2209 return [(i, j, tuple(int(n) for n in np.rint(rec @ R / (2 * PI))), t)
2210 for i, j, R, t in self._hop]
2212 def _finite_entries(
2213 self, n_cells: int | tuple[int, ...], periodic: bool, twist: NDArray | None = None,
2214 ) -> tuple[tuple[int, ...], int, list[tuple[NDArray, NDArray, int, int, tuple, NDArray, complex]]]:
2215 r'''
2216 Private method. For each stored hopping, the row and column indices
2217 it fills in a finite sample of *n_cells* cells (see *finite_ham*),
2218 with its orbitals, lattice vector (integers and Cartesian) and amplitude.
2219 With *twist* (periodic only), the amplitude is an array: the hopping
2220 times the phase :math:`e^{i\theta\cdot w}` of the *w* windings
2221 of each bond around the torus.
2222 '''
2223 if isinstance(n_cells, int):
2224 n_cells = (n_cells,) * self.dim
2225 n_tot = int(np.prod(n_cells))
2226 cells = np.array(np.meshgrid(*[np.arange(n) for n in n_cells], indexing='ij'))
2227 cells = cells.reshape(self.dim, -1).T # (n_tot, dim)
2228 strides = np.cumprod((1,) + tuple(n_cells[:-1]))
2229 index = cells @ strides
2230 order = np.argsort(index)
2231 cells = cells[order]
2232 dims = np.array(n_cells)
2233 entries = []
2234 for (i, j, R, t), (_, _, R_cart, _) in zip(self._hop_cells(), self._hop):
2235 target = cells + np.array(R)[None, :]
2236 if periodic:
2237 target = target % dims
2238 keep = np.ones(n_tot, bool)
2239 else:
2240 keep = np.all((target >= 0) & (target < dims), axis=1)
2241 rows = np.arange(n_tot)[keep] * self.norb + i
2242 cols = (target[keep] @ strides) * self.norb + j
2243 if twist is not None:
2244 t = t * np.exp(1j * (((cells + np.array(R)[None, :]) // dims) @ twist))
2245 entries.append((rows, cols, i, j, R, R_cart, t))
2246 return n_cells, n_tot, entries
2248 def finite_ham(
2249 self, n_cells: int | tuple[int, ...], periodic: bool = False, sparse: bool = False,
2250 twist: ArrayLike | None = None,
2251 ) -> NDArray[np.complex128] | sp.csr_matrix:
2252 r'''
2253 Get the real-space Hamiltonian of a finite sample of
2254 :math:`N_1\times N_2\times\dots` unit cells of the model -- open
2255 boundaries (a flake, a finite chain), or periodic ones (a torus).
2256 Orbital *o* of cell :math:`(n_1, n_2, n_3)` is row
2257 :math:`((n_3 N_2 + n_2) N_1 + n_1)\,\mathrm{norb} + o`.
2259 Parameters
2260 ----------
2261 n_cells : Positive integer, or tuple of *dim* positive integers
2262 periodic : Boolean, default False
2263 Periodic boundary
2264 conditions (the spectrum is then that of *get_bands* on the
2265 :math:`N_1\times N_2\times\dots` k-mesh), else open ones.
2266 sparse : Boolean, default False
2267 Return a sparse CSR
2268 matrix (for large samples, e.g. with *tbkit.kpm*) instead of a
2269 dense array.
2270 twist : Real array of *dim* angles, or None, default None
2271 Twisted boundary conditions (periodic only),
2272 :math:`\psi(\mathbf{n} + N_\alpha\mathbf{e}_\alpha) = e^{i\theta_\alpha}\psi(\mathbf{n})`:
2273 every bond that winds around the torus along
2274 :math:`\mathbf{a}_\alpha` picks up the phase
2275 :math:`e^{i\theta_\alpha}`, a flux :math:`\theta_\alpha/2\pi`
2276 threaded through that cycle. The spectrum is that of
2277 *get_bands* on the mesh shifted by :math:`\theta_\alpha/N_\alpha`
2278 along :math:`\mathbf{b}_\alpha`.
2280 Returns
2281 -------
2282 ham
2283 Complex ndarray (or CSR matrix), shape (N*norb, N*norb), N the number of cells.
2284 '''
2285 error_handling.nk(n_cells, self.dim)
2286 error_handling.boolean(periodic, 'periodic')
2287 error_handling.boolean(sparse, 'sparse')
2288 if twist is not None:
2289 twist = np.asarray(twist, dtype='f8')
2290 error_handling.twist(twist, self.dim, periodic)
2291 _, n_tot, entries = self._finite_entries(n_cells, periodic, twist)
2292 onsite = np.diag(self.onsite) + self._onsite_offdiag
2293 if sparse:
2294 onsite_rows, onsite_cols = np.nonzero(onsite)
2295 rows = [c * self.norb + onsite_rows for c in range(n_tot)]
2296 cols = [c * self.norb + onsite_cols for c in range(n_tot)]
2297 vals = [onsite[onsite_rows, onsite_cols]] * n_tot
2298 for r, c, _, _, _, _, t in entries:
2299 rows.append(r)
2300 cols.append(c)
2301 vals.append(np.full(len(r), t, dtype='c16'))
2302 n = n_tot * self.norb
2303 return sp.coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))),
2304 shape=(n, n)).tocsr()
2305 ham = np.zeros((n_tot * self.norb, n_tot * self.norb), 'c16')
2306 for cell in range(n_tot):
2307 ham[cell*self.norb:(cell+1)*self.norb, cell*self.norb:(cell+1)*self.norb] += onsite
2308 for r, c, _, _, _, _, t in entries:
2309 np.add.at(ham, (r, c), t)
2310 return ham
2312 def finite_velocity(
2313 self, n_cells: int | tuple[int, ...], periodic: bool = False, sparse: bool = False,
2314 ) -> list[NDArray[np.complex128] | sp.csr_matrix]:
2315 r'''
2316 Get the velocity operators :math:`\mathbf{v} = i[H, \mathbf{r}]`
2317 (:math:`\hbar = 1`) of the finite sample of *finite_ham*, from the
2318 Cartesian bond vectors of the hoppings rather than from the site
2319 coordinates:
2321 .. math::
2323 (v_\alpha)_{ab} = i\,H_{ab}\,d_\alpha\, ,\qquad
2324 \mathbf{d} = \mathbf{R} + \boldsymbol\tau_j - \boldsymbol\tau_i\, ,
2326 so that they are well defined on a torus (``periodic=True``), where
2327 the position operator is not: a bond that wraps around the sample
2328 keeps its short displacement. They are the real-space counterpart of
2329 :math:`\partial H/\partial\mathbf{k}` with ``positions=True``
2330 (*hall_conductivity*), and the input of *tbkit.kpm.hall_conductivity*.
2332 Parameters
2333 ----------
2334 n_cells
2335 See *finite_ham*.
2336 periodic : Boolean, default False
2337 See *finite_ham*.
2338 sparse : Boolean, default False
2339 See *finite_ham*.
2341 Returns
2342 -------
2343 vel
2344 List of *space_dim* complex ndarrays (or CSR
2345 matrices), shape (N*norb, N*norb): :math:`v_x, v_y, (v_z)`.
2346 '''
2347 error_handling.nk(n_cells, self.dim)
2348 error_handling.boolean(periodic, 'periodic')
2349 error_handling.boolean(sparse, 'sparse')
2350 return [self._finite_derivative(n_cells, periodic, sparse, (alpha,)) for alpha in range(self.space_dim)]
2352 def finite_derivatives(
2353 self, n_cells: int | tuple[int, ...], component: str, periodic: bool = False,
2354 sparse: bool = False,
2355 ) -> dict[str, NDArray[np.complex128] | sp.csr_matrix]:
2356 r'''
2357 Get the derivatives of the Hamiltonian of the finite sample of
2358 *finite_ham* with respect to a uniform vector potential, the
2359 vertices of the nonlinear optical response in the velocity gauge
2360 (*tbkit.kpm.nonlinear_optical_conductivity*). With the Peierls
2361 phases :math:`H_{ab}(\mathbf{A}) = H_{ab}\,e^{i\mathbf{A}\cdot\mathbf{d}}`
2362 (:math:`\mathbf{d}` the bond vector of *finite_velocity*, a charge
2363 :math:`-e`, :math:`\hbar = e = 1`),
2365 .. math::
2367 h^{\alpha_1\dots\alpha_n}_{ab} =
2368 \frac{\partial^n H_{ab}}{\partial A_{\alpha_1}\cdots\partial A_{\alpha_n}}
2369 = i^n\,d_{\alpha_1}\cdots d_{\alpha_n}\,H_{ab}\, ,
2371 the real-space counterparts of :math:`\partial^nH/\partial k_{\alpha_1}\cdots`
2372 with ``positions=True``. :math:`h^\alpha` is the velocity
2373 :math:`v_\alpha` of *finite_velocity*.
2375 Parameters
2376 ----------
2377 n_cells
2378 See *finite_ham*.
2379 component : String
2380 Cartesian axes, e.g. 'xyy' for :math:`\sigma^{xyy}`.
2381 periodic : Boolean, default False
2382 See *finite_ham*.
2383 sparse : Boolean, default False
2384 See *finite_ham*.
2386 Returns
2387 -------
2388 derivatives
2389 Dict from axes (letters in alphabetical order, e.g. 'y', 'xy',
2390 'xyy') to complex ndarrays (or CSR matrices): one entry per
2391 nonempty subset of the letters of *component*.
2392 '''
2393 error_handling.nk(n_cells, self.dim)
2394 error_handling.cartesian_axes(component, self.space_dim)
2395 error_handling.boolean(periodic, 'periodic')
2396 error_handling.boolean(sparse, 'sparse')
2397 keys = {''.join(sorted(component[i] for i in subset))
2398 for size in range(1, len(component) + 1) for subset in combinations(range(len(component)), size)}
2399 return {key: self._finite_derivative(n_cells, periodic, sparse, tuple('xyz'.index(c) for c in key))
2400 for key in sorted(keys, key=lambda s: (len(s), s))}
2402 def _finite_derivative(
2403 self, n_cells: int | tuple[int, ...], periodic: bool, sparse: bool, axes: tuple[int, ...],
2404 ) -> NDArray[np.complex128] | sp.csr_matrix:
2405 r'''
2406 Private method. :math:`i^n d_{\alpha_1}\cdots d_{\alpha_n}H` on the
2407 finite sample (see *finite_derivatives*), one term per stored
2408 hopping, so that bonds that wrap onto the same pair of a small
2409 torus keep their own displacements.
2410 '''
2411 _, n_tot, entries = self._finite_entries(n_cells, periodic)
2412 tau = self.orbital_positions()
2413 n = n_tot * self.norb
2414 rows, cols, vals = [np.zeros(0, int)], [np.zeros(0, int)], [np.zeros(0, 'c16')]
2415 for r, c, i, j, _, R_cart, t in entries:
2416 factor = 1j ** len(axes) * t
2417 for alpha in axes:
2418 factor *= R_cart[alpha] + tau[j, alpha] - tau[i, alpha]
2419 rows.append(r)
2420 cols.append(c)
2421 vals.append(np.full(len(r), factor, dtype='c16'))
2422 mat = sp.coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))),
2423 shape=(n, n)).tocsr()
2424 return mat if sparse else mat.toarray()
2426 def get_ham_beta(self, beta: complex) -> NDArray[np.complex128]:
2427 r'''
2428 Get the non-Bloch Hamiltonian of a 1D model,
2429 :math:`H(\beta) = \sum_{n} t(n)\, \beta^{n}`: the Bloch Hamiltonian
2430 continued off the unit circle, :math:`\beta = e^{ik}` with complex
2431 :math:`k`. On the generalized Brillouin zone (see *gbz*), its
2432 spectrum is the open-chain spectrum of a non-Hermitian chain.
2434 Parameters
2435 ----------
2436 beta : Complex number, nonzero
2438 Returns
2439 -------
2440 ham : Complex ndarray, shape (norb, norb)
2441 '''
2442 error_handling.dim_exact(self.dim, 1)
2443 error_handling.nonzero_number(beta, 'beta')
2444 ham = np.diag(self.onsite).astype('c16') + self._onsite_offdiag
2445 for i, j, (n,), t in self._hop_cells():
2446 ham[i, j] += t * complex(beta) ** n
2447 return ham
2449 def spectral_winding(self, e_ref: complex = 0., nk: int = 400) -> float:
2450 r'''
2451 Get the spectral winding number of a 1D (non-Hermitian) model about
2452 the reference energy :math:`E_r`,
2454 .. math::
2456 W(E_r) = \frac{1}{2\pi i}\oint_0^{2\pi} dk\,
2457 \partial_k \ln\det\left[H(k) - E_r\right]\, ,
2459 the number of times the periodic-chain spectrum winds around
2460 :math:`E_r` in the complex plane. :math:`W \neq 0` for some
2461 :math:`E_r` is the criterion for the non-Hermitian skin effect: the
2462 open-chain eigenstates then pile up at one end (Okuma, Kawabata,
2463 Shiozaki and Sato, Phys. Rev. Lett. 124, 086801 (2020)).
2465 Parameters
2466 ----------
2467 e_ref : Complex number, default 0
2468 Reference energy.
2469 nk : Positive integer, default 400
2470 k-points.
2472 Returns
2473 -------
2474 W
2475 Real number, close to an integer (it is ill defined if
2476 :math:`E_r` lies on the periodic spectrum).
2477 '''
2478 error_handling.dim_exact(self.dim, 1)
2479 error_handling.number(e_ref, 'e_ref')
2480 error_handling.positive_int(nk, 'nk')
2481 ks = np.arange(nk + 1) / nk * self.rec_vec_k[0, 0]
2482 dets = np.array([np.linalg.det(self.get_ham([k]) - e_ref * np.eye(self.norb)) for k in ks])
2483 steps = np.angle(dets[1:] / dets[:-1])
2484 return float(np.sum(steps) / (2 * PI))
2486 def gbz(self, energies: ArrayLike) -> NDArray[np.complex128]:
2487 r'''
2488 Get the generalized Brillouin zone of a 1D non-Hermitian model
2489 (Yao and Wang, Phys. Rev. Lett. 121, 086803 (2018); Yokomizo and
2490 Murakami, Phys. Rev. Lett. 123, 066404 (2019)): for each energy
2491 :math:`E`, the roots of :math:`\det[H(\beta)-E] = 0` sorted by modulus,
2492 :math:`|\beta_1|\le\dots\le|\beta_{p+s}|` (:math:`p` the order of its
2493 pole at :math:`\beta = 0`), and the middle pair
2494 :math:`\beta_p, \beta_{p+1}`. The open-chain spectrum, in the limit of
2495 a long chain, is where :math:`|\beta_p| = |\beta_{p+1}|`; those
2496 :math:`\beta` trace the generalized Brillouin zone, on which the
2497 non-Bloch bands :math:`H(\beta)` (see *get_ham_beta*) replace the
2498 Bloch ones. For a Hermitian model it is the unit circle.
2500 Parameters
2501 ----------
2502 energies
2503 Complex array of energies (e.g. open-chain eigenvalues
2504 from *finite_ham*).
2506 Returns
2507 -------
2508 beta : Complex ndarray, shape (len(energies), 2): :math:`\beta_p, \beta_{p+1}`
2509 '''
2510 error_handling.dim_exact(self.dim, 1)
2511 energies = np.atleast_1d(np.asarray(energies, dtype='c16'))
2512 error_handling.ndarray_empty(energies, 'energies')
2513 powers = [n for _, _, (n,), _ in self._hop_cells()] + [0]
2514 low, high = self.norb * min(powers), self.norb * max(powers)
2515 n_samples = 2 * (high - low) + 8
2516 theta = 2 * PI * np.arange(n_samples) / n_samples
2517 hams = np.array([self.get_ham_beta(np.exp(1j * th)) for th in theta])
2518 out = np.zeros((len(energies), 2), 'c16')
2519 exps = np.arange(low, high + 1)
2520 for n, e in enumerate(energies):
2521 dets = np.linalg.det(hams - e * np.eye(self.norb)[None])
2522 # Laurent coefficients c_m of det[H(beta) - E] = sum_m c_m beta^m
2523 coef = np.array([np.mean(dets * np.exp(-1j * m * theta)) for m in exps])
2524 nonzero = np.abs(coef) > 1e-12 * np.max(np.abs(coef))
2525 first, last = np.argmax(nonzero), len(coef) - 1 - np.argmax(nonzero[::-1])
2526 p = -exps[first]
2527 roots = np.roots(coef[first:last + 1][::-1])
2528 roots = roots[np.argsort(np.abs(roots))]
2529 error_handling.gbz_roots(len(roots), p)
2530 out[n] = roots[p - 1], roots[p]
2531 return out
2533 # ------------------------------------------------------------------
2534 # Berry phases, Wannier centres, Z2, symmetries, quantum geometry
2535 # ------------------------------------------------------------------
2537 def orbital_positions(self) -> NDArray[np.float64]:
2538 r'''
2539 Get the positions :math:`\boldsymbol\tau` of the orbitals within the
2540 unit cell (each site twice, for its two spin components, if
2541 ``spin=True``).
2543 Returns
2544 -------
2545 tau : Real ndarray, shape (norb, space_dim)
2546 '''
2547 tau = np.array([dic['r0'] for dic in self.lat.unit_cell], dtype='f8')
2548 return np.repeat(tau, 2, axis=0) if self.spin else tau
2550 def _loop(
2551 self, bands: list[int], nk: int, direction: int, fracs_perp: dict[int, float],
2552 positions: bool,
2553 ) -> NDArray[np.complex128]:
2554 '''
2555 Private method. Wilson loop matrix of *bands* along the closed path
2556 k0 -> k0 + b_direction (nk steps), at fixed fractional coordinates
2557 *fracs_perp* along the other reciprocal vectors.
2558 '''
2559 frac = np.zeros(self.dim)
2560 for d, f in fracs_perp.items():
2561 frac[d] = f
2562 b = self.rec_vec_k[direction]
2563 k0 = frac @ self.rec_vec_k
2564 # each link carries exp(-i dk.tau): the Bloch sums then include the
2565 # orbital positions, so that the phases locate the Wannier centres
2566 # in space rather than on the cell origin.
2567 dk_space = self.k_basis @ (b / nk)
2568 phase = np.exp(-1j * self.orbital_positions() @ dk_space) if positions \
2569 else np.ones(self.norb)
2570 vs = self._subspaces(k0 + np.arange(nk)[:, None] * b[None] / nk, bands)
2571 links = vs.conj().transpose(0, 2, 1) @ (phase[:, None] * np.roll(vs, -1, axis=0))
2572 # keep only the unitary part of each link (its singular values
2573 # tend to 1 as nk grows): the product then stays unitary
2574 u, _, vh = np.linalg.svd(links)
2575 wilson = np.eye(len(bands), dtype='c16')
2576 for unitary in u @ vh:
2577 wilson = wilson @ unitary
2578 return wilson
2580 def _perp(self, direction: int, k_perp: float | tuple | None) -> dict[int, float]:
2581 '''
2582 Private method. Fractional coordinates of a loop along the other
2583 reciprocal vectors, from *k_perp* (a number in 2D, a pair in 3D).
2584 '''
2585 others = [d for d in range(self.dim) if d != direction]
2586 if k_perp is None:
2587 k_perp = (0.,) * len(others)
2588 if not isinstance(k_perp, tuple):
2589 k_perp = (k_perp,)
2590 error_handling.k_perp(k_perp, len(others))
2591 return dict(zip(others, k_perp))
2593 def berry_phase(
2594 self, bands: int | list[int], nk: int = 100, direction: int = 0,
2595 k_perp: float | tuple[float, float] | None = None, positions: bool = True,
2596 ) -> float:
2597 r'''
2598 Get the Berry phase of a group of bands along a closed loop across the
2599 Brillouin zone, :math:`\mathbf{k}\to\mathbf{k}+\mathbf{b}_{direction}`,
2601 .. math::
2603 \gamma = \oint \mathbf{A}\cdot d\mathbf{k} = -\arg\det W\, ,\qquad
2604 W = \prod_{m} \langle u(\mathbf{k}_m)|u(\mathbf{k}_{m+1})\rangle\, ,
2606 with :math:`\mathbf{A} = i\langle u|\nabla_{\mathbf{k}}u\rangle` (the
2607 convention of *berry_curvature*). In 1D it is the Zak phase: its
2608 value :math:`\gamma/2\pi`, modulo 1, is the centre of the band's
2609 Wannier functions in units of :math:`\mathbf{a}_{direction}` (the
2610 polarization).
2612 Parameters
2613 ----------
2614 bands : Band index, or list of band indices
2615 nk : Positive integer, default 100
2616 Number of k-points on the loop.
2617 direction : Integer, default 0
2618 Reciprocal vector the loop follows.
2619 k_perp : Real number (2D) or pair of real numbers (3D)
2620 Default
2621 value None (zero). Fractional coordinates of the loop along the
2622 other reciprocal vectors.
2623 positions : Boolean, default True
2624 Include the orbital
2625 positions in the Bloch functions (the physical choice: the phase
2626 then locates the Wannier centres in the crystal). If False, all
2627 orbitals are placed on the cell origin (the periodic gauge of
2628 *get_ham*); the two differ by :math:`\sum_n\mathbf{b}\cdot\boldsymbol\tau`
2629 weighted by the orbital content, and agree on quantized
2630 differences between phases.
2632 Returns
2633 -------
2634 gamma : Real number in :math:`(-\pi, \pi]`
2635 '''
2636 bands = self._check_loop(bands, nk, direction, positions)
2637 wilson = self._loop(bands, nk, direction, self._perp(direction, k_perp), positions)
2638 return float(-np.angle(np.linalg.det(wilson)))
2640 def wannier_centers(
2641 self, bands: int | list[int], nk: int = 100, direction: int = 0,
2642 k_perp: float | tuple[float, float] | None = None, positions: bool = True,
2643 ) -> NDArray[np.float64]:
2644 r'''
2645 Get the (hybrid) Wannier centres of a group of bands: minus the
2646 phases of the eigenvalues of the Wilson loop (see *berry_phase*),
2647 divided by :math:`2\pi`. They are the positions, in units of
2648 :math:`\mathbf{a}_{direction}` and modulo 1, of the maximally
2649 localized Wannier functions along that direction (hybrid: still
2650 Bloch waves along the others, at *k_perp*). Their sum is
2651 :math:`\gamma/2\pi`, modulo 1.
2653 Parameters
2654 ----------
2655 bands : Band index, or list of band indices
2656 nk : Positive integer, default 100
2657 Number of k-points on the loop.
2658 direction : Integer, default 0
2659 k_perp
2660 See *berry_phase*.
2661 positions : Boolean, default True
2662 See *berry_phase*.
2664 Returns
2665 -------
2666 centers : Real ndarray, sorted, in :math:`[0, 1)`
2667 '''
2668 bands = self._check_loop(bands, nk, direction, positions)
2669 wilson = self._loop(bands, nk, direction, self._perp(direction, k_perp), positions)
2670 return np.sort((-np.angle(np.linalg.eigvals(wilson)) / (2*PI)) % 1.)
2672 def wannier_flow(
2673 self, bands: int | list[int], nk: int = 100, nk_perp: int = 51, direction: int = 0,
2674 flow: int | None = None, k_fixed: float = 0., positions: bool = True,
2675 k_range: tuple[float, float] = (0., 1.),
2676 ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
2677 r'''
2678 Get the flow of the hybrid Wannier centres (see *wannier_centers*)
2679 along *direction*, as the loop is moved across the Brillouin zone
2680 along the reciprocal vector *flow*. In a Chern insulator the centres
2681 wind by :math:`C` cells over a full period; in a
2682 :math:`\mathbb{Z}_2` topological insulator, the Kramers pairs swap
2683 partners over half a period (see *z2_invariant*).
2685 Parameters
2686 ----------
2687 bands : Band index, or list of band indices
2688 nk : Positive integer, default 100
2689 k-points on each loop.
2690 nk_perp : Positive integer, default 51
2691 Number of loops.
2692 direction : Integer, default 0
2693 Direction of the loops.
2694 flow : Integer
2695 Default value None (the first other direction).
2696 Reciprocal vector along which the loops are moved.
2697 k_fixed : Real number, default 0
2698 3D only: fractional
2699 coordinate along the remaining reciprocal vector.
2700 positions : Boolean, default True
2701 See *berry_phase*.
2702 k_range : Pair of real numbers
2703 Default value (0, 1). Range of
2704 the fractional coordinate along *flow* (both ends included).
2706 Returns
2707 -------
2708 fracs : Real ndarray, shape (nk_perp,)
2709 Fractional coordinates along *flow*.
2710 centers : Real ndarray, shape (nk_perp, len(bands))
2711 Sorted centres, in [0, 1).
2712 '''
2713 bands = self._check_loop(bands, nk, direction, positions)
2714 error_handling.dim_min(self.dim, 2)
2715 error_handling.positive_int(nk_perp, 'nk_perp')
2716 others = [d for d in range(self.dim) if d != direction]
2717 if flow is None:
2718 flow = others[0]
2719 error_handling.flow(flow, direction, self.dim)
2720 error_handling.real_number(k_fixed, 'k_fixed')
2721 error_handling.lims(k_range)
2722 fracs = np.linspace(k_range[0], k_range[1], nk_perp)
2723 centers = np.zeros((nk_perp, len(bands)))
2724 for n, f in enumerate(fracs):
2725 perp = {d: (f if d == flow else k_fixed) for d in others}
2726 wilson = self._loop(bands, nk, direction, perp, positions)
2727 centers[n] = np.sort((-np.angle(np.linalg.eigvals(wilson)) / (2*PI)) % 1.)
2728 return fracs, centers
2730 def z2_invariant(
2731 self, bands: list[int], nk: int = 100, nk_perp: int = 51, direction: int = 0,
2732 flow: int | None = None, k_fixed: float = 0.,
2733 ) -> int:
2734 r'''
2735 Get the :math:`\mathbb{Z}_2` invariant of a time-reversal-symmetric
2736 group of bands (an even number, e.g. all occupied bands of the
2737 Kane-Mele model) from the flow of its hybrid Wannier centres over
2738 half the Brillouin zone (Soluyanov and Vanderbilt, Phys. Rev. B 83,
2739 235401 (2011); Yu, Qi, Bernevig, Fang and Dai, Phys. Rev. B 84,
2740 075119 (2011)): follow the midpoint of the largest gap between the
2741 centres, and count, modulo 2, how many centres it jumps over. It is
2742 odd when the Kramers partners exchange along the flow -- a
2743 topological insulator -- and even otherwise.
2745 Unlike the parity criterion (*parity_z2*), it needs no inversion
2746 symmetry, so it also works with Rashba coupling.
2748 Parameters
2749 ----------
2750 bands : List of band indices (an even number of bands)
2751 nk : Positive integer, default 100
2752 k-points on each loop.
2753 nk_perp : Positive integer, default 51
2754 Number of loops
2755 over the half zone (the flow must be resolved finely enough that
2756 no two centres cross between neighbouring loops unnoticed).
2757 direction : Integer, default 0
2758 See *wannier_flow*.
2759 flow : Integer, default None
2760 See *wannier_flow*.
2761 k_fixed : Real number, default 0
2762 3D only: a time-reversal
2763 invariant plane has *k_fixed* 0 or 0.5 (the weak and strong
2764 indices follow from the six such planes).
2766 Returns
2767 -------
2768 nu : 0 (trivial) or 1 (topological)
2769 '''
2770 error_handling.even_bands(bands)
2771 _, centers = self.wannier_flow(bands, nk, nk_perp, direction, flow, k_fixed,
2772 positions=False, k_range=(0., 0.5))
2773 gap = [self._largest_gap(c) for c in centers]
2774 jumps = sum(self._between(gap[n], gap[n + 1], centers[n + 1])
2775 for n in range(len(gap) - 1))
2776 return int(jumps % 2)
2778 def z2_indices_3d(
2779 self, bands: list[int], nk: int = 100, nk_perp: int = 51,
2780 ) -> tuple[int, int, int, int]:
2781 r'''
2782 Get the four :math:`\mathbb{Z}_2` indices
2783 :math:`(\nu_0;\nu_1\nu_2\nu_3)` of a 3D time-reversal-invariant
2784 insulator (Fu, Kane and Mele, Phys. Rev. Lett. 98, 106803 (2007);
2785 Moore and Balents, Phys. Rev. B 75, 121306(R) (2007)) from the
2786 :math:`\mathbb{Z}_2` invariants of its six time-reversal-invariant
2787 planes :math:`k_i = 0` and :math:`k_i = 1/2` (fractional coordinates
2788 along :math:`\mathbf{b}_i`), each computed by *z2_invariant*:
2790 .. math::
2792 \nu_0 = \nu(k_i = 0) + \nu(k_i = 1/2) \bmod 2\, ,\qquad
2793 \nu_i = \nu(k_i = 1/2)\, .
2795 The strong index :math:`\nu_0` comes out the same for the three
2796 :math:`i`, which is checked (a ValueError asks for a finer flow
2797 otherwise). :math:`\nu_0 = 1` is a strong topological insulator; a
2798 weak one has :math:`\nu_0 = 0` and some :math:`\nu_i = 1`, i.e.
2799 stacked quantum spin Hall layers normal to
2800 :math:`\nu_1\mathbf{b}_1 + \nu_2\mathbf{b}_2 + \nu_3\mathbf{b}_3`.
2801 No inversion symmetry is needed (compare *parity_z2*).
2803 Parameters
2804 ----------
2805 bands : List of band indices (an even number of bands)
2806 nk : Positive integer, default 100
2807 See *z2_invariant*.
2808 nk_perp : Positive integer, default 51
2809 See *z2_invariant*.
2811 Returns
2812 -------
2813 indices : Tuple of four integers, 0 or 1: :math:`(\nu_0, \nu_1, \nu_2, \nu_3)`
2814 '''
2815 error_handling.dim_exact(self.dim, 3)
2816 nu = np.zeros((3, 2), int)
2817 for i in range(3):
2818 direction, flow = [d for d in range(3) if d != i]
2819 for n, k_fixed in enumerate((0., 0.5)):
2820 nu[i, n] = self.z2_invariant(bands, nk, nk_perp, direction, flow, k_fixed)
2821 strong = nu.sum(axis=1) % 2
2822 error_handling.strong_index(strong)
2823 return int(strong[0]), int(nu[0, 1]), int(nu[1, 1]), int(nu[2, 1])
2825 def entanglement_spectrum(
2826 self, ks: ArrayLike, region: list[int], bands: int | list[int],
2827 ) -> NDArray[np.float64]:
2828 r'''
2829 Get the k-resolved entanglement spectrum of a group of bands
2830 (Peschel, J. Phys. A 36, L205 (2003); Li and Haldane, Phys. Rev. Lett.
2831 101, 010504 (2008); Fidkowski, Phys. Rev. Lett. 104, 130502 (2010)):
2832 the eigenvalues :math:`\xi_n(\mathbf{k})` of the correlation matrix
2833 :math:`P(\mathbf{k})` of the filled *bands*, restricted to the
2834 orbitals of *region*,
2836 .. math::
2838 C_A(\mathbf{k}) = \left[P(\mathbf{k})\right]_{A}\, ,\qquad
2839 P(\mathbf{k}) = \sum_{n\in\mathrm{bands}}|u_n(\mathbf{k})\rangle\langle u_n(\mathbf{k})|\, ,
2841 between 0 and 1. For a ribbon or a supercell
2842 (*tbkit.moire.supercell*) cut in two halves across its width, the
2843 states of the whole are either inside the region
2844 (:math:`\xi \approx 1`) or outside (:math:`\xi \approx 0`), except
2845 for those localized at the cuts: a topological phase leaves
2846 entanglement modes inside :math:`(0, 1)` -- a mode pinned at 1/2 in
2847 a chiral-symmetric chain, a branch that flows from 0 to 1 across
2848 the zone in a Chern insulator. The single-particle entanglement
2849 energies are :math:`\epsilon = \ln[(1-\xi)/\xi]`.
2851 Parameters
2852 ----------
2853 ks : ndarray, shape (nk, dim)
2854 k-points (see *get_bands*).
2855 region : List of orbital indices (the region :math:`A`)
2856 bands : Band index, or list of band indices (the filled bands)
2858 Returns
2859 -------
2860 xi : Real ndarray, shape (nk, len(region)), sorted ascending at every k
2861 '''
2862 ks = np.atleast_2d(np.asarray(ks, dtype='f8'))
2863 error_handling.ks(ks, self.dim)
2864 error_handling.region(region, self.norb)
2865 if isinstance(bands, int):
2866 bands = [bands]
2867 error_handling.band_indices(bands, self.norb)
2868 error_handling.hermitian_kspace(self.is_hermitian(), self._overlap_hop)
2869 v = self._subspaces(ks, bands)[:, region, :]
2870 return np.linalg.eigvalsh(v @ v.conj().transpose(0, 2, 1))
2872 @staticmethod
2873 def _largest_gap(centers: NDArray[np.float64]) -> float:
2874 '''
2875 Private method. Midpoint of the largest gap between sorted centres on the circle [0, 1).
2876 '''
2877 ext = np.append(centers, centers[0] + 1.)
2878 n = np.argmax(np.diff(ext))
2879 return float((ext[n] + ext[n + 1]) / 2 % 1.)
2881 @staticmethod
2882 def _between(a: float, b: float, centers: NDArray[np.float64]) -> int:
2883 '''
2884 Private method. Number of centres on the shorter arc between a and b.
2885 '''
2886 d = (b - a) % 1.
2887 start, length = (a, d) if d <= 0.5 else (b, 1. - d)
2888 return int(np.sum((centers - start) % 1. < length))
2890 def _check_loop(self, bands, nk, direction, positions) -> list[int]:
2891 '''
2892 Private method. Validate the arguments shared by the Wilson-loop methods.
2893 '''
2894 if isinstance(bands, int):
2895 bands = [bands]
2896 error_handling.band_indices(bands, self.norb)
2897 error_handling.positive_int(nk, 'nk')
2898 error_handling.direction(direction, self.dim)
2899 error_handling.boolean(positions, 'positions')
2900 return bands
2902 def _trims(self) -> list[NDArray[np.float64]]:
2903 '''
2904 Private method. Time-reversal-invariant momenta: fractional
2905 coordinates in {0, 1/2}^dim, as k points.
2906 '''
2907 grid = np.array(np.meshgrid(*[[0., 0.5]] * self.dim, indexing='ij')).reshape(self.dim, -1).T
2908 return [f @ self.rec_vec_k for f in grid]
2910 def _operator(self, op, k: NDArray[np.float64]) -> NDArray[np.complex128]:
2911 '''
2912 Private method. Matrix of a symmetry operator at k (op is a matrix, or a callable of k).
2913 '''
2914 mat = np.asarray(op(k) if callable(op) else op, dtype='c16')
2915 error_handling.operator(mat, self.norb)
2916 return mat
2918 def parity_z2(self, inversion, bands: list[int]) -> int:
2919 r'''
2920 Get the :math:`\mathbb{Z}_2` invariant of an inversion- and
2921 time-reversal-symmetric model from the parity eigenvalues of its
2922 occupied bands at the time-reversal-invariant momenta
2923 :math:`\Gamma_i` (Fu and Kane, Phys. Rev. B 76, 045302 (2007)):
2925 .. math::
2927 (-1)^\nu = \prod_i \delta_i\, ,\qquad
2928 \delta_i = \prod_{m=1}^{N} \xi_{2m}(\Gamma_i)\, ,
2930 one parity :math:`\xi = \pm1` per Kramers pair. In 3D, :math:`\nu`
2931 is the strong index.
2933 Parameters
2934 ----------
2935 inversion
2936 Complex ndarray, shape (norb, norb), or callable of
2937 k returning one: the inversion operator :math:`P`, with
2938 :math:`P H(\mathbf{k}) P^{-1} = H(-\mathbf{k})` (e.g. swapping the
2939 two sublattices of graphene, and the identity on spin).
2940 bands : List of band indices (the occupied Kramers pairs)
2942 Returns
2943 -------
2944 nu : 0 (trivial) or 1 (topological)
2945 '''
2946 error_handling.even_bands(bands)
2947 error_handling.band_indices(bands, self.norb)
2948 product = 1
2949 for k in self._trims():
2950 v = self._subspace(k, bands)
2951 xi = np.linalg.eigvals(v.conj().T @ self._operator(inversion, k) @ v)
2952 error_handling.parities(xi)
2953 n_minus = int(np.sum(xi.real < 0))
2954 product *= (-1) ** (n_minus // 2)
2955 return 0 if product == 1 else 1
2957 def symmetry_error(
2958 self, op, k_map: str = 'minus', antiunitary: bool = False, anti: bool = False,
2959 nk: int = 5, seed: int = 0, transpose: bool = False,
2960 ) -> float:
2961 r'''
2962 Check a symmetry of the Bloch Hamiltonian,
2964 .. math::
2966 H(g\mathbf{k}) = \pm\, U\, \mathcal{K}H(\mathbf{k})\mathcal{K}^{-1} U^\dagger\, ,
2968 with :math:`g\mathbf{k} = -\mathbf{k}` or :math:`\mathbf{k}`,
2969 :math:`\mathcal{K}` complex conjugation if *antiunitary*, and the
2970 minus sign if *anti*: time reversal is antiunitary with
2971 :math:`\mathbf{k}\to-\mathbf{k}` and the plus sign, particle-hole
2972 antiunitary with :math:`\mathbf{k}\to-\mathbf{k}` and the minus sign,
2973 chiral unitary with :math:`\mathbf{k}\to\mathbf{k}` and the minus sign,
2974 inversion unitary with :math:`\mathbf{k}\to-\mathbf{k}` and the plus
2975 sign. With *transpose*, :math:`H^T` replaces :math:`\mathcal{K}H\mathcal{K}^{-1} = H^*`
2976 (and :math:`H^\dagger` with *antiunitary* too): the symmetries
2977 of non-Hermitian Hamiltonians, where :math:`H^T \neq H^*` (see
2978 *non_hermitian_class*).
2980 *op* may also be a space-group operation
2981 (:class:`tbkit.symmetry.Operation`): then :math:`g\mathbf{k} =
2982 R\mathbf{k}` (:math:`-R\mathbf{k}` if antiunitary) and :math:`U =
2983 U_g(\mathbf{k})` (*symmetry.representation*), and *k_map* and
2984 *antiunitary* are those of the operation (the arguments are ignored).
2986 Parameters
2987 ----------
2988 op : Complex ndarray, shape (norb, norb), or callable of k: :math:`U`; or an **Operation**
2989 k_map : 'minus' or 'identity', default 'minus'
2990 antiunitary : Boolean, default False
2991 anti : Boolean, default False
2992 nk : Positive integer, default 5
2993 Points per direction of
2994 the (randomly shifted) test mesh.
2995 seed : Integer, default 0
2996 Seed of the random shift.
2997 transpose : Boolean, default False
2999 Returns
3000 -------
3001 error : Real number
3002 Largest deviation over the mesh (0 for a symmetry).
3003 '''
3004 error_handling.k_map(k_map)
3005 error_handling.boolean(antiunitary, 'antiunitary')
3006 error_handling.boolean(anti, 'anti')
3007 error_handling.positive_int(nk, 'nk')
3008 error_handling.boolean(transpose, 'transpose')
3009 rng = np.random.default_rng(seed)
3010 fracs = np.array(np.meshgrid(*[np.arange(nk) / nk] * self.dim, indexing='ij')).reshape(self.dim, -1).T
3011 fracs = fracs + rng.uniform(0., 1. / nk, self.dim)
3012 sign = -1. if anti else 1.
3013 from tbkit.symmetry import Operation, _representations
3014 if isinstance(op, Operation):
3015 k_all = fracs @ self.rec_vec_k
3016 u, gk = _representations(self, op, k_all)
3017 ham = self._bloch_ham(k_all @ self.k_basis.T)
3018 ham = ham.conj() if op.antiunitary else ham
3019 rhs = u @ (ham.transpose(0, 2, 1) if transpose else ham) @ u.conj().transpose(0, 2, 1)
3020 return float(np.max(np.abs(self._bloch_ham(gk @ self.k_basis.T) - sign * rhs)))
3021 err = 0.
3022 for f in fracs:
3023 k = f @ self.rec_vec_k
3024 gk = -k if k_map == 'minus' else k
3025 ham = self.get_ham(k)
3026 u = self._operator(op, k)
3027 ham = ham.conj() if antiunitary else ham
3028 rhs = u @ (ham.T if transpose else ham) @ u.conj().T
3029 err = max(err, float(np.max(np.abs(self.get_ham(gk) - sign * rhs))))
3030 return err
3032 def tenfold_class(
3033 self, time_reversal=None, particle_hole=None, chiral=None, nk: int = 5, tol: float = 1e-8,
3034 ) -> str:
3035 r'''
3036 Get the Altland-Zirnbauer symmetry class (the "tenfold way") of the
3037 model from its time-reversal :math:`T = U_T\mathcal{K}`, particle-hole
3038 :math:`C = U_C\mathcal{K}` and chiral :math:`S = U_S` symmetries. Each
3039 given operator is first checked (see *symmetry_error*) to be a
3040 symmetry; the class then follows from :math:`T^2 = U_TU_T^* = \pm1`,
3041 :math:`C^2 = \pm1`, and the presence of :math:`S`. Any two of the
3042 three imply the third (:math:`S = TC`), which need not be given.
3044 Parameters
3045 ----------
3046 time_reversal : Matrix :math:`U_T`, or None (absent)
3047 particle_hole : Matrix :math:`U_C`, or None (absent)
3048 chiral : Matrix :math:`U_S`, or None (absent)
3049 nk : Positive integer, default 5
3050 See *symmetry_error*.
3051 tol : Positive real, default 1e-8
3052 Tolerance of the checks.
3054 Returns
3055 -------
3056 name : String: 'A', 'AIII', 'AI', 'BDI', 'D', 'DIII', 'AII', 'CII', 'C' or 'CI'
3057 '''
3058 error_handling.positive_real(tol, 'tol')
3059 k0 = np.zeros(self.dim)
3060 for op, k_map, antiu, anti in ((time_reversal, 'minus', True, False),
3061 (particle_hole, 'minus', True, True),
3062 (chiral, 'identity', False, True)):
3063 if op is not None:
3064 error_handling.is_symmetry(self.symmetry_error(op, k_map, antiu, anti, nk), tol)
3065 u_t = None if time_reversal is None else self._operator(time_reversal, k0)
3066 u_c = None if particle_hole is None else self._operator(particle_hole, k0)
3067 # two of the three imply the third: C = S T, T = S C
3068 if chiral is not None and (u_t is None) != (u_c is None):
3069 u_s = self._operator(chiral, k0)
3070 if u_t is not None:
3071 u_c = u_s @ u_t
3072 elif u_c is not None:
3073 u_t = u_s @ u_c
3074 squares = []
3075 for u in (u_t, u_c):
3076 if u is None:
3077 squares.append(0)
3078 continue
3079 square = u @ u.conj()
3080 error_handling.square(square, tol)
3081 squares.append(int(np.sign(square[0, 0].real)))
3082 has_s = chiral is not None or (u_t is not None and u_c is not None)
3083 table = {(0, 0, False): 'A', (0, 0, True): 'AIII', (1, 0, False): 'AI',
3084 (1, 1, True): 'BDI', (0, 1, False): 'D', (-1, 1, True): 'DIII',
3085 (-1, 0, False): 'AII', (-1, -1, True): 'CII', (0, -1, False): 'C',
3086 (1, -1, True): 'CI'}
3087 return table[(squares[0], squares[1], has_s)]
3089 def non_hermitian_class(
3090 self, time_reversal=None, particle_hole=None, chiral=None, time_reversal_dagger=None,
3091 particle_hole_dagger=None, sublattice=None, pseudo_hermiticity=None, canonical: bool = False,
3092 nk: int = 5, tol: float = 1e-8,
3093 ) -> str:
3094 r'''
3095 Get the non-Hermitian symmetry class (the "38-fold way", Kawabata,
3096 Shiozaki, Ueda and Sato, Phys. Rev. X 9, 041015 (2019); Zhou and Lee,
3097 Phys. Rev. B 99, 235112 (2019)) of the model. A non-Hermitian
3098 Hamiltonian has :math:`H^* \neq H^T`, so each symmetry of the tenfold
3099 way (see *tenfold_class*) splits in two:
3101 .. math::
3103 \text{TRS: } U_T H^*(\mathbf{k}) U_T^\dagger = H(-\mathbf{k}),\qquad
3104 \text{TRS}^\dagger\text{: } U_{C_+} H^T(\mathbf{k}) U_{C_+}^\dagger = H(-\mathbf{k}),
3106 \text{PHS: } U_C H^T(\mathbf{k}) U_C^\dagger = -H(-\mathbf{k}),\qquad
3107 \text{PHS}^\dagger\text{: } U_{T_-} H^*(\mathbf{k}) U_{T_-}^\dagger = -H(-\mathbf{k}),
3109 \text{CS: } U_\Gamma H^\dagger(\mathbf{k}) U_\Gamma^\dagger = -H(\mathbf{k}),\qquad
3110 \text{SLS: } U_S H(\mathbf{k}) U_S^\dagger = -H(\mathbf{k}),\qquad
3111 \text{pH: } U_\eta H^\dagger(\mathbf{k}) U_\eta^\dagger = H(\mathbf{k}).
3113 Each given operator is first checked (see *symmetry_error*) to be a
3114 symmetry. The operators are then closed under products (two
3115 symmetries imply their product, which need not be given, as
3116 :math:`S = TC` in the tenfold way); a product of two operators of
3117 the same kind must agree with the given one up to a phase (no
3118 unitary symmetry left: block-diagonalize it first). The class
3119 follows from the kinds present, the squares :math:`UU^* = \pm1` of
3120 the four antiunitary kinds, and the commutation of
3121 :math:`S` (or :math:`\eta`) with them: :math:`U_SU = \epsilon\,UU_S^*`
3122 gives the subscript :math:`\epsilon` (for classes with TRS and PHS,
3123 the first refers to TRS, the second to PHS; in class AIII it is
3124 :math:`U_\Gamma U_S = \epsilon\,U_SU_\Gamma`).
3126 The name is that of the tables of Kawabata et al.: an AZ class
3127 ('AI', ...), an AZ\ :math:`^\dagger` class ('AI†', ...), an AZ class
3128 with SLS ('A + S', 'BDI + S-+', ...) when :math:`S` is present, or
3129 with pseudo-Hermiticity ('A + η', 'D + η+', ...) when :math:`\eta`
3130 is. These 54 names describe 38 classes: :math:`H \to iH` turns TRS
3131 into PHS\ :math:`^\dagger` and CS into pH, keeping the topology but
3132 exchanging real and imaginary line gaps, so that D† is AI, C† is AII,
3133 AII + S- is AI + S-, DIII + S-+ is BDI + S-+, A + η is AIII, and so
3134 on (their Tables XII and XIV). Since the tables differ for such
3135 partners, the name keeps the symmetries as given unless *canonical*.
3137 Parameters
3138 ----------
3139 time_reversal : Matrix :math:`U_T` (TRS), or None (absent)
3140 particle_hole : Matrix :math:`U_C` (PHS), or None (absent)
3141 chiral : Matrix :math:`U_\Gamma` (CS), or None (absent)
3142 time_reversal_dagger : Matrix :math:`U_{C_+}` (TRS†), or None (absent)
3143 particle_hole_dagger : Matrix :math:`U_{T_-}` (PHS†), or None (absent)
3144 sublattice : Matrix :math:`U_S` (SLS), or None (absent)
3145 pseudo_hermiticity : Matrix :math:`U_\eta` (pH), or None (absent)
3146 canonical : Boolean, default False
3147 Return the representative of
3148 the 38 classes instead (AZ names before AZ† ones, η classes as
3149 their equivalents without η).
3150 nk : Positive integer, default 5
3151 See *symmetry_error*.
3152 tol : Positive real, default 1e-8
3153 Tolerance of the checks.
3155 Returns
3156 -------
3157 name : String, for instance 'A', 'AI†', 'AIII + S-', 'BDI + S+-' or 'C + η+'
3159 Notes
3160 -----
3161 For a Hermitian model :math:`H^* = H^T` and :math:`H^\dagger = H`,
3162 so TRS is also TRS†, PHS also PHS†, CS also SLS, and :math:`\eta = 1`
3163 is a pseudo-Hermiticity: a Hermitian class BDI is 'BDI + S++' once
3164 all of them are given.
3165 '''
3166 error_handling.positive_real(tol, 'tol')
3167 error_handling.boolean(canonical, 'canonical')
3168 k0 = np.zeros(self.dim)
3169 given = {}
3170 ops = (time_reversal, particle_hole, chiral, time_reversal_dagger, particle_hole_dagger,
3171 sublattice, pseudo_hermiticity)
3172 for op, kind in zip(ops, _NH_KINDS):
3173 if op is not None:
3174 conj, transpose, minus = kind
3175 k_map = 'minus' if conj != transpose else 'identity'
3176 err = self.symmetry_error(op, k_map, bool(conj), bool(minus), nk, transpose=bool(transpose))
3177 error_handling.is_symmetry(err, tol)
3178 given[kind] = self._operator(op, k0)
3179 group = self._symmetry_group(given, tol)
3180 squares = {}
3181 for kind, u in group.items():
3182 if kind[0] != kind[1]:
3183 square = u @ u.conj()
3184 error_handling.square(square, tol)
3185 squares[kind] = int(np.sign(square[0, 0].real))
3186 t_p, c_m, c_p, t_m = (squares.get(kind, 0) for kind in ((1, 0, 0), (0, 1, 1), (0, 1, 0), (1, 0, 1)))
3187 az = {(1, 1): 'BDI', (-1, 1): 'DIII', (-1, -1): 'CII', (1, -1): 'CI', (1, 0): 'AI',
3188 (-1, 0): 'AII', (0, 1): 'D', (0, -1): 'C'}
3190 def sign(eps):
3191 return '+' if eps > 0 else '-'
3193 if (0, 0, 1) in group: # SLS
3194 if not squares:
3195 if (1, 1, 1) not in group:
3196 name = 'A + S'
3197 else:
3198 u_g, u_s = group[(1, 1, 1)], group[(0, 0, 1)]
3199 eps = np.trace((u_s @ u_g).conj().T @ u_g @ u_s).real
3200 name = 'AIII + S' + sign(eps)
3201 elif not (c_p or c_m):
3202 name = az[(t_p, 0)] + ' + S' + sign(t_p * t_m)
3203 elif not (t_p or t_m):
3204 name = az[(0, c_m)] + ' + S' + sign(c_p * c_m)
3205 else:
3206 name = az[(t_p, c_m)] + ' + S' + sign(t_p * t_m) + sign(c_p * c_m)
3207 elif (1, 1, 0) in group: # pseudo-Hermiticity
3208 if not squares:
3209 name = 'A + η'
3210 elif t_p:
3211 name = az[(t_p, 0)] + ' + η' + sign(t_p * c_p)
3212 else:
3213 name = az[(0, c_m)] + ' + η' + sign(t_m * c_m)
3214 elif t_p or c_m:
3215 name = az[(t_p, c_m)]
3216 elif c_p or t_m:
3217 name = az[(c_p, t_m)] + '†'
3218 else:
3219 name = 'AIII' if (1, 1, 1) in group else 'A'
3220 return _NH_CANONICAL.get(name, name) if canonical else name
3222 def _symmetry_group(self, given: dict, tol: float) -> dict:
3223 '''
3224 Private method. Close the symmetry operators *given* ({kind: matrix},
3225 kind = (conjugation, transposition, minus sign), see *_NH_KINDS*)
3226 under products, checking that two products of the same kind agree up
3227 to a phase. Unitary kinds come back normalized to :math:`U^2 = 1`.
3228 '''
3229 group = {(0, 0, 0): np.eye(self.norb, dtype='c16')}
3230 todo = list(given.items())
3231 while todo:
3232 kind, u = todo.pop()
3233 if kind in group:
3234 error_handling.symmetry_algebra(group[kind], u, tol)
3235 continue
3236 group[kind] = u
3237 for other, v in list(group.items()):
3238 product = tuple(a ^ b for a, b in zip(kind, other))
3239 # first one, then the other: U_2 f(U_1), f = conjugation for the antiunitary kinds
3240 todo.append((product, v @ (u.conj() if other[0] != other[1] else u)))
3241 todo.append((product, u @ (v.conj() if kind[0] != kind[1] else v)))
3242 for kind, u in group.items():
3243 if kind[0] == kind[1]:
3244 group[kind] = u / np.sqrt((u @ u)[0, 0])
3245 return group
3247 def quantum_geometric_tensor(
3248 self, bands: int | list[int], k: ArrayLike, dk: float = 1e-4, positions: bool = True,
3249 ) -> NDArray[np.complex128]:
3250 r'''
3251 Get the quantum geometric tensor of a group of bands at :math:`\mathbf{k}`,
3253 .. math::
3255 Q_{\mu\nu} = \mathrm{Tr}\left[P\,\partial_\mu P\,\partial_\nu P\right]
3256 = \sum_{n\in\mathrm{bands}}\langle\partial_\mu u_n|(1-P)|\partial_\nu u_n\rangle\, ,
3258 with :math:`P(\mathbf{k})` the projector on the bands (gauge
3259 invariant, so degeneracies within the group are harmless), from
3260 central differences. Many k-points are evaluated at once, with one
3261 batched diagonalization (see *set_workers*). Its real
3262 part is the quantum metric :math:`g_{\mu\nu}` (Provost and Vallee,
3263 1980), minus twice its imaginary part the Berry curvature
3264 :math:`\Omega_{\mu\nu} = -2\,\mathrm{Im}\,Q_{\mu\nu}` (the convention of
3265 *berry_curvature*, per unit k-area here). They obey
3266 :math:`\sqrt{\det g} \ge |\Omega_{xy}|/2` in 2D.
3268 Parameters
3269 ----------
3270 bands : Band index, or list of band indices
3271 k : k point (see *get_ham*), or real array of shape (nk, dim)
3272 One or many k-points.
3273 dk : Positive real, default 1e-4
3274 Finite-difference step.
3275 positions : Boolean, default True
3276 Include the orbital
3277 positions in the Bloch functions. The local metric and curvature
3278 depend on this choice (the Berry curvature of *berry_curvature* is
3279 that of ``positions=False``); integrals such as the Chern number
3280 do not.
3282 Returns
3283 -------
3284 Q : Complex ndarray, shape (dim, dim), in the k coordinates of *get_ham*
3285 Shape (nk, dim, dim) for many k-points.
3286 '''
3287 if isinstance(bands, int):
3288 bands = [bands]
3289 error_handling.band_indices(bands, self.norb)
3290 error_handling.k_points(k, 'k', self.dim)
3291 error_handling.positive_real(dk, 'dk')
3292 error_handling.boolean(positions, 'positions')
3293 k = np.asarray(k, dtype='f8')
3294 ks = np.atleast_2d(k)
3295 # k, then k + dk e_mu and k - dk e_mu for every mu
3296 shifts = np.concatenate([np.zeros((1, self.dim)), dk * np.eye(self.dim), -dk * np.eye(self.dim)])
3297 kk = (ks[:, None, :] + shifts[None]).reshape(-1, self.dim)
3298 v = self._subspaces(kk, bands)
3299 if positions:
3300 v = np.exp(-1j * (kk @ self.k_basis.T) @ self.orbital_positions().T)[:, :, None] * v
3301 proj = (v @ v.conj().transpose(0, 2, 1)).reshape(len(ks), 1 + 2 * self.dim, self.norb, self.norb)
3302 dp = (proj[:, 1:1 + self.dim] - proj[:, 1 + self.dim:]) / (2 * dk)
3303 q = np.einsum('kab,kmbc,knca->kmn', proj[:, 0], dp, dp)
3304 return q if k.ndim == 2 else q[0]
3306 def surface_spectral_function(
3307 self, ks: ArrayLike, energies: ArrayLike, direction: int, side: int = 1,
3308 eta: float = 1e-2, bulk: bool = False, max_iter: int = 10000,
3309 ) -> NDArray[np.float64]:
3310 r'''
3311 Get the spectral function of the surface of a semi-infinite crystal,
3313 .. math::
3315 A_s(\mathbf{k}_\parallel, E) = -\frac{1}{\pi}\,
3316 \mathrm{Im}\,\mathrm{Tr}\, G_{00}(\mathbf{k}_\parallel, E + i\eta)\, ,
3318 with :math:`G_{00}` the Green's function of the outermost unit cell:
3319 the crystal fills the cells :math:`n\,\mathbf{a}_d`,
3320 :math:`n = 0, 1, 2, \dots` along the primitive vector
3321 :math:`\mathbf{a}_d` (``lat.prim_vec[direction]``), times *side*, and
3322 is periodic along the others. It comes from the Lopez Sancho-Rubio
3323 decimation (see *transport.surface_green*) of the chain of principal
3324 layers (as many cells as the longest hopping along
3325 :math:`\mathbf{a}_d` spans), so the crystal is truly semi-infinite: no
3326 finite slab, and no states of the opposite surface. It is the
3327 tight-binding picture of an ARPES map -- surface states (edge states,
3328 in 2D; the end state of a 1D chain) show up as sharp lines inside the
3329 bulk gaps. With *bulk*, the same quantity for a unit cell deep inside
3330 the crystal: the bulk bands projected on the surface Brillouin zone.
3332 Parameters
3333 ----------
3334 ks : Real array, shape (nk, dim)
3335 k-points, in the coordinates
3336 of *get_ham* (e.g. from a *k_path* of the surface Brillouin zone).
3337 Only :math:`\mathbf{k}_\parallel` matters: the result does not
3338 depend on the component along the reciprocal vector
3339 :math:`\mathbf{b}_d`.
3340 energies : Real number or real array
3341 Energies :math:`E`.
3342 direction : Integer, between 0 and dim-1
3343 The primitive vector
3344 normal to the surface (the one along which the crystal is
3345 semi-infinite).
3346 side : +1 or -1, default 1
3347 The crystal extends along
3348 :math:`+\mathbf{a}_d` (the surface faces :math:`-\mathbf{a}_d`) or
3349 along :math:`-\mathbf{a}_d` (the opposite surface).
3350 eta : Positive real, default 1e-2
3351 Broadening: the
3352 width of the lines, and the decay length (about :math:`v/\eta`
3353 cells) over which the bulk is resolved.
3354 bulk : Boolean, default False
3355 If True, the spectral
3356 function of a bulk unit cell instead of the surface one.
3357 max_iter : Positive integer, default 10000
3358 Maximum
3359 number of decimation steps.
3361 Returns
3362 -------
3363 A : Real ndarray, shape (nk, len(energies))
3365 Examples
3366 --------
3367 Example usage::
3369 # the (001) surface of a 3D model, along a path of the surface zone
3370 A = ks.surface_spectral_function(k_path, np.linspace(-1, 1, 201), direction=2)
3371 '''
3372 error_handling.no_overlap(self._overlap_hop)
3373 ks = np.atleast_2d(np.asarray(ks, dtype='f8'))
3374 error_handling.ks(ks, self.dim)
3375 error_handling.frequencies(energies, 'energies')
3376 energies = np.atleast_1d(np.asarray(energies, dtype='f8'))
3377 error_handling.direction(direction, self.dim)
3378 error_handling.surface_side(side)
3379 error_handling.positive_real(eta, 'eta')
3380 error_handling.boolean(bulk, 'bulk')
3381 error_handling.positive_int(max_iter, 'max_iter')
3382 # H_m(k): the hoppings from a cell to the cell m a_d away, with the
3383 # phase of their in-plane part only (independent of k along b_d)
3384 a_dir = np.array(self.lat.prim_vec[direction], dtype='f8')
3385 layers: dict[int, list] = {}
3386 for (i, j, cell, t), (_, _, R, _) in zip(self._hop_cells(), self._hop):
3387 layers.setdefault(cell[direction], []).append((i, j, R - cell[direction] * a_dir, t))
3388 k_cart = ks @ self.k_basis.T
3389 blocks: dict[int, NDArray] = {m: self._bloch_sum(hops, k_cart)[0] for m, hops in layers.items()}
3390 blocks[0] = blocks.get(0, 0.) + (np.diag(self.onsite) + self._onsite_offdiag)[None]
3391 width = max([abs(m) for m in layers] + [1])
3392 norb, nk = self.norb, len(ks)
3394 def layer(shift):
3395 # block (p, q) couples cell p of a principal layer to cell q of
3396 # the layer *shift* cells further into the crystal
3397 out = np.zeros((nk, width, norb, width, norb), 'c16')
3398 for p in range(width):
3399 for q in range(width):
3400 m = side * (q - p + shift)
3401 if m in blocks:
3402 out[:, p, :, q, :] = blocks[m]
3403 return out.reshape(nk, width * norb, width * norb)
3404 h0, alpha, beta = layer(0), layer(width), layer(-width)
3405 # one task per k-point and chunk of energies, enough tasks for every thread
3406 n_e = max(1, min(len(energies), -(-self.workers // nk)))
3407 tasks = [(n, part) for n in range(nk) for part in np.array_split(np.arange(len(energies)), n_e)]
3409 def task(n_part):
3410 n, part = n_part
3411 gs, gb = _green_surface_bulk(energies[part] + 1j * eta, h0[n], alpha[n], beta[n], 1e-12,
3412 max_iter, 'surface_spectral_function')
3413 g = gb if bulk else gs
3414 return -np.trace(g[:, :norb, :norb], axis1=1, axis2=2).imag / PI
3415 if self.workers > 1 and len(tasks) > 1:
3416 with ThreadPoolExecutor(min(self.workers, len(tasks))) as pool:
3417 out = list(pool.map(task, tasks))
3418 else:
3419 out = [task(t) for t in tasks]
3420 spec = np.empty((nk, len(energies)))
3421 for (n, part), a in zip(tasks, out):
3422 spec[n, part] = a
3423 return spec
3425 # ------------------------------------------------------------------
3426 # Projections, constant-energy contours and plot helpers
3427 # ------------------------------------------------------------------
3429 def spin_operator(self, axis: str) -> NDArray[np.complex128]:
3430 r'''
3431 Get the Pauli matrix :math:`\sigma_{axis}` acting on the spin of
3432 every site, :math:`\mathbb{1}_{sites}\otimes\sigma_{axis}`, for a model
3433 built with ``spin=True`` (for *band_weights* and *spin_texture*).
3435 Parameters
3436 ----------
3437 axis : 'x', 'y' or 'z'
3439 Returns
3440 -------
3441 op : Complex ndarray, shape (norb, norb)
3442 '''
3443 error_handling.spinful(self.spin)
3444 error_handling.spin_axis(axis)
3445 return np.kron(np.eye(self.n_sites), PAULI[axis])
3447 def _projector(self, projector) -> NDArray[np.complex128]:
3448 '''
3449 Private method. The (norb, norb) operator of *band_weights* from an
3450 orbital index, a list of them, a sublattice tag or a matrix.
3451 '''
3452 error_handling.projector(projector, self.norb, self.tags)
3453 if isinstance(projector, np.ndarray):
3454 return projector.astype('c16')
3455 if isinstance(projector, str):
3456 sites = np.nonzero(self.tags == projector)[0]
3457 projector = np.concatenate([2 * sites, 2 * sites + 1]) if self.spin else sites
3458 diag = np.zeros(self.norb)
3459 diag[projector] = 1.
3460 return np.diag(diag).astype('c16')
3462 def _expectations(self, ks: NDArray[np.float64], ops: list) -> NDArray[np.float64]:
3463 r'''
3464 Private method. :math:`\mathrm{Re}\langle u_n(\mathbf{k})|O|u_n(\mathbf{k})\rangle
3465 /\langle u_n|u_n\rangle` for each operator of *ops*, band and k-point:
3466 shape (len(ops), nk, norb), from one diagonalization. Within a group
3467 of degenerate bands (energies within 1e-8 of each other, relative to
3468 the largest one), each band gets the average over the group: the
3469 trace of O over the degenerate subspace divided by its dimension,
3470 which does not depend on the eigenvectors the solver returns.
3471 '''
3472 en, vn = self._eigs(ks, eigenvec=True)
3473 norm = np.sum(np.abs(vn) ** 2, axis=1)
3474 values = np.array([np.einsum('kin,ij,kjn->kn', vn.conj(), op, vn).real / norm for op in ops])
3475 # label the degenerate groups (consecutive bands, sorted by energy)
3476 tol = 1e-8 * max(1., np.abs(en).max())
3477 new_group = np.concatenate([np.ones((len(en), 1), bool),
3478 np.abs(np.diff(en, axis=1)) > tol], axis=1)
3479 groups = np.cumsum(new_group.ravel()) - 1
3480 counts = np.bincount(groups)
3481 return np.array([(np.bincount(groups, v.ravel()) / counts)[groups].reshape(v.shape)
3482 for v in values])
3484 def band_weights(self, projector, ks: ArrayLike | None = None) -> NDArray[np.float64]:
3485 r'''
3486 Get the weight of each band on a set of orbitals, or the expectation
3487 value of an operator, for "fat band" plots (see *plot_bands*):
3489 .. math::
3491 w_n(\mathbf{k}) = \langle u_n(\mathbf{k})|P|u_n(\mathbf{k})\rangle\, ,
3493 with :math:`P` the projector on the chosen orbitals (a weight
3494 between 0 and 1; the weights on all the sublattices add up to 1), or
3495 any Hermitian operator, e.g. ``ks.spin_operator('z')`` for the spin
3496 polarization (between -1 and 1). Within a group of degenerate bands
3497 (e.g. Kramers pairs with inversion and time reversal), the weight of
3498 a single eigenvector depends on the choice of eigenvectors; each band
3499 of the group gets instead the average over the group, which does not
3500 (a Kramers pair has zero spin polarization).
3501 For a non-Hermitian model, the right eigenvectors are used; with an
3502 overlap (*set_overlap*), :math:`v^\dagger Pv/v^\dagger v`.
3504 Parameters
3505 ----------
3506 projector
3507 Orbital index, list of orbital indices, sublattice
3508 tag (all the orbitals, both spins, of the sites with that tag),
3509 or a (norb, norb) Hermitian matrix.
3510 ks : Real array, shape (nk, dim)
3511 Default value None: the
3512 k-points of the last *get_bands* or *k_path*.
3514 Returns
3515 -------
3516 weights : Real ndarray, shape (nk, norb), ordered as the bands
3518 Examples
3519 --------
3520 Example usage::
3522 ks.k_path(points, nk=100)
3523 ks.plot_bands(weights=ks.band_weights('a'))
3524 '''
3525 op = self._projector(projector)
3526 if ks is None:
3527 error_handling.empty_ndarray(self.en, 'get_bands or k_path')
3528 ks = self.ks
3529 ks = np.atleast_2d(np.asarray(ks, dtype='f8'))
3530 error_handling.ks(ks, self.dim)
3531 return self._expectations(ks, [op])[0]
3533 def spin_texture(self, ks: ArrayLike, band: int) -> NDArray[np.float64]:
3534 r'''
3535 Get the spin expectation values
3536 :math:`\langle\boldsymbol\sigma\rangle_n(\mathbf{k}) =
3537 \langle u_n|\boldsymbol\sigma|u_n\rangle` of a band, for a model built
3538 with ``spin=True``. Their length is 1 if the band is fully polarized,
3539 less if spin-orbit coupling entangles the spin with the orbitals.
3540 Within a group of degenerate bands, each band gets the average spin
3541 of the group (see *band_weights*): zero for a Kramers pair, with both
3542 inversion and time reversal.
3544 Parameters
3545 ----------
3546 ks : Real array, shape (nk, dim)
3547 k-points.
3548 band : Integer
3549 Band index.
3551 Returns
3552 -------
3553 spin
3554 Real ndarray, shape (nk, 3):
3555 :math:`(\langle\sigma_x\rangle, \langle\sigma_y\rangle, \langle\sigma_z\rangle)`.
3556 '''
3557 error_handling.spinful(self.spin)
3558 error_handling.band_index(band, self.norb)
3559 ks = np.atleast_2d(np.asarray(ks, dtype='f8'))
3560 error_handling.ks(ks, self.dim)
3561 ops = [self.spin_operator(a) for a in 'xyz']
3562 return self._expectations(ks, ops)[:, :, band].T
3564 def _fold(self, elements: NDArray[np.float64]) -> NDArray[np.float64]:
3565 '''
3566 Private method. Bring segments or triangles (fractional coordinates,
3567 shape (n, nv, dim)) into the first Brillouin zone (the Wigner-Seitz
3568 cell of the reciprocal lattice, by their centres), in the k
3569 coordinates of *get_ham*.
3570 '''
3571 elements = elements - np.floor(elements.mean(axis=1) + 0.5)[:, None, :]
3572 cart = elements @ self.rec_vec_k
3573 shifts = np.array(list(product((-1, 0, 1), repeat=self.dim))) @ self.rec_vec_k
3574 dist = np.linalg.norm(cart.mean(axis=1)[:, None, :] - shifts[None], axis=2)
3575 return cart - shifts[np.argmin(dist, axis=1)][:, None, :]
3577 def fermi_surface(
3578 self, energy: float = 0., nk: int | tuple[int, ...] | None = None,
3579 bands: int | list[int] | None = None,
3580 ) -> list[NDArray[np.float64]]:
3581 r'''
3582 Get the constant-energy surfaces :math:`E_n(\mathbf{k}) = E` (the
3583 Fermi surface at :math:`E = E_F`): lines in a 2D Brillouin zone,
3584 surfaces in 3D. The bands are interpolated linearly in the triangles
3585 (tetrahedra in 3D) of a uniform mesh, the same decomposition as
3586 *dos.tetrahedron_dos*, and the level set of each simplex is a segment
3587 (a triangle or a quadrilateral, split in two, in 3D): marching
3588 triangles and tetrahedra, exact for the interpolated bands. Each
3589 piece is brought into the first Brillouin zone, the Wigner-Seitz
3590 cell around :math:`\Gamma`. For a non-Hermitian model, the real part
3591 of the energies is used.
3593 Parameters
3594 ----------
3595 energy : Real number, default 0
3596 The energy :math:`E`.
3597 nk : Positive integer, or tuple of *dim* positive integers, default None: 100 in 2D, 40 in 3D
3598 Number of k-points along
3599 each reciprocal lattice vector.
3600 bands : Band index, or list of band indices
3601 Default value
3602 None: all bands.
3604 Returns
3605 -------
3606 surfaces
3607 List, one entry per band of *bands*: a real
3608 ndarray of shape (n, 2, 2) in 2D (n segments, each two k-points)
3609 or (n, 3, 3) in 3D (n triangles, each three k-points), in the
3610 k coordinates of *get_ham*. Empty (n = 0) if the band does not
3611 cross *energy*.
3613 Examples
3614 --------
3615 Example usage::
3617 # the Fermi surface of the half-filled square lattice
3618 segments = sq.fermi_surface(0.)[0]
3619 '''
3620 error_handling.dim_min(self.dim, 2)
3621 error_handling.real_number(energy, 'energy')
3622 if nk is None:
3623 nk = 100 if self.dim == 2 else 40
3624 error_handling.nk(nk, self.dim)
3625 if isinstance(nk, int):
3626 nk = (nk,) * self.dim
3627 if bands is None:
3628 bands = list(range(self.norb))
3629 elif isinstance(bands, int):
3630 bands = [bands]
3631 error_handling.band_indices(bands, self.norb)
3632 _, ks = self.mesh_grid(nk)
3633 en = self._eigs(ks).real.reshape(*nk, self.norb)
3634 return [self._fold(_level_set(en[..., n], energy)) for n in bands]
3636 def _k_labels(self) -> list[str]:
3637 '''
3638 Private method. Axis labels of the k coordinates of *get_ham*:
3639 '$k_x$' for a coordinate along the Cartesian x axis (the slab of a
3640 3D model along x and z gives '$k_x$', '$k_z$'), '$k_1$', ... otherwise.
3641 '''
3642 labels = []
3643 for n, col in enumerate(self.k_basis.T):
3644 axis = np.nonzero(np.isclose(np.abs(col), 1.))[0]
3645 labels.append('$k_{}$'.format('xyz'[axis[0]] if len(axis) else n + 1))
3646 return labels
3648 def _zone_axes(self, ax, fs: float) -> None:
3649 '''
3650 Private method. Draw the first Brillouin zone of a 2D model on *ax*,
3651 and label and scale its axes.
3652 '''
3653 zone = _zone_polygon(self.rec_vec_k)
3654 ax.plot(*np.vstack([zone, zone[:1]]).T, 'k', lw=1)
3655 ax.set_aspect('equal')
3656 pad = 0.05 * np.ptp(zone, axis=0).max()
3657 ax.set_xlim(zone[:, 0].min() - pad, zone[:, 0].max() + pad)
3658 ax.set_ylim(zone[:, 1].min() - pad, zone[:, 1].max() + pad)
3659 ax.set_xlabel(self._k_labels()[0], fontsize=fs)
3660 ax.set_ylabel(self._k_labels()[1], fontsize=fs)
3662 def plot_fermi_surface(
3663 self, energy: float = 0., nk: int | tuple[int, ...] | None = None,
3664 bands: int | list[int] | None = None, lw: float = 2., alpha: float = 0.6,
3665 fs: float = 20, figsize: tuple[float, float] | None = None,
3666 ) -> Figure:
3667 '''
3668 Plot the constant-energy contours of *fermi_surface* (one color per
3669 band, with a legend if several bands cross the energy): lines inside
3670 the first Brillouin zone (drawn in black) in 2D, surfaces in 3D.
3672 Parameters
3673 ----------
3674 energy : Real number, default 0
3675 The energy.
3676 nk
3677 See *fermi_surface*.
3678 bands
3679 See *fermi_surface*.
3680 lw : Positive number, default 2
3681 Linewidth (2D).
3682 alpha : Real number in (0, 1], default 0.6
3683 Opacity of
3684 the surfaces (3D).
3685 fs : Positive number, default 20
3686 Fontsize.
3687 figsize : Tuple, default None
3688 Figure size.
3690 Returns
3691 -------
3692 fig : Figure
3693 '''
3694 error_handling.positive_real(lw, 'lw')
3695 error_handling.positive_real(alpha, 'alpha')
3696 error_handling.positive_real(fs, 'fs')
3697 error_handling.tuple_2elem(figsize, 'figsize')
3698 surfaces = self.fermi_surface(energy, nk, bands)
3699 bands = list(range(self.norb)) if bands is None else np.atleast_1d(bands).tolist()
3700 fig = plt.figure(figsize=figsize)
3701 if self.dim == 2:
3702 ax = fig.add_subplot()
3703 for n, (band, segs) in enumerate(zip(bands, surfaces)):
3704 if len(segs):
3705 ax.add_collection(LineCollection(list(segs), colors='C{}'.format(n % 10), lw=lw,
3706 label='band {}'.format(band)))
3707 self._zone_axes(ax, fs)
3708 else:
3709 ax = fig.add_subplot(projection='3d')
3710 for n, (band, tris) in enumerate(zip(bands, surfaces)):
3711 if len(tris):
3712 ax.add_collection3d(Poly3DCollection(tris, facecolor='C{}'.format(n % 10),
3713 alpha=min(alpha, 1.), edgecolor='none',
3714 label='band {}'.format(band)))
3715 extent = np.abs(np.concatenate([t.reshape(-1, 3) for t in surfaces] +
3716 [self.rec_vec_k / 2])).max()
3717 ax.set(xlim=(-extent, extent), ylim=(-extent, extent), zlim=(-extent, extent))
3718 ax.set_box_aspect((1, 1, 1))
3719 ax.set_xlabel(self._k_labels()[0], fontsize=fs)
3720 ax.set_ylabel(self._k_labels()[1], fontsize=fs)
3721 ax.set_zlabel(self._k_labels()[2], fontsize=fs)
3722 if sum(len(s) > 0 for s in surfaces) > 1:
3723 ax.legend(fontsize=0.6 * fs)
3724 ax.set_title('$E = {:g}$'.format(energy), fontsize=fs)
3725 plt.draw()
3726 return fig
3728 def plot_spin_texture(
3729 self, band: int, energy: float = 0., nk: int = 100, n_arrows: int = 40,
3730 cmap: str = 'RdBu_r', lw: float = 1., fs: float = 20,
3731 figsize: tuple[float, float] | None = None,
3732 ) -> Figure:
3733 r'''
3734 Plot the spin texture of a band of a 2D spinful model on its
3735 constant-energy contour (see *fermi_surface*), zoomed on the
3736 contour: arrows of
3737 :math:`(\langle\sigma_x\rangle, \langle\sigma_y\rangle)` along the
3738 contour, colored by :math:`\langle\sigma_z\rangle` (see *spin_texture*).
3739 Rashba coupling, for instance, locks the spin perpendicular to
3740 :math:`\mathbf{k}`, winding once around the contour.
3742 Parameters
3743 ----------
3744 band : Integer
3745 Band index.
3746 energy : Real number, default 0
3747 Energy of the contour.
3748 nk : Positive integer, default 100
3749 Mesh of the contour.
3750 n_arrows : Positive integer, default 40
3751 Approximate
3752 number of arrows, evenly spaced along the contour. A fully
3753 polarized in-plane spin is drawn 80% as long as their spacing.
3754 cmap
3755 Default value 'RdBu_r'. Colormap of :math:`\langle\sigma_z\rangle`.
3756 lw : Positive number, default 1
3757 Linewidth of the contour.
3758 fs : Positive number, default 20
3759 Fontsize.
3760 figsize : Tuple, default None
3761 Figure size.
3763 Returns
3764 -------
3765 fig : Figure
3766 '''
3767 error_handling.dim_2(self.dim)
3768 error_handling.spinful(self.spin)
3769 error_handling.band_index(band, self.norb)
3770 error_handling.positive_int(nk, 'nk')
3771 error_handling.positive_int(n_arrows, 'n_arrows')
3772 error_handling.positive_real(lw, 'lw')
3773 error_handling.positive_real(fs, 'fs')
3774 error_handling.tuple_2elem(figsize, 'figsize')
3775 segs = self.fermi_surface(energy, nk, [band])[0]
3776 error_handling.contour_found(len(segs), energy)
3777 # arrows at segment midpoints, at least one contour length / n_arrows apart
3778 mids = segs.mean(axis=1)
3779 spacing = np.linalg.norm(segs[:, 1] - segs[:, 0], axis=1).sum() / n_arrows
3780 keep = [0]
3781 for i in range(1, len(mids)):
3782 if np.min(np.linalg.norm(mids[keep] - mids[i], axis=1)) >= spacing:
3783 keep.append(i)
3784 spin = self.spin_texture(mids[keep], band)
3785 fig, ax = plt.subplots(figsize=figsize)
3786 ax.add_collection(LineCollection(list(segs), colors='0.6', lw=lw))
3787 arrows = ax.quiver(mids[keep, 0], mids[keep, 1], spin[:, 0], spin[:, 1], spin[:, 2],
3788 cmap=cmap, norm=Normalize(-1., 1.), pivot='mid', edgecolor='k',
3789 linewidth=0.5, angles='xy', scale_units='xy', scale=1.25 / spacing)
3790 fig.colorbar(arrows, ax=ax).set_label(r'$\langle\sigma_z\rangle$', fontsize=fs)
3791 self._zone_axes(ax, fs)
3792 # zoom on the contour (within the zone)
3793 low, high = segs.reshape(-1, 2).min(axis=0), segs.reshape(-1, 2).max(axis=0)
3794 pad = 0.1 * (high - low).max() + spacing
3795 ax.set_xlim(max(ax.get_xlim()[0], low[0] - pad), min(ax.get_xlim()[1], high[0] + pad))
3796 ax.set_ylim(max(ax.get_ylim()[0], low[1] - pad), min(ax.get_ylim()[1], high[1] + pad))
3797 ax.set_title('Spin texture of band {}, $E = {:g}$'.format(band, energy), fontsize=fs)
3798 plt.draw()
3799 return fig
3801 def plot_berry_curvature(
3802 self, bands: int | list[int], nk: int | tuple[int, int] = 60,
3803 plane: tuple[int, int] = (0, 1), k_fixed: float = 0., cmap: str = 'RdBu_r',
3804 fs: float = 20, figsize: tuple[float, float] | None = None,
3805 ) -> Figure:
3806 r'''
3807 Plot the Berry curvature of *berry_curvature* as a density,
3808 :math:`\Omega(\mathbf{k})` = flux of each plaquette / its area. In
3809 2D, the plaquettes are brought into the first Brillouin zone (drawn
3810 in black), in the k coordinates of *get_ham*. In 3D, they fill the
3811 parallelogram spanned by the two reciprocal vectors of *plane*, in
3812 orthonormal coordinates of the plane (:math:`k_1` along
3813 :math:`\mathbf{b}_i`). The title gives the Chern number, the total
3814 flux over :math:`2\pi`.
3816 Parameters
3817 ----------
3818 bands
3819 See *berry_curvature*.
3820 nk
3821 Default value 60. See *berry_curvature*.
3822 plane
3823 See *berry_curvature*.
3824 k_fixed
3825 See *berry_curvature*.
3826 cmap
3827 Default value 'RdBu_r'. Colormap, centred on zero.
3828 fs : Positive number, default 20
3829 Fontsize.
3830 figsize : Tuple, default None
3831 Figure size.
3833 Returns
3834 -------
3835 fig : Figure
3836 '''
3837 error_handling.positive_real(fs, 'fs')
3838 error_handling.tuple_2elem(figsize, 'figsize')
3839 curv = self.berry_curvature(bands, nk, plane, k_fixed)
3840 n1, n2 = curv.shape
3841 # the corners of each plaquette, counterclockwise, in fractional coordinates
3842 f1, f2 = np.meshgrid(np.arange(n1) / n1, np.arange(n2) / n2, indexing='ij')
3843 corner = np.stack([f1.ravel(), f2.ravel()], axis=-1)[:, None, :]
3844 quads = corner + np.array([[0., 0.], [1. / n1, 0.], [1. / n1, 1. / n2], [0., 1. / n2]])
3845 b_i, b_j = self.rec_vec_k[plane[0]], self.rec_vec_k[plane[1]]
3846 if self.dim == 2:
3847 quads = self._fold(quads)
3848 else:
3849 # orthonormal coordinates of the plane, the first along b_i
3850 u = b_i / np.linalg.norm(b_i)
3851 v = b_j - (b_j @ u) * u
3852 b_i, b_j = np.array([b_i @ u, 0.]), np.array([b_j @ u, b_j @ v / np.linalg.norm(v)])
3853 quads = quads @ np.array([b_i, b_j])
3854 area = abs(b_i[0] * b_j[1] - b_i[1] * b_j[0]) / (n1 * n2)
3855 omega = curv.ravel() / area
3856 vmax = np.abs(omega).max() or 1.
3857 fig, ax = plt.subplots(figsize=figsize)
3858 patches = PolyCollection(quads, array=omega, cmap=cmap, norm=Normalize(-vmax, vmax),
3859 edgecolors='face', linewidths=0.2)
3860 ax.add_collection(patches)
3861 fig.colorbar(patches, ax=ax).set_label(r'$\Omega(\mathbf{k})$', fontsize=fs)
3862 if self.dim == 2:
3863 self._zone_axes(ax, fs)
3864 else:
3865 ax.autoscale_view()
3866 ax.set_aspect('equal')
3867 ax.set_xlabel('$k_1$', fontsize=fs)
3868 ax.set_ylabel('$k_2$', fontsize=fs)
3869 ax.set_title('Berry curvature, $C = {:.3f}$'.format(curv.sum() / (2 * PI)), fontsize=fs)
3870 fig.set_layout_engine('tight')
3871 plt.draw()
3872 return fig
3874 def plot_wannier_flow(
3875 self, bands: int | list[int], nk: int = 100, nk_perp: int = 51, direction: int = 0,
3876 flow: int | None = None, k_fixed: float = 0., positions: bool = True,
3877 k_range: tuple[float, float] = (0., 1.), ms: float = 4., c: str = 'b', fs: float = 20,
3878 figsize: tuple[float, float] | None = None,
3879 ) -> Figure:
3880 r'''
3881 Plot the flow of the hybrid Wannier centres (the Wilson-loop
3882 spectrum) of *wannier_flow*: the centres along *direction*, in
3883 units of :math:`\mathbf{a}_{direction}`, as the loop moves along
3884 the reciprocal vector *flow*. They wind :math:`C` times in a Chern
3885 insulator, and the Kramers pairs swap partners in a
3886 :math:`\mathbb{Z}_2` topological insulator.
3888 Parameters
3889 ----------
3890 bands
3891 See *wannier_flow*.
3892 nk
3893 See *wannier_flow*.
3894 nk_perp
3895 See *wannier_flow*.
3896 direction
3897 See *wannier_flow*.
3898 flow
3899 See *wannier_flow*.
3900 k_fixed
3901 See *wannier_flow*.
3902 positions
3903 See *wannier_flow*.
3904 k_range
3905 See *wannier_flow*.
3906 ms : Positive number, default 4
3907 Marker size.
3908 c
3909 Default value 'b'. Marker color.
3910 fs : Positive number, default 20
3911 Fontsize.
3912 figsize : Tuple, default None
3913 Figure size.
3915 Returns
3916 -------
3917 fig : Figure
3918 '''
3919 error_handling.positive_real(ms, 'ms')
3920 error_handling.positive_real(fs, 'fs')
3921 error_handling.tuple_2elem(figsize, 'figsize')
3922 fracs, centers = self.wannier_flow(bands, nk, nk_perp, direction, flow, k_fixed,
3923 positions, k_range)
3924 if flow is None:
3925 flow = [d for d in range(self.dim) if d != direction][0]
3926 fig, ax = plt.subplots(figsize=figsize)
3927 ax.plot(fracs, centers, 'o', c=c, ms=ms)
3928 ax.set_xlim(fracs[0], fracs[-1])
3929 ax.set_ylim(0., 1.)
3930 ax.set_xlabel(r'$k_{0}/|\mathbf{{b}}_{0}|$'.format(flow + 1), fontsize=fs)
3931 ax.set_ylabel(r'Wannier centres ($\mathbf{{a}}_{}$)'.format(direction + 1), fontsize=fs)
3932 fig.set_layout_engine('tight')
3933 plt.draw()
3934 return fig
3936 def plot_surface_spectral_function(
3937 self, points: list[ArrayLike], energies: ArrayLike, direction: int, nk: int = 60,
3938 side: int = 1, eta: float = 1e-2, bulk: bool = False,
3939 node_labels: list[str] | None = None, log: bool = True, cmap: str = 'magma',
3940 fs: float = 20, figsize: tuple[float, float] | None = None,
3941 ) -> Figure:
3942 r'''
3943 Plot the surface spectral function of *surface_spectral_function*
3944 along a path through the surface Brillouin zone (built as in
3945 *k_path*), as an ARPES-like map of :math:`E` against
3946 :math:`\mathbf{k}_\parallel`. Surface states are the sharp lines in
3947 the bulk gaps.
3949 Parameters
3950 ----------
3951 points : List of at least two k-points, the nodes of the path (see *k_path*)
3952 energies : Real array
3953 Energies :math:`E`.
3954 direction
3955 See *surface_spectral_function*.
3956 nk : Positive integer, default 60
3957 Number of k-points per path segment.
3958 side
3959 See *surface_spectral_function*.
3960 eta
3961 See *surface_spectral_function*.
3962 bulk
3963 See *surface_spectral_function*.
3964 node_labels : List of strings, default None
3965 Labels of *points*.
3966 log : Boolean, default True
3967 Logarithmic color scale, over
3968 four decades below the maximum (the surface states are much
3969 sharper than the bulk continuum).
3970 cmap
3971 Default value 'magma'. Colormap.
3972 fs : Positive number, default 20
3973 Fontsize.
3974 figsize : Tuple, default None
3975 Figure size.
3977 Returns
3978 -------
3979 fig : Figure
3980 '''
3981 error_handling.k_path_points(points, self.dim)
3982 error_handling.positive_int(nk, 'nk')
3983 error_handling.boolean(log, 'log')
3984 error_handling.positive_real(fs, 'fs')
3985 error_handling.tuple_2elem(figsize, 'figsize')
3986 if node_labels is not None:
3987 error_handling.ndarray(np.array(node_labels), 'node_labels', len(points))
3988 ks, dist, nodes = _path(points, nk)
3989 spec = self.surface_spectral_function(ks, energies, direction, side, eta, bulk)
3990 energies = np.atleast_1d(np.asarray(energies, dtype='f8'))
3991 vmax = spec.max() if spec.max() > 0 else 1.
3992 norm = LogNorm(vmax * 1e-4, vmax) if log else Normalize(0., vmax)
3993 fig, ax = plt.subplots(figsize=figsize)
3994 mesh = ax.pcolormesh(dist, energies, np.maximum(spec, vmax * 1e-4).T, cmap=cmap,
3995 norm=norm, shading='nearest')
3996 fig.colorbar(mesh, ax=ax).set_label(r'$A(\mathbf{k}_\parallel, E)$', fontsize=fs)
3997 for node in nodes:
3998 ax.axvline(node, color='w', lw=0.5)
3999 if node_labels is not None:
4000 ax.set_xticks(nodes)
4001 ax.set_xticklabels(node_labels, fontsize=fs)
4002 ax.set_ylabel('$E$', fontsize=fs)
4003 ax.set_title('Bulk' if bulk else 'Surface', fontsize=fs)
4004 fig.set_layout_engine('tight')
4005 plt.draw()
4006 return fig
4008 def plot_dos(
4009 self,
4010 nk: int | tuple[int, ...] = 30,
4011 broadening: float = 0.05,
4012 kernel: str = 'gaussian',
4013 e_grid: ArrayLike | None = None,
4014 fs: float = 20,
4015 lw: float = 2.,
4016 figsize: tuple[float, float] | None = None,
4017 ) -> Figure:
4018 '''
4019 Plot the density of states, obtained by diagonalizing
4020 :math:`H(\\mathbf{k})` over a uniform Brillouin-zone mesh: broadened
4021 (see *tbkit.dos.density_of_states*), or by the linear tetrahedron
4022 method (``kernel='tetrahedron'``, see *tbkit.dos.tetrahedron_dos*),
4023 which needs no broadening and keeps band edges and van Hove
4024 singularities sharp.
4026 Parameters
4027 ----------
4028 nk : Positive integer, or tuple of *dim* positive integers, default 30
4029 Number of k-points along each reciprocal
4030 lattice vector.
4031 broadening : Positive real number, default 0.05
4032 Kernel
4033 width (unused by the tetrahedron method).
4034 kernel : String, default 'gaussian'
4035 'gaussian',
4036 'lorentzian' or 'tetrahedron'.
4037 e_grid : Real ndarray, default None
4038 Energies at which to
4039 evaluate the density of states.
4040 fs : Positive number, default 20
4041 Fontsize.
4042 lw : Positive number, default 2
4043 Linewidth.
4044 figsize : Tuple, default None
4045 Figure size.
4047 Returns
4048 -------
4049 fig : Figure
4050 '''
4051 error_handling.positive_real(fs, 'fs')
4052 error_handling.positive_real(lw, 'lw')
4053 error_handling.tuple_2elem(figsize, 'figsize')
4054 error_handling.kspace_dos_kernel(kernel)
4055 en = self.mesh_bands(nk)
4056 if kernel != 'tetrahedron':
4057 return dos._plot_density_of_states(en, e_grid, broadening, kernel, fs, lw, figsize)
4058 nk = (nk,) * self.dim if isinstance(nk, int) else nk
4059 e_grid, rho = dos.tetrahedron_dos(en.reshape(*nk, self.norb), e_grid)
4060 return dos._plot_dos_curve(e_grid, rho, fs, lw, figsize)
4062 def plot_bands(
4063 self,
4064 node_labels: list[str] | None = None,
4065 fs: float = 20,
4066 lw: float = 2.,
4067 ms: float = 0.,
4068 c: str = 'b',
4069 lims: tuple[float, float] | None = None,
4070 figsize: tuple[float, float] | None = None,
4071 weights: ArrayLike | None = None,
4072 style: str = 'color',
4073 cmap: str | None = None,
4074 irreps: list | bool | None = None,
4075 ) -> Figure:
4076 '''
4077 Plot the band structure computed by *k_path* or *get_bands*, against
4078 the cumulative distance along the k-points (vertical lines mark the
4079 nodes of a *k_path*). For a non-Hermitian model, the real part of
4080 the energies is plotted. With *weights* (e.g. from *band_weights*:
4081 an orbital, sublattice or spin projection), a "fat band" plot: the
4082 bands are colored by the weights (with a colorbar), or drawn with
4083 dots sized by their absolute value.
4085 Parameters
4086 ----------
4087 node_labels : List of strings, default None
4088 Labels of the
4089 high-symmetry points passed to *k_path*.
4090 fs : Positive number, default 20
4091 Fontsize.
4092 lw : Positive number, default 2
4093 Linewidth.
4094 ms : Positive number, default 0
4095 Marker size.
4096 c
4097 Default value 'b'. Line color.
4098 lims : List, default None
4099 Energy plot limits.
4100 figsize : Tuple, default None
4101 Figure size.
4102 weights : Real array, shape (nk, norb), default None
4103 One weight per k-point and band, e.g. from *band_weights*.
4104 style : String, default 'color'
4105 'color': the bands
4106 colored by *weights*; 'size': dots of size proportional to
4107 :math:`|w|` (*ms*, or 8 if *ms* is 0, for the largest) on thin
4108 lines of color *c*.
4109 cmap
4110 Default value None ('viridis', or 'RdBu_r', centred on
4111 zero, if some weights are negative). Colormap of *style* 'color'.
4112 irreps : List of **Operation**, or True, default None
4113 Write, at each node of
4114 the *k_path*, the irreducible representation of each level (see
4115 *symmetry.irreps*), for these operations (True: those of
4116 *symmetry.find_symmetries*). Nodes whose point group is not
4117 tabulated (in 3D, the non-cubic ones) are left unlabelled.
4119 Returns
4120 -------
4121 fig : Figure
4122 '''
4123 error_handling.empty_ndarray(self.en, 'get_bands or k_path')
4124 error_handling.positive_real(fs, 'fs')
4125 error_handling.positive_real(lw, 'lw')
4126 error_handling.lims(lims)
4127 error_handling.tuple_2elem(figsize, 'figsize')
4128 if irreps is not None and irreps is not False:
4129 error_handling.empty_ndarray(self.nodes, 'k_path')
4130 error_handling.spinless_irreps(self.spin)
4131 fig, ax = plt.subplots(figsize=figsize)
4132 if weights is None:
4133 for n in range(self.norb):
4134 ax.plot(self.ks_dist, self.en[:, n].real, c=c, lw=lw, marker='o', ms=ms)
4135 else:
4136 self._plot_fat_bands(fig, ax, weights, style, cmap, c, lw, ms)
4137 for node in self.nodes:
4138 ax.axvline(node, color='k', lw=0.5)
4139 ax.set_xlim(self.ks_dist[0], self.ks_dist[-1])
4140 if lims is not None:
4141 ax.set_ylim(lims)
4142 if node_labels is not None:
4143 error_handling.ndarray(np.array(node_labels), 'node_labels', len(self.nodes))
4144 ax.set_xticks(self.nodes)
4145 ax.set_xticklabels(node_labels, fontsize=fs)
4146 if irreps is not None and irreps is not False:
4147 self._plot_irreps(ax, irreps, fs)
4148 ax.set_ylabel('$E$', fontsize=fs)
4149 for label in ax.yaxis.get_majorticklabels():
4150 label.set_fontsize(fs)
4151 fig.set_layout_engine('tight')
4152 plt.draw()
4153 return fig
4155 def _plot_irreps(self, ax, ops, fs: float) -> None:
4156 '''
4157 Private method. The irreps of the levels at the nodes of the k-path
4158 (see *plot_bands*).
4159 '''
4160 from tbkit import symmetry
4161 ops = symmetry.find_symmetries(self, antiunitary=False) if ops is True else ops
4162 error_handling.operations(ops)
4163 for node in self.nodes:
4164 index = int(np.argmin(np.abs(self.ks_dist - node)))
4165 res = symmetry._irreps(self, self.ks[index], ops, 1e-6)
4166 if res is None:
4167 continue
4168 for energy, label in zip(res.energies, res.labels):
4169 ax.annotate(label, (node, energy), xytext=(3, 2), textcoords='offset points',
4170 fontsize=0.6 * fs)
4172 def _plot_fat_bands(self, fig, ax, weights, style, cmap, c, lw, ms) -> None:
4173 '''
4174 Private method. The bands of *plot_bands* colored (or with dots
4175 sized) by *weights*.
4176 '''
4177 error_handling.band_weights(weights, self.en.shape)
4178 error_handling.weight_style(style)
4179 weights = np.asarray(weights, dtype='f8')
4180 signed = weights.min() < 0
4181 vmax = np.abs(weights).max() or 1.
4182 if style == 'size':
4183 size = (ms or 8.) ** 2
4184 for n in range(self.norb):
4185 ax.plot(self.ks_dist, self.en[:, n].real, c=c, lw=lw / 4)
4186 ax.scatter(self.ks_dist, self.en[:, n].real, s=size * np.abs(weights[:, n]) / vmax,
4187 c=c, lw=0)
4188 return
4189 norm = Normalize(-vmax if signed else 0., vmax)
4190 cmap = cmap or ('RdBu_r' if signed else 'viridis')
4191 for n in range(self.norb):
4192 pts = np.stack([self.ks_dist, self.en[:, n].real], axis=-1)
4193 lines = LineCollection(list(np.stack([pts[:-1], pts[1:]], axis=1)), cmap=cmap, norm=norm, lw=lw)
4194 lines.set_array((weights[:-1, n] + weights[1:, n]) / 2)
4195 ax.add_collection(lines)
4196 ax.autoscale_view()
4197 fig.colorbar(lines, ax=ax)
4199 def show(self) -> None:
4200 '''
4201 Emulate Matplotlib method plt.show().
4202 '''
4203 plt.show()
4206def ribbon(
4207 lat: Lattice,
4208 list_hop: list[dict],
4209 width: int,
4210 direction: int = 1,
4211 onsite: dict | None = None,
4212 spin: bool = False,
4213) -> KSpace:
4214 r'''
4215 Cut a ribbon out of a 2D periodic model: periodic along one primitive
4216 vector, finite (open boundary, *width* unit cells) along the other.
4217 This is the standard way to see edge states in a band structure (e.g.
4218 the zero-energy edge band of a zigzag graphene ribbon, or the helical
4219 edge states of a Kane-Mele ribbon). Cut out of a 3D model, it gives a
4220 slab: periodic along the two other primitive vectors, the way to see
4221 surface states (e.g. the Fermi arcs of a Weyl semimetal).
4223 Parameters
4224 ----------
4225 lat
4226 **Lattice** class instance (2D or 3D, i.e. two or three primitive
4227 vectors). Only *unit_cell* and *prim_vec* are used.
4228 list_hop
4229 List of dictionaries, in the same format passed to
4230 *KSpace.set_hopping* -- the hoppings of the periodic (2D) model
4231 that the ribbon is cut from.
4232 width : Positive integer
4233 Number of unit cells across the ribbon.
4234 direction : 0 or 1 (or 2, in 3D), default 1
4235 Which primitive
4236 vector (``lat.prim_vec[direction]``) becomes finite; the others stay
4237 periodic.
4238 onsite : Dictionary, default None
4239 Onsite energies, in the
4240 same format passed to *KSpace.set_onsite* -- applied identically
4241 on every row of the ribbon.
4242 spin : Boolean, default False
4243 See *KSpace*.
4245 Returns
4246 -------
4247 rib
4248 **KSpace** instance, 1D-periodic (2D-periodic for a slab), with
4249 ``width * len(lat.unit_cell)`` sites (each site of *lat*,
4250 repeated once per row across the ribbon; row *w*'s copy of site
4251 *i* is orbital ``w*len(lat.unit_cell) + i``).
4253 Examples
4254 --------
4255 Example usage::
4257 # zigzag graphene ribbon, 20 unit cells wide
4258 list_hop = [{'i': 0, 'j': 1, 'R': (0, 0), 't': 1.},
4259 {'i': 0, 'j': 1, 'R': (-1, 0), 't': 1.},
4260 {'i': 0, 'j': 1, 'R': (0, -1), 't': 1.}]
4261 rib = ribbon(lat, list_hop, width=20)
4262 '''
4263 error_handling.lat(lat)
4264 error_handling.dim_min(len(lat.prim_vec), 2)
4265 error_handling.positive_int(width, 'width')
4266 error_handling.direction(direction, len(lat.prim_vec))
4267 periodic = [d for d in range(len(lat.prim_vec)) if d != direction]
4268 n_sites = len(lat.unit_cell)
4269 a_dir = np.array(lat.prim_vec[direction])
4270 new_unit_cell = []
4271 for w in range(width):
4272 for dic in lat.unit_cell:
4273 r0 = np.array(dic['r0']) + w*a_dir
4274 new_unit_cell.append({'tag': dic['tag'], 'r0': tuple(float(c) for c in r0)})
4275 new_lat = Lattice(unit_cell=new_unit_cell, prim_vec=[lat.prim_vec[d] for d in periodic])
4276 rib = KSpace(new_lat, spin=spin)
4277 new_list_hop = []
4278 for dic in list_hop:
4279 w2_shift = dic['R'][direction]
4280 n_periodic = tuple(dic['R'][d] for d in periodic)
4281 for w in range(width):
4282 w2 = w + w2_shift
4283 if 0 <= w2 < width:
4284 new_list_hop.append({'i': w*n_sites + dic['i'],
4285 'j': w2*n_sites + dic['j'],
4286 'R': n_periodic,
4287 't': dic['t']})
4288 rib.set_hopping(new_list_hop)
4289 if onsite is not None:
4290 rib.set_onsite(onsite)
4291 return rib
4294def magnetic_supercell(
4295 lat: Lattice,
4296 list_hop: list[dict],
4297 p: int,
4298 q: int,
4299 onsite: dict | None = None,
4300 spin: bool = False,
4301) -> KSpace:
4302 r'''
4303 Thread a uniform magnetic field through a 2D periodic model, with a
4304 rational flux :math:`\alpha = p/q` flux quanta per unit cell, and return
4305 the Bloch Hamiltonian of its magnetic unit cell: *q* cells along
4306 :math:`\mathbf{a}_1`. Each hopping gets its Peierls phase (see
4307 *System.set_peierls_phase*)
4309 .. math::
4311 \phi_{ij} = \frac{2\pi}{\Phi_0}\int_{\mathbf{r}_i}^{\mathbf{r}_j}\mathbf{A}\cdot d\mathbf{l}
4312 = 2\pi\alpha\,\frac{s_{1,i}+s_{1,j}}{2}\,(s_{2,j}-s_{2,i})
4314 in the gauge :math:`\mathbf{A} = \alpha\Phi_0\, s_1\nabla s_2`, with
4315 :math:`(s_1, s_2)` the fractional coordinates of a point along
4316 :math:`(\mathbf{a}_1, \mathbf{a}_2)`, periodic along :math:`\mathbf{a}_2`.
4317 A translation by :math:`q\mathbf{a}_1` is a symmetry only up to the
4318 gauge transformation :math:`e^{-2\pi i p s_2}`, which the hoppings
4319 crossing the magnetic cell boundary carry. The bands of the result are
4320 the Hofstadter subbands, and their *chern_number* the TKNN integers.
4322 Parameters
4323 ----------
4324 lat : **Lattice** class instance, 2D (two primitive vectors in the plane)
4325 list_hop
4326 List of dictionaries, the hoppings of the field-free
4327 model, in the format of *KSpace.set_hopping*.
4328 p : Integer
4329 Numerator of the flux per unit cell.
4330 q : Positive integer
4331 Denominator of the flux per unit cell: the
4332 magnetic cell has *q* unit cells.
4333 onsite : Dictionary, default None
4334 Onsite energies, in the
4335 format of *KSpace.set_onsite*, applied to every copy.
4336 spin : Boolean, default False
4337 See *KSpace*.
4339 Returns
4340 -------
4341 mag
4342 **KSpace** instance, with ``q * len(lat.unit_cell)``
4343 sites: copy *m* of site *i* is site ``m*len(lat.unit_cell) + i``,
4344 displaced by :math:`m\mathbf{a}_1`.
4346 Examples
4347 --------
4348 Example usage::
4350 # square lattice, flux 1/3 per plaquette: three Hofstadter bands
4351 mag = magnetic_supercell(lattices.square(), list_hop, p=1, q=3)
4352 chern = [mag.chern_number(bands=[n]) for n in range(3)]
4353 '''
4354 error_handling.lat(lat)
4355 error_handling.planar_cell(lat.prim_vec)
4356 error_handling.set_hopping_kspace(list_hop, len(lat.unit_cell), 2, spin)
4357 error_handling.integer(p, 'p')
4358 error_handling.positive_int(q, 'q')
4359 alpha = p / q
4360 n_sites = len(lat.unit_cell)
4361 a = np.array(lat.prim_vec, dtype='f8')
4362 frac = np.linalg.solve(a.T, np.array([dic['r0'] for dic in lat.unit_cell], dtype='f8').T).T
4363 new_unit_cell = []
4364 for m in range(q):
4365 for dic in lat.unit_cell:
4366 r0 = np.array(dic['r0'], dtype='f8') + m * a[0]
4367 new_unit_cell.append({'tag': dic['tag'], 'r0': (float(r0[0]), float(r0[1]))})
4368 new_lat = Lattice(unit_cell=new_unit_cell, prim_vec=[tuple(q * a[0]), lat.prim_vec[1]])
4369 mag = KSpace(new_lat, spin=spin)
4370 new_list_hop = []
4371 for dic in list_hop:
4372 n1, n2 = dic['R']
4373 for m in range(q):
4374 s1_i, s2_i = m + frac[dic['i'], 0], frac[dic['i'], 1]
4375 s1_j, s2_j = m + n1 + frac[dic['j'], 0], n2 + frac[dic['j'], 1]
4376 big, m_j = divmod(m + n1, q)
4377 phase = 2 * PI * alpha * 0.5 * (s1_i + s1_j) * (s2_j - s2_i) - 2 * PI * p * big * s2_j
4378 new_list_hop.append({'i': m * n_sites + dic['i'], 'j': m_j * n_sites + dic['j'],
4379 'R': (big, n2), 't': dic['t'] * np.exp(1j * phase)})
4380 mag.set_hopping(new_list_hop)
4381 if onsite is not None:
4382 mag.set_onsite(onsite)
4383 return mag
4386#################################
4387# K-PATHS AND CONSTANT-ENERGY CONTOURS
4388#################################
4391def _response_weights(
4392 en: NDArray[np.float64], mu: float, temperature: float, response: str,
4393) -> NDArray[np.float64]:
4394 r'''
4395 Private. The weights :math:`P_{nm}` of the Kubo pair sum of
4396 *KSpace._kubo*, shape (nk, n, n), from the bands *en* (nk, n). With
4397 :math:`x_n = (E_n-\mu)/T`, the conductivities are
4398 :math:`\sum_n w_n\Omega_n`, i.e. :math:`P_{nm} = -(w_n - w_m)`, with
4399 :math:`w = f` ('hall'), the entropy per state
4400 :math:`s = -f\ln f-(1-f)\ln(1-f)` ('nernst') and
4401 :math:`c_2/T = T\int_x^\infty y^2(-f'(y))\,dy` ('thermal'). The orbital
4402 magnetization ('magnetization'),
4403 :math:`\sum_n[f_n\,\mathrm{Im}\langle\partial_xu_n|(H-E_n)|\partial_yu_n\rangle + g_n\Omega_n]`
4404 with :math:`g = T\ln(1+e^{-x})` (:math:`\max(\mu-E, 0)` at :math:`T = 0`),
4405 has :math:`P_{nm} = \frac12(f_n+f_m)(E_m-E_n) - (g_n-g_m)`.
4406 '''
4407 if response == 'magnetization':
4408 f = occupation.fermi_dirac(en, mu, temperature)
4409 if temperature == 0:
4410 g = np.maximum(mu - en, 0.)
4411 else:
4412 g = temperature * np.logaddexp(0., -(en - mu) / temperature)
4413 return 0.5 * (f[:, :, None] + f[:, None, :]) * (en[:, None, :] - en[:, :, None]) \
4414 - (g[:, :, None] - g[:, None, :])
4415 w = _response_occupations(en, mu, temperature, response)
4416 return -(w[:, :, None] - w[:, None, :])
4419def _response_occupations(
4420 en: NDArray[np.float64], mu: float, temperature: float, response: str,
4421) -> NDArray[np.float64]:
4422 r'''
4423 Private. The weights :math:`w_n` of the responses
4424 :math:`\sum_n w_n\Omega_n` ('hall', 'nernst', 'thermal'), shape of
4425 *en*: see *_response_weights*.
4426 '''
4427 if response == 'hall':
4428 return occupation.fermi_dirac(en, mu, temperature)
4429 a = np.abs(en - mu) / temperature
4430 if response == 'nernst':
4431 return np.log1p(np.exp(-a)) + a * expit(-a)
4432 # int_a^inf y^2 (-f') dy = a^2 f(a) + 2 [a ln(1 + e^-a) - Li2(-e^-a)]
4433 # for a >= 0, and pi^2/3 minus it below the Fermi level
4434 # (Li2(z) = spence(1 - z) in scipy's convention)
4435 c2 = a ** 2 * expit(-a) + 2 * (a * np.log1p(np.exp(-a)) - spence(1 + np.exp(-a)))
4436 return temperature * np.where(en >= mu, c2, PI ** 2 / 3 - c2)
4439def _path(
4440 points: list[ArrayLike], nk: int,
4441) -> tuple[NDArray[np.float64], NDArray[np.float64], list[float]]:
4442 '''
4443 Private function. The k-points of a path through *points* (*nk* per
4444 segment, the last point included), their cumulative distance, and the
4445 positions of the nodes along it.
4446 '''
4447 pts = np.atleast_2d(np.asarray(points, dtype='f8'))
4448 ks = np.concatenate([np.linspace(pts[i], pts[i+1], nk, endpoint=False)
4449 for i in range(len(pts) - 1)] + [pts[-1:]])
4450 dist = np.concatenate([[0.], np.cumsum(np.linalg.norm(np.diff(ks, axis=0), axis=1))])
4451 return ks, dist, dist[::nk][:len(pts)-1].tolist() + [dist[-1]]
4454def _marching_table(dim: int) -> dict[int, list[list[tuple[int, int]]]]:
4455 '''
4456 Private function. For each pattern of the vertices of a triangle
4457 (*dim* = 2) or tetrahedron (*dim* = 3) above a level (bit m set if
4458 vertex m is above), the pieces of the level set, as lists of the edges
4459 (a, b) that they cross: one segment in 2D; one triangle, or two
4460 triangles forming a quadrilateral when two vertices are above, in 3D.
4461 '''
4462 table = {}
4463 for pattern in range(1, 2 ** (dim + 1) - 1):
4464 up = [m for m in range(dim + 1) if pattern >> m & 1]
4465 down = [m for m in range(dim + 1) if not pattern >> m & 1]
4466 if dim == 3 and len(up) == 2:
4467 (a, b), (c, d) = up, down
4468 table[pattern] = [[(a, c), (a, d), (b, d)], [(a, c), (b, d), (b, c)]]
4469 else:
4470 table[pattern] = [[(a, b) for a in up for b in down]]
4471 return table
4474def _level_set(values: NDArray[np.float64], level: float) -> NDArray[np.float64]:
4475 '''
4476 Private function. The level set ``values == level`` of a function on a
4477 periodic 2D or 3D mesh (*values* of shape (n1, n2) or (n1, n2, n3)),
4478 linear in each simplex of *dos._mesh_simplices*: segments (shape
4479 (n, 2, 2)) or triangles (shape (n, 3, 3)), in fractional coordinates
4480 (not folded: between 0 and 1 + 1/n_d).
4481 '''
4482 shape, dim = values.shape, values.ndim
4483 offsets = dos._mesh_simplices(dim)
4484 vals = dos._simplex_values(values - level, offsets).reshape(dim + 1, -1)
4485 pattern = sum((vals[m] > 0).astype(int) << m for m in range(dim + 1))
4486 pieces = [np.empty((0, dim, dim))]
4487 for pat, polygons in _marching_table(dim).items():
4488 sel = np.nonzero(pattern == pat)[0]
4489 if not len(sel):
4490 continue
4491 simplex, cell = np.divmod(sel, int(np.prod(shape)))
4492 corner = np.stack(np.unravel_index(cell, shape), axis=-1)
4493 pos = corner[None] + offsets[simplex].transpose(1, 0, 2)
4494 v = vals[:, sel]
4495 for polygon in polygons:
4496 # the crossing on edge (a, b): v[a] > 0 >= v[b] or the reverse
4497 pieces.append(np.stack([pos[a] + (v[a] / (v[a] - v[b]))[:, None] * (pos[b] - pos[a])
4498 for a, b in polygon], axis=1))
4499 return np.concatenate(pieces) / np.array(shape)
4502def _zone_polygon(rec: NDArray[np.float64]) -> NDArray[np.float64]:
4503 '''
4504 Private function. Vertices, counterclockwise, of the first Brillouin
4505 zone (Wigner-Seitz cell) of the 2D reciprocal lattice with basis *rec*
4506 (rows): the points at least as close to the origin as to any other
4507 reciprocal lattice vector, where two of the bisectors meet.
4508 '''
4509 gs = np.array([n @ rec for n in product(range(-2, 3), repeat=2) if any(n)])
4510 half = np.sum(gs ** 2, axis=1) / 2
4511 tol = 1e-9 * half.max()
4512 found = []
4513 for i in range(len(gs)):
4514 for j in range(i + 1, len(gs)):
4515 mat = gs[[i, j]]
4516 if abs(np.linalg.det(mat)) > tol:
4517 k = np.linalg.solve(mat, half[[i, j]])
4518 if np.all(gs @ k <= half + tol):
4519 found.append(k)
4520 verts = np.unique(np.round(np.array(found), 9), axis=0)
4521 return verts[np.argsort(np.arctan2(verts[:, 1], verts[:, 0]))]
4524def _gauss_reduce(u: NDArray[np.float64], v: NDArray[np.float64]):
4525 '''
4526 Private function. Gauss-reduced basis of a 2D lattice: the two
4527 shortest independent vectors, |u| <= |v|, at an obtuse (or right)
4528 angle, so that the edges of the Wigner-Seitz cell are normal to
4529 u, v and u + v.
4530 '''
4531 while True:
4532 if u @ u > v @ v:
4533 u, v = v, u
4534 m = np.round(u @ v / (u @ u))
4535 if m == 0:
4536 break
4537 v = v - m * u
4538 return (u, v - u) if u @ v > 0 else (u, v)
4541def _successive_minima(vecs: NDArray[np.float64]):
4542 '''
4543 Private function. The shortest lattice vectors of a 3D lattice with
4544 basis *vecs* (rows): the three successive minima, the shells of
4545 lattice vectors sorted by length (list of arrays), and their lengths.
4546 '''
4547 pts = np.array([n @ vecs for n in product(range(-3, 4), repeat=3) if any(n)])
4548 lengths = np.linalg.norm(pts, axis=1)
4549 # by length, then (among equal lengths) the most positive first: x, then y, then z
4550 order = np.lexsort((-pts[:, 2], -pts[:, 1], -pts[:, 0], np.round(lengths / lengths.min(), 6)))
4551 pts, lengths = pts[order], lengths[order]
4552 minima: list = []
4553 for p in pts:
4554 if np.linalg.matrix_rank(np.array(minima + [p]), tol=1e-8 * lengths[0]) == len(minima) + 1:
4555 minima.append(p)
4556 if len(minima) == 3:
4557 break
4558 bounds = np.nonzero(np.diff(lengths) > 1e-6 * lengths[0])[0] + 1
4559 return np.array(minima), np.split(pts, bounds), [s[0] for s in np.split(lengths, bounds)]
4562def _orthogonal_axes(shell: NDArray[np.float64]) -> NDArray[np.float64]:
4563 '''
4564 Private function. Three mutually orthogonal unit vectors among the
4565 vectors of *shell* (the conventional cubic axes).
4566 '''
4567 x = shell[0] / np.linalg.norm(shell[0])
4568 y = next(s for s in shell if abs(s @ x) < 1e-6 * np.linalg.norm(s))
4569 y = y / np.linalg.norm(y)
4570 return np.array([x, y, np.cross(x, y)])
4573def cubic_path(
4574 points: dict[str, ArrayLike], names: list[str], a: float = 1., axes: ArrayLike | None = None,
4575) -> tuple[list[NDArray[np.float64]], list[str]]:
4576 r'''
4577 Build a path through k-points given in the conventional coordinates of
4578 a cubic crystal: in units of :math:`2\pi/a` along the cubic axes, with
4579 :math:`a` the side of the conventional cube, as tables of high-symmetry
4580 points list them (e.g. :math:`X = (0, 1, 0)` and
4581 :math:`L = (\tfrac12, \tfrac12, \tfrac12)` for fcc). *high_symmetry_path*
4582 builds the standard simple cubic, fcc and bcc paths with it; use it
4583 for another path, or other points, of the same lattices.
4585 Parameters
4586 ----------
4587 points : Dictionary
4588 key: label, val: tuple of 3 real numbers,
4589 the point in units of :math:`2\pi/a`.
4590 names
4591 List of at least two labels (keys of *points*), the
4592 nodes of the path in order.
4593 a : Positive real, default 1
4594 Side of the conventional cube.
4595 axes : Real array, shape (3, 3)
4596 Default value None: the
4597 Cartesian axes. Rows: the three orthonormal cubic axes, in the
4598 coordinates of *KSpace.get_ham* (for a crystal whose cube is rotated).
4600 Returns
4601 -------
4602 points : List of real ndarrays, the k-points, for *KSpace.k_path*
4603 labels : List of strings, *names*, for *node_labels*
4605 Examples
4606 --------
4607 Example usage::
4609 # fcc, along Gamma - X - U and K - Gamma - L
4610 pts = {'G': (0, 0, 0), 'X': (0, 1, 0), 'U': (.25, 1, .25),
4611 'K': (.75, .75, 0), 'L': (.5, .5, .5)}
4612 points, labels = cubic_path(pts, ['G', 'X', 'U'], a=3.6)
4613 '''
4614 error_handling.cubic_path(points, names, axes)
4615 error_handling.positive_real(a, 'a')
4616 axes = np.eye(3) if axes is None else np.asarray(axes, dtype='f8')
4617 return [2 * PI / a * np.asarray(points[n], dtype='f8') @ axes for n in names], list(names)
4620def _bravais_3d(vecs: NDArray[np.float64]):
4621 '''
4622 Private function. The points and labels of the high-symmetry path of a
4623 3D lattice (basis *vecs*, rows), or (None, None) if it is not one of
4624 the simple cubic, fcc, bcc, simple tetragonal or hexagonal lattices.
4625 '''
4626 minima, shells, radii = _successive_minima(vecs)
4627 lengths = np.linalg.norm(minima, axis=1)
4628 pairs = [(0, 1), (0, 2), (1, 2)]
4629 cosine = {p: abs(minima[p[0]] @ minima[p[1]]) / (lengths[p[0]] * lengths[p[1]]) for p in pairs}
4630 equal = {p: abs(lengths[p[0]] - lengths[p[1]]) < 1e-6 * lengths[2] for p in pairs}
4631 right = {p: cosine[p] < 1e-6 for p in pairs}
4632 G = r'$\Gamma$'
4633 if all(right.values()):
4634 if all(equal.values()): # simple cubic
4635 return cubic_path({G: (0, 0, 0), 'X': (0, .5, 0), 'M': (.5, .5, 0), 'R': (.5, .5, .5)},
4636 [G, 'X', 'M', G, 'R', 'X'], lengths[0], minima / lengths[:, None])
4637 if sum(equal.values()) != 1: # orthorhombic
4638 return None, None
4639 # simple tetragonal: a, a, c
4640 (i, j), = [p for p in pairs if equal[p]]
4641 k = 3 - i - j
4642 a, c = lengths[i], lengths[k]
4643 axes = np.array([minima[i] / a, minima[j] / a, minima[k] / c])
4644 pts = {G: (0, 0, 0), 'X': (0, .5, 0), 'M': (.5, .5, 0), 'Z': (0, 0, .5),
4645 'R': (0, .5, .5), 'A': (.5, .5, .5)}
4646 names = [G, 'X', 'M', G, 'Z', 'R', 'A', 'Z']
4647 scale = 2 * PI * np.array([1 / a, 1 / a, 1 / c])
4648 return [(scale * pts[n]) @ axes for n in names], names
4649 for (i, j) in pairs:
4650 k = 3 - i - j
4651 if equal[(i, j)] and abs(cosine[(i, j)] - .5) < 1e-6 and \
4652 all(right[p] for p in pairs if p != (i, j)):
4653 # hexagonal: reciprocal vectors of (a1, a2, c), in-plane ones at 120 degrees
4654 rec = 2 * PI * np.linalg.inv(minima[[i, j, k]]).T
4655 b1, b2 = _gauss_reduce(rec[0], rec[1])
4656 M, K, A = b1 / 2, (2 * b1 + b2) / 3, rec[2] / 2
4657 hex_pts = {G: np.zeros(3), 'M': M, 'K': K, 'A': A, 'L': M + A, 'H': K + A}
4658 names = [G, 'M', 'K', G, 'A', 'L', 'H', 'A']
4659 return [hex_pts[n] for n in names], names
4660 if not all(equal.values()):
4661 return None, None
4662 if len(shells[0]) == 12: # fcc: 12 nearest neighbours at a/sqrt(2), then 6 at a
4663 return cubic_path({G: (0, 0, 0), 'X': (0, 1, 0), 'W': (.5, 1, 0), 'K': (.75, .75, 0),
4664 'L': (.5, .5, .5), 'U': (.25, 1, .25)},
4665 [G, 'X', 'W', 'K', G, 'L', 'U', 'W', 'L', 'K'],
4666 radii[1], _orthogonal_axes(shells[1]))
4667 if len(shells[0]) == 8 and all(abs(c - 1 / 3) < 1e-6 for c in cosine.values()):
4668 # bcc: 8 nearest neighbours at a sqrt(3)/2, then 6 at a
4669 return cubic_path({G: (0, 0, 0), 'H': (0, 0, 1), 'N': (.5, 0, .5), 'P': (.5, .5, .5)},
4670 [G, 'H', 'N', G, 'P', 'H'], radii[1], _orthogonal_axes(shells[1]))
4671 return None, None
4674def high_symmetry_path(lat: Lattice) -> tuple[list[NDArray[np.float64]], list[str]]:
4675 r'''
4676 Get a standard path through the high-symmetry points of the Brillouin
4677 zone of a lattice, for *KSpace.k_path* and the labels of
4678 *KSpace.plot_bands*. The Bravais lattice is recognized from
4679 *lat.prim_vec*, whatever the choice of primitive vectors and the
4680 orientation of the lattice:
4682 * 1D: :math:`-X, \Gamma, X` (the whole zone, :math:`X = \mathbf{b}/2`).
4683 * 2D (the five Bravais lattices): square :math:`\Gamma X M \Gamma`;
4684 rectangular :math:`\Gamma X S Y \Gamma`; hexagonal
4685 :math:`\Gamma M K \Gamma`; centred rectangular and oblique
4686 :math:`\Gamma X H C H_1 Y \Gamma`, along the edges of the
4687 zone: :math:`X, Y, C` are the midpoints of the edges normal to the
4688 reciprocal vectors :math:`\mathbf{b}_1, \mathbf{b}_2,
4689 \mathbf{b}_1+\mathbf{b}_2` of the reduced basis (with
4690 :math:`|\mathbf{b}_1| \le |\mathbf{b}_2|`), :math:`H` and
4691 :math:`H_1` the corners between them.
4692 * 3D: simple cubic :math:`\Gamma X M \Gamma R X`; fcc
4693 :math:`\Gamma X W K \Gamma L U W L K`; bcc :math:`\Gamma H N \Gamma P H`;
4694 simple tetragonal :math:`\Gamma X M \Gamma Z R A Z`; hexagonal
4695 :math:`\Gamma M K \Gamma A L H A`. These are the paths of Setyawan
4696 and Curtarolo (Comput. Mater. Sci. 49, 299 (2010)), up to their
4697 first discontinuity (a path here is one continuous line).
4699 The other 3D lattices (orthorhombic, monoclinic, body-centred
4700 tetragonal, rhombohedral, ...) raise a ValueError: give their points
4701 to *k_path* directly.
4703 Parameters
4704 ----------
4705 lat : **lattice** class instance (only *prim_vec* is used)
4707 Returns
4708 -------
4709 points
4710 List of real ndarrays, the k-points, in the
4711 coordinates of *KSpace.get_ham*.
4712 labels : List of strings (LaTeX), for *node_labels*
4714 Examples
4715 --------
4716 Example usage::
4718 points, labels = high_symmetry_path(lat)
4719 ks.k_path(points, nk=60)
4720 ks.plot_bands(node_labels=labels)
4721 '''
4722 ks = KSpace(lat)
4723 vecs = np.array(lat.prim_vec, dtype='f8') @ ks.k_basis # in the k coordinates
4724 G = r'$\Gamma$'
4725 if ks.dim == 1:
4726 x = PI / vecs[0]
4727 return [-x, np.zeros(1), x], ['$-X$', G, 'X']
4728 if ks.dim == 3:
4729 points, labels = _bravais_3d(vecs)
4730 error_handling.bravais_lattice(labels, 3)
4731 return points, labels
4732 rec = 2 * PI * np.linalg.inv(vecs).T
4733 b1, b2 = _gauss_reduce(rec[0], rec[1])
4734 l1, l2, l3 = (np.linalg.norm(b) for b in (b1, b2, b1 + b2))
4735 close = lambda a, b: abs(a - b) < 1e-6 * max(abs(a), abs(b))
4736 cosine = b1 @ b2 / (l1 * l2)
4737 if abs(cosine) < 1e-6:
4738 if close(l1, l2):
4739 return [np.zeros(2), b1 / 2, (b1 + b2) / 2, np.zeros(2)], [G, 'X', 'M', G]
4740 return [np.zeros(2), b1 / 2, (b1 + b2) / 2, b2 / 2, np.zeros(2)], [G, 'X', 'S', 'Y', G]
4741 if close(l1, l2) and close(cosine, -.5):
4742 return [np.zeros(2), b1 / 2, (2 * b1 + b2) / 3, np.zeros(2)], [G, 'M', 'K', G]
4743 # centred rectangular and oblique: around half of the hexagonal zone
4744 b3 = b1 + b2
4745 corner = lambda u, v: np.linalg.solve(np.array([u, v]), np.array([u @ u, v @ v]) / 2)
4746 return ([np.zeros(2), b1 / 2, corner(b1, b3), b3 / 2, corner(b2, b3), b2 / 2, np.zeros(2)],
4747 [G, 'X', 'H', 'C', '$H_1$', 'Y', G])