Coverage for tbkit/symmetry.py: 100%

488 statements  

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

1# Copyright 2014 Charles Poli. 

2# 

3# This file is part of TBKIT. It is subject to the license terms in the 

4# LICENSE file found in the top-level directory of this distribution and at 

5# https://github.com/cpoli/tbkit. 

6 

7r''' 

8Crystal symmetry of a Bloch Hamiltonian (:class:`tbkit.kspace.KSpace`). 

9 

10A space-group operation :math:`g = \{R|\boldsymbol\tau\}` (a rotation or 

11reflection :math:`R`, a translation :math:`\boldsymbol\tau`, a matrix 

12:math:`D` on the orbitals of a site, possibly times complex conjugation) is 

13an :class:`Operation`. It sends the orbital :math:`s` of the home cell to 

14the orbital :math:`\pi(s)` of the cell :math:`\mathbf{L}_s`, 

15:math:`R\boldsymbol\tau_s + \boldsymbol\tau = \boldsymbol\tau_{\pi(s)} + 

16\mathbf{L}_s`, so that in the periodic gauge of *KSpace* 

17 

18.. math:: 

19 

20 U_g(\mathbf{k})_{\pi(s), s} = D\, e^{-i g\mathbf{k}\cdot\mathbf{L}_s},\qquad 

21 H(g\mathbf{k}) = U_g(\mathbf{k})\, H(\mathbf{k})\, U_g(\mathbf{k})^\dagger 

22 

23(with :math:`H^*(\mathbf{k})` and :math:`g\mathbf{k} = -R\mathbf{k}` for an 

24antiunitary operation). On this representation are built: 

25 

26* :func:`find_symmetries`: the operations of the Bravais lattice that are 

27 symmetries of the model, as ``qsymm.symmetries`` does; 

28* :func:`irreps`: the irreducible representations of the bands at a 

29 k-point (Bouckaert, Smoluchowski and Wigner, Phys. Rev. 50, 58 (1936)), 

30 from the character tables of the ten 2D point groups and of the five 

31 cubic ones; *KSpace.plot_bands* writes them on the bands; 

32* the symmetry indicators :func:`rotation_indicator` (the Chern number 

33 modulo :math:`n` from the :math:`C_n` eigenvalues, Fang, Gilbert and 

34 Bernevig, Phys. Rev. B 86, 115112 (2012)), :func:`inversion_indicators` 

35 (Khalaf, Po, Vishwanath and Watanabe, Phys. Rev. X 8, 031070 (2018)) and 

36 :func:`corner_charge` (of a :math:`C_4`-symmetric insulator, Benalcazar, 

37 Li and Hughes, Phys. Rev. B 99, 245151 (2019)); 

38* :func:`symmetrize`: the group average of the hoppings, as 

39 ``TBmodels.Model.symmetrize``. 

40''' 

41 

42from __future__ import annotations 

43 

44import itertools 

45from typing import Callable 

46 

47import numpy as np 

48from numpy.typing import ArrayLike, NDArray 

49from scipy.spatial.transform import Rotation 

50 

51import tbkit.error_handling as error_handling 

52from tbkit.kspace import KSpace, PAULI 

53 

54PI = np.pi 

55TOL = 1e-6 # positions, rotation matrices and fractional coordinates 

56_I_SIGMA_Y = 1j * PAULI['y'] # the spin part of time reversal, T = i sigma_y K 

57 

58 

59class Operation(): 

60 r''' 

61 A space-group operation :math:`g = \{R|\boldsymbol\tau\}`: 

62 :math:`\mathbf{r} \to R\mathbf{r} + \boldsymbol\tau`, possibly 

63 antiunitary (times complex conjugation, e.g. time reversal). 

64 

65 Parameters 

66 ---------- 

67 rotation : Real ndarray, shape (space_dim, space_dim) 

68 Orthogonal matrix :math:`R` 

69 (a rotation, a reflection or the inversion), in the Cartesian frame 

70 of *prim_vec*. See :func:`rotation` and :func:`mirror`. 

71 translation : Real ndarray, shape (space_dim,), default None (zero) 

72 :math:`\boldsymbol\tau`. A rotation about a point 

73 :math:`\mathbf{c}` has :math:`\boldsymbol\tau = \mathbf{c} - R\mathbf{c}` 

74 (see :meth:`about`). *irreps* and the indicators need it so, not 

75 reduced modulo a lattice vector: :math:`\{R|\boldsymbol\tau + 

76 \mathbf{L}\}` is another element of the space group, whose 

77 characters differ by :math:`e^{-i\mathbf{k}\cdot\mathbf{L}}`. 

78 orbitals : Complex ndarray, default None 

79 Unitary matrix :math:`D` on the 

80 orbitals at one position of the unit cell (the entries of 

81 *unit_cell* that share a position, in their order, each twice, 

82 site-major, if ``spin=True``): orbital :math:`a` of a position goes 

83 to :math:`\sum_b D_{ba}\,b` at the image position. None: the 

84 identity on the orbitals and, if ``spin=True``, the spin-1/2 

85 rotation of :math:`\det(R)R` (times :math:`i\sigma_y` if 

86 *antiunitary*, so that the antiunitary identity is time reversal). 

87 Given, it must include the spin part. 

88 antiunitary : Boolean, default False 

89 name : String, default None (from the rotation) 

90 

91 Examples 

92 -------- 

93 Example usage:: 

94 

95 c3 = Operation.about(rotation(2 * np.pi / 3), center) # C3 about a hexagon centre 

96 mx = Operation(mirror((1., 0.))) # x -> -x 

97 time_reversal = Operation(np.eye(2), antiunitary=True) 

98 ks.symmetry_error(c3) 

99 ''' 

100 

101 def __init__( 

102 self, rotation: ArrayLike, translation: ArrayLike | None = None, orbitals: ArrayLike | None = None, 

103 antiunitary: bool = False, name: str | None = None, 

104 ) -> None: 

105 error_handling.operation(rotation, translation, orbitals, antiunitary, name) 

106 self.rotation = np.array(rotation, dtype='f8') 

107 d = len(self.rotation) 

108 self.translation = np.zeros(d) if translation is None else np.array(translation, dtype='f8') 

109 self.orbitals = None if orbitals is None else np.array(orbitals, dtype='c16') 

110 self.antiunitary = antiunitary 

111 self.name = _name(self.rotation, antiunitary) if name is None else name 

112 

113 @classmethod 

114 def about( 

115 cls, rotation: ArrayLike, center: ArrayLike, orbitals: ArrayLike | None = None, 

116 antiunitary: bool = False, name: str | None = None, 

117 ) -> Operation: 

118 r''' 

119 The operation :math:`R` about the point *center* :math:`\mathbf{c}`: 

120 :math:`\boldsymbol\tau = \mathbf{c} - R\mathbf{c}`. Other 

121 parameters: see :class:`Operation`. 

122 ''' 

123 error_handling.operation(rotation, None, orbitals, antiunitary, name) 

124 rot = np.array(rotation, dtype='f8') 

125 c = np.array(center, dtype='f8') 

126 error_handling.ndarray(c, 'center', len(rot)) 

127 return cls(rot, c - rot @ c, orbitals, antiunitary, name) 

128 

129 def __matmul__(self, other: Operation) -> Operation: 

130 r''' 

131 The product :math:`g_1 g_2` (*other* first): :math:`\{R_1R_2|R_1\boldsymbol\tau_2 + 

132 \boldsymbol\tau_1\}`, :math:`D_1 D_2` (:math:`D_1 D_2^*` if :math:`g_1` 

133 is antiunitary). With ``orbitals=None`` and spin, the spin part of the 

134 product is fixed up to a sign (the double group is not followed). 

135 ''' 

136 error_handling.compose(self, other) 

137 orb = None 

138 if self.orbitals is not None and other.orbitals is not None: 

139 orb = self.orbitals @ (other.orbitals.conj() if self.antiunitary else other.orbitals) 

140 return Operation(self.rotation @ other.rotation, self.rotation @ other.translation + self.translation, 

141 orb, self.antiunitary != other.antiunitary) 

142 

143 def __pow__(self, n: int) -> Operation: 

144 ''' 

145 :math:`g^n`, *n* a positive integer. 

146 ''' 

147 error_handling.positive_int(n, 'n') 

148 out = self 

149 for _ in range(n - 1): 

150 out = self @ out 

151 return out 

152 

153 def __repr__(self) -> str: 

154 return 'Operation({}, translation={})'.format(self.name, np.round(self.translation, 6).tolist()) 

155 

156 

157def rotation(angle: float, axis: ArrayLike | None = None) -> NDArray[np.float64]: 

158 r''' 

159 The matrix of a counterclockwise rotation by *angle* (radians): 2x2 in 

160 the plane, or 3x3 about *axis*. 

161 

162 Parameters 

163 ---------- 

164 angle : Real number 

165 axis : Real ndarray of 3 numbers, default None (a 2D rotation) 

166 

167 Returns 

168 ------- 

169 R : Real ndarray, shape (2, 2) or (3, 3) 

170 ''' 

171 error_handling.real_number(angle, 'angle') 

172 if axis is None: 

173 c, s = np.cos(angle), np.sin(angle) 

174 return np.array([[c, -s], [s, c]]) 

175 n = np.array(axis, dtype='f8') 

176 error_handling.ndarray(n, 'axis', 3) 

177 error_handling.nonzero_vector(n, 'axis') 

178 return Rotation.from_rotvec(angle * n / np.linalg.norm(n)).as_matrix() 

179 

180 

181def mirror(normal: ArrayLike) -> NDArray[np.float64]: 

182 r''' 

183 The matrix :math:`1 - 2\hat{\mathbf{n}}\hat{\mathbf{n}}^T` of the 

184 reflection through the line (2D) or plane (3D) normal to *normal*. 

185 

186 Parameters 

187 ---------- 

188 normal : Real ndarray of 2 or 3 numbers 

189 

190 Returns 

191 ------- 

192 R : Real ndarray, shape (len(normal), len(normal)) 

193 ''' 

194 n = np.array(normal, dtype='f8') 

195 error_handling.nonzero_vector(n, 'normal') 

196 n = n / np.linalg.norm(n) 

197 return np.eye(len(n)) - 2 * np.outer(n, n) 

198 

199 

200def _proper(rot: NDArray[np.float64]) -> NDArray[np.float64]: 

201 ''' 

202 Private function. The proper rotation det(R) R, embedded in 3D (a 2D 

203 operation acts on the plane z = 0 and leaves z unchanged: a 2D mirror 

204 is a vertical mirror plane). 

205 ''' 

206 r3 = np.eye(3) 

207 d = len(rot) 

208 r3[:d, :d] = rot 

209 return np.linalg.det(r3) * r3 

210 

211 

212def _su2(rot: NDArray[np.float64]) -> NDArray[np.complex128]: 

213 r''' 

214 Private function. The spin-1/2 matrix :math:`e^{-i\theta\hat{\mathbf{n}}\cdot\boldsymbol\sigma/2}` 

215 of the proper part of *rot* (one of its two signs). 

216 ''' 

217 x, y, z, w = Rotation.from_matrix(_proper(rot)).as_quat() 

218 return w * PAULI['0'] - 1j * (x * PAULI['x'] + y * PAULI['y'] + z * PAULI['z']) 

219 

220 

221def _angle_axis(rot: NDArray[np.float64]) -> tuple[float, NDArray[np.float64]]: 

222 ''' 

223 Private function. Angle in [0, pi] and unit axis of the proper part of *rot*. 

224 ''' 

225 vec = Rotation.from_matrix(_proper(rot)).as_rotvec() 

226 angle = float(np.linalg.norm(vec)) 

227 if angle < TOL: 

228 return 0., np.array([0., 0., 1.]) 

229 return angle, vec / angle 

230 

231 

232def _name(rot: NDArray[np.float64], antiunitary: bool) -> str: 

233 ''' 

234 Private function. A name for an operation: 'E', 'C3', 'C3^-1', 'M(30)' 

235 (a mirror line at 30 degrees), 'I', 'S4[0 0 1]', ... and ' T' if antiunitary. 

236 ''' 

237 det = np.linalg.det(rot) 

238 angle, axis = _angle_axis(rot) 

239 if len(rot) == 2: 

240 theta = float(np.arctan2(rot[1, 0], rot[0, 0])) 

241 if det < 0: 

242 name = 'M({:g})'.format(round(np.degrees(theta / 2) % 180., 3)) 

243 elif abs(theta) < TOL: 

244 name = 'E' 

245 else: 

246 n = int(round(2 * PI / abs(theta))) 

247 name = 'C{}'.format(n) + ('^-1' if theta < 0 and n > 2 else '') 

248 else: 

249 big = axis[np.argmax(np.abs(axis))] 

250 ax = '[{}]'.format(' '.join('{:g}'.format(round(c / big, 3) + 0.) for c in axis)) 

251 n = int(round(2 * PI / angle)) if angle > TOL else 1 

252 if det > 0: 

253 name = 'E' if n == 1 else 'C{}{}'.format(n, ax) 

254 elif n == 1: 

255 name = 'I' 

256 elif n == 2: 

257 name = 'M' + ax 

258 else: # -R = C_n: S_2n for odd n, S_(n/2) for n = 2 mod 4, S_n otherwise 

259 name = 'S{}{}'.format(2 * n if n % 2 else (n // 2 if n % 4 == 2 else n), ax) 

260 return name + (' T' if antiunitary else '') 

261 

262 

263class _Action(): 

264 ''' 

265 Private class. How an operation acts on the orbitals of a KSpace: the 

266 position blocks (orbital indices sharing a position), the permutation 

267 of the blocks, the lattice vectors L_s (integers and Cartesian), and the 

268 matrix D of each block. 

269 ''' 

270 

271 def __init__(self, ks: KSpace, op: Operation) -> None: 

272 error_handling.is_operation(op) 

273 error_handling.operation_space(op, ks.space_dim) 

274 tau = np.array([dic['r0'] for dic in ks.lat.unit_cell], dtype='f8').reshape(ks.n_sites, -1) 

275 keys: list = [] 

276 entries: list[list[int]] = [] 

277 for e, r in enumerate(tau): 

278 for b, p in enumerate(keys): 

279 if np.allclose(r, p, atol=TOL): 

280 entries[b].append(e) 

281 break 

282 else: 

283 keys.append(r) 

284 entries.append([e]) 

285 pos = np.array(keys) 

286 a = np.array(ks.lat.prim_vec, dtype='f8') 

287 diff = (pos @ op.rotation.T + op.translation)[:, None, :] - pos[None, :, :] 

288 frac = diff @ np.linalg.pinv(a) 

289 ints = np.round(frac) 

290 ok = np.all(np.abs(frac - ints) < TOL, axis=2) & np.all(np.abs(ints @ a - diff) < TOL, axis=2) 

291 error_handling.maps_lattice(ok) 

292 self.perm = np.argmax(ok, axis=1) 

293 self.L = ints[np.arange(len(pos)), self.perm].astype(int) 

294 self.L_cart = self.L @ a 

295 self.positions = pos 

296 self.idx = [np.array([2 * e + s for e in ent for s in range(2)] if ks.spin else ent) for ent in entries] 

297 self.tags = [tuple(ks.tags[ent]) for ent in entries] 

298 sizes = [len(i) for i in self.idx] 

299 error_handling.block_sizes(sizes, self.perm, None if op.orbitals is None else len(op.orbitals)) 

300 if op.orbitals is not None: 

301 self.D = [op.orbitals] * len(pos) 

302 elif ks.spin: 

303 s = _su2(op.rotation) @ (_I_SIGMA_Y if op.antiunitary else PAULI['0']) 

304 self.D = [np.kron(np.eye(n // 2), s) for n in sizes] 

305 else: 

306 self.D = [np.eye(n) for n in sizes] 

307 

308 

309def _representations( 

310 ks: KSpace, op: Operation, k: NDArray[np.float64], 

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

312 r''' 

313 Private function. The matrices :math:`U_g(\mathbf{k})` (shape (nk, norb, 

314 norb)) at the k-points *k* (shape (nk, dim), coordinates of *get_ham*), 

315 and the images :math:`g\mathbf{k}` (same coordinates). 

316 ''' 

317 act = _Action(ks, op) 

318 k_cart = np.atleast_2d(k) @ ks.k_basis.T 

319 gk = (-1. if op.antiunitary else 1.) * k_cart @ op.rotation.T 

320 phase = np.exp(-1j * gk @ act.L_cart.T) 

321 u = np.zeros((len(k_cart), ks.norb, ks.norb), dtype='c16') 

322 for b, target in enumerate(act.perm): 

323 u[:, act.idx[target][:, None], act.idx[b][None, :]] = phase[:, b, None, None] * act.D[b][None] 

324 return u, gk @ ks.k_basis 

325 

326 

327def representation(ks: KSpace, op: Operation, k: ArrayLike) -> NDArray[np.complex128]: 

328 r''' 

329 Get the matrix :math:`U_g(\mathbf{k})` of an operation on the Bloch 

330 basis of *ks* (periodic gauge), which sends :math:`\mathbf{k}` to 

331 :math:`g\mathbf{k}` (see the module docstring). 

332 

333 Parameters 

334 ---------- 

335 ks : **KSpace** instance 

336 op : :class:`Operation` 

337 k : k-point (coordinates of *KSpace.get_ham*) 

338 

339 Returns 

340 ------- 

341 U : Complex ndarray, shape (norb, norb) 

342 ''' 

343 error_handling.k_vector(k, 'k', ks.dim) 

344 return _representations(ks, op, np.array(k, dtype='f8')[None])[0][0] 

345 

346 

347def _lattice_rotations(a: NDArray[np.float64]) -> list[NDArray[np.float64]]: 

348 ''' 

349 Private function. The orthogonal matrices that map the lattice of the 

350 rows of *a* (dim = space_dim) onto itself: the point group of the 

351 Bravais lattice. 

352 ''' 

353 d = len(a) 

354 combos = np.array(list(itertools.product(range(-2, 3), repeat=d))) 

355 vecs = combos @ a 

356 norms = np.linalg.norm(vecs, axis=1) 

357 cands = [vecs[np.abs(norms - np.linalg.norm(v)) < TOL] for v in a] 

358 inv = np.linalg.inv(a.T) 

359 out: list[NDArray[np.float64]] = [] 

360 for combo in itertools.product(*cands): 

361 rot = np.array(combo).T @ inv 

362 if np.allclose(rot @ rot.T, np.eye(d), atol=TOL) and not any(np.allclose(rot, r, atol=TOL) for r in out): 

363 out.append(rot) 

364 return out 

365 

366 

367def _structure_translations(act_data: tuple, rot: NDArray[np.float64]) -> list[NDArray[np.float64]]: 

368 ''' 

369 Private function. The translations t (one per class modulo the lattice) 

370 for which {rot|t} maps the positions of the unit cell onto positions 

371 with as many orbitals (the tags are not compared: a sublattice mass is 

372 found broken by the Hamiltonian, not by its tags). *act_data* = 

373 (positions, orbitals per position, lattice rows). 

374 ''' 

375 pos, tags, a = act_data 

376 pinv = np.linalg.pinv(a) 

377 out: list[NDArray[np.float64]] = [] 

378 for target in range(len(pos)): 

379 t = pos[target] - rot @ pos[0] 

380 f = t @ pinv 

381 t = (f - np.floor(f + TOL)) @ a + (t - f @ a) # reduced into the cell (component off the lattice kept) 

382 diff = (pos @ rot.T + t)[:, None, :] - pos[None, :, :] 

383 frac = diff @ pinv 

384 ok = np.all(np.abs(frac - np.round(frac)) < TOL, axis=2) & np.all( 

385 np.abs(np.round(frac) @ a - diff) < TOL, axis=2) 

386 match = [np.flatnonzero(row) for row in ok] 

387 if all(len(m) == 1 and len(tags[int(m[0])]) == len(tags[s]) for s, m in enumerate(match)) and not any( 

388 _lattice_vector(t - u, a) for u in out): 

389 out.append(t) 

390 return out 

391 

392 

393def _lattice_vector(v: NDArray[np.float64], a: NDArray[np.float64]) -> bool: 

394 ''' 

395 Private function. Whether *v* is a lattice vector of the rows of *a*. 

396 ''' 

397 f = v @ np.linalg.pinv(a) 

398 return bool(np.all(np.abs(f - np.round(f)) < TOL) and np.allclose(np.round(f) @ a, v, atol=TOL)) 

399 

400 

401def _origin(cosets: list, a: NDArray[np.float64]) -> NDArray[np.float64] | None: 

402 r''' 

403 Private function. A point :math:`\mathbf{c}` about which every rotation 

404 of *cosets* ((R, t) pairs) is a symmetry of the structure, :math:`\{R|\mathbf{c} - 

405 R\mathbf{c}\}` in the class of one of its t: the group is symmorphic 

406 with origin :math:`\mathbf{c}`. Tried on the points of fractional 

407 coordinates n/12 (every Wyckoff position of highest symmetry), the 

408 closest to the origin first. None if there is none (a nonsymmorphic group). 

409 ''' 

410 d = len(a) 

411 grid = np.array(list(itertools.product(np.arange(12) / 12, repeat=d))) @ a 

412 grid = grid[np.argsort(np.linalg.norm(grid, axis=1), kind='stable')] 

413 good = np.ones(len(grid), bool) 

414 rots: dict = {} 

415 for rot, t in cosets: 

416 rots.setdefault(_key(rot), []).append((rot, t)) 

417 for group in rots.values(): 

418 hit = np.zeros(len(grid), bool) 

419 for rot, t in group: 

420 diff = grid - grid @ rot.T - t 

421 f = diff @ np.linalg.inv(a) 

422 hit |= np.all(np.abs(f - np.round(f)) < TOL, axis=1) 

423 good &= hit 

424 return grid[np.argmax(good)] if good.any() else None 

425 

426 

427def _key(rot: NDArray[np.float64]) -> tuple: 

428 ''' 

429 Private function. A hashable key of a rotation matrix. 

430 ''' 

431 return tuple(np.round(rot, 6).ravel() + 0.) 

432 

433 

434def find_symmetries( 

435 ks: KSpace, orbitals: Callable | None = None, antiunitary: bool = True, nk: int = 5, tol: float = 1e-8, 

436) -> list[Operation]: 

437 r''' 

438 Find the space-group operations of a model: the operations of its 

439 Bravais lattice, combined with the translations that map every 

440 position of the unit cell onto one with as many orbitals, that leave :math:`H(\mathbf{k})` 

441 invariant (*KSpace.symmetry_error* below *tol*), as 

442 ``qsymm.symmetries`` does. For a symmorphic structure, every operation 

443 is a rotation about the same point (a site, a bond centre, the centre of 

444 a hexagon...), the one closest to the origin: the form *irreps* needs. 

445 Lattice translations are not listed: the result is one operation per 

446 element of the point group (times time reversal). 

447 

448 Parameters 

449 ---------- 

450 ks : **KSpace** instance, whose lattice fills its space (dim = space_dim) 

451 orbitals : Callable, default None 

452 ``orbitals(R)`` returns the matrix 

453 on the orbitals at one position (without spin) for the rotation 

454 :math:`R`, e.g. ``lambda R: scipy.linalg.block_diag(1., R)`` for an s 

455 and two p orbitals at each site; with ``spin=True``, the 

456 :math:`D` of :class:`Operation` is its Kronecker product with the 

457 spin-1/2 rotation. None: the identity on the orbitals (and the 

458 spin-1/2 rotation if ``spin=True``). 

459 antiunitary : Boolean, default True 

460 Also look for antiunitary 

461 operations (time reversal, alone or times a rotation): with spin, 

462 :math:`D\,i\sigma_y` on every site. 

463 nk : Positive integer, default 5 

464 Points per direction of the test mesh of *symmetry_error*. 

465 tol : Positive real, default 1e-8 

466 

467 Returns 

468 ------- 

469 ops : List of :class:`Operation` 

470 The unitary ones first, each group 

471 in the order of the lattice operations; the identity first. 

472 

473 Examples 

474 -------- 

475 Example usage:: 

476 

477 ops = find_symmetries(graphene) # 24: C6v, and each times time reversal 

478 [op.name for op in ops if not op.antiunitary] 

479 ''' 

480 error_handling.full_dim(ks.dim, ks.space_dim) 

481 error_handling.callable_or_none(orbitals, 'orbitals') 

482 error_handling.boolean(antiunitary, 'antiunitary') 

483 error_handling.positive_int(nk, 'nk') 

484 error_handling.positive_real(tol, 'tol') 

485 a = np.array(ks.lat.prim_vec, dtype='f8') 

486 act = _Action(ks, Operation(np.eye(ks.space_dim))) 

487 rots = _lattice_rotations(a) 

488 rots.sort(key=lambda r: (-round(np.linalg.det(r)), -np.trace(r))) 

489 data = (act.positions, act.tags, a) 

490 cosets = [(rot, t) for rot in rots for t in _structure_translations(data, rot)] 

491 origin = _origin(cosets, a) 

492 unitary, anti = [], [] 

493 for rot, t in cosets: 

494 if origin is not None: 

495 t0 = origin - rot @ origin 

496 t = t0 if _lattice_vector(t - t0, a) else t 

497 orb = None if orbitals is None else np.asarray(orbitals(rot), dtype='c16') 

498 if orb is not None and ks.spin: 

499 orb = np.kron(orb, _su2(rot)) 

500 op = Operation(rot, t, orb) 

501 if ks.symmetry_error(op, nk=nk) < tol: 

502 unitary.append(op) 

503 if antiunitary: 

504 if orb is not None and ks.spin: 

505 orb = orb @ np.kron(np.eye(len(orb) // 2), _I_SIGMA_Y) 

506 op = Operation(rot, t, orb, antiunitary=True) 

507 if ks.symmetry_error(op, nk=nk) < tol: 

508 anti.append(op) 

509 return unitary + anti 

510 

511 

512def _invariant(ks: KSpace, op: Operation, k: NDArray[np.float64]) -> bool: 

513 ''' 

514 Private function. Whether the operation leaves the k-point invariant 

515 (modulo a reciprocal lattice vector). 

516 ''' 

517 gk = _representations(ks, op, k[None])[1][0] 

518 vecs = np.array(ks.lat.prim_vec, dtype='f8') @ ks.k_basis 

519 f = (gk - k) @ vecs.T / (2 * PI) 

520 return bool(np.all(np.abs(f - np.round(f)) < TOL)) 

521 

522 

523# Character tables. Each irrep is a function of an element's descriptor. 

524# 2D: ('rot', theta) with theta the counterclockwise angle, or ('mir', s) 

525# with s = +1 for the class sigma_v (the mirror lines closest to a_1) and 

526# -1 for sigma_d. 

527def _table_2d(n: int, mirrors: bool) -> list[tuple[str, Callable]]: 

528 ''' 

529 Private function. Irreps of the 2D point groups C_n and C_nv. 

530 ''' 

531 def rot(f): 

532 return lambda d: f(d[1]) if d[0] == 'rot' else None 

533 

534 if not mirrors: 

535 table: list[tuple[str, Callable]] = [('A', rot(lambda t: 1.))] 

536 if n % 2 == 0: 

537 table.append(('B', rot(lambda t: np.exp(1j * n * t / 2)))) 

538 orders = [m for m in range(1, (n - 1) // 2 + 1)] 

539 for m in orders: 

540 suffix = str(m) if len(orders) > 1 else '' 

541 table.append(('¹E' + suffix, rot(lambda t, m=m: np.exp(1j * m * t)))) 

542 table.append(('²E' + suffix, rot(lambda t, m=m: np.exp(-1j * m * t)))) 

543 return table 

544 if n == 1: 

545 return [("A'", lambda d: 1.), ("A''", lambda d: 1. if d[0] == 'rot' else -1.)] 

546 

547 def irrep(fr, fm): 

548 return lambda d: fr(d[1]) if d[0] == 'rot' else fm(d[1]) 

549 

550 table = [('A1', irrep(lambda t: 1., lambda s: 1.)), ('A2', irrep(lambda t: 1., lambda s: -1.))] 

551 if n % 2 == 0: 

552 table.append(('B1', irrep(lambda t: np.cos(n * t / 2), lambda s: s))) 

553 table.append(('B2', irrep(lambda t: np.cos(n * t / 2), lambda s: -s))) 

554 orders = [m for m in range(1, (n - 1) // 2 + 1)] 

555 for m in orders: 

556 table.append(('E' + (str(m) if len(orders) > 1 else ''), 

557 irrep(lambda t, m=m: 2 * np.cos(m * t), lambda s: 0.))) 

558 return table 

559 

560 

561# Cubic groups, by the class of the proper part P = det(R) R in O: 

562# E, C3 (8), C2' (6, about face diagonals), C4 (6), C2 (3, about the cube axes) 

563_O_TABLE = {'A1': (1, 1, 1, 1, 1), 'A2': (1, 1, -1, -1, 1), 'E': (2, -1, 0, 0, 2), 

564 'T1': (3, 0, -1, 1, -1), 'T2': (3, 0, 1, -1, -1)} 

565_O_CLASSES = ('E', 'C3', "C2'", 'C4', 'C2') 

566_W = np.exp(2j * PI / 3) 

567# T: E, C3 (+120 degrees about [111], [1-1-1], ...), C3^2, C2 

568_T_TABLE = {'A': (1, 1, 1, 1), '¹E': (1, _W, _W.conjugate(), 1), '²E': (1, _W.conjugate(), _W, 1), 

569 'T': (3, 0, 0, -1)} 

570_T_CLASSES = ('E', 'C3', 'C3^2', 'C2') 

571 

572 

573def _cubic_class(rot: NDArray[np.float64]) -> str | None: 

574 ''' 

575 Private function. The class (in O, or T for 'C3'/'C3^2') of the proper 

576 part of a cubic operation, None if its axis is not a cube axis, face 

577 diagonal or body diagonal of the Cartesian frame. 

578 ''' 

579 angle, axis = _angle_axis(rot) 

580 if angle < TOL: 

581 return 'E' 

582 mags = np.sort(np.round(np.abs(axis) * np.sqrt(3), 6)) 

583 order = int(round(2 * PI / angle)) 

584 if order == 3 and np.allclose(mags, 1.): 

585 return 'C3' if np.prod(np.sign(axis)) > 0 else 'C3^2' 

586 if order in (2, 4) and np.allclose(mags, [0., 0., np.sqrt(3)]): 

587 return 'C4' if order == 4 else 'C2' 

588 if order == 2 and np.allclose(mags, [0., np.sqrt(1.5), np.sqrt(1.5)]): 

589 return "C2'" 

590 return None 

591 

592 

593def _point_group(rots: list[NDArray[np.float64]], a1: NDArray[np.float64]): 

594 ''' 

595 Private function. The name of the point group of the matrices *rots* 

596 and its irreps, as (name, [(label, characters over rots)]), or None if 

597 it is not tabulated (3D groups other than the cubic ones). 

598 ''' 

599 if len(rots[0]) == 2: 

600 dets = [np.linalg.det(r) for r in rots] 

601 n = sum(d > 0 for d in dets) 

602 mirrors = n < len(rots) 

603 lines = [float(np.arctan2(r[1, 0], r[0, 0]) / 2) % PI for r, d in zip(rots, dets) if d < 0] 

604 alpha = float(np.arctan2(a1[1], a1[0])) % PI 

605 dist = [min(abs(phi - alpha) % PI, PI - abs(phi - alpha) % PI) for phi in lines] 

606 phi0 = lines[int(np.argmin(dist))] if mirrors else 0. 

607 desc = [] 

608 for r, d in zip(rots, dets): 

609 if d > 0: 

610 desc.append(('rot', float(np.arctan2(r[1, 0], r[0, 0])))) 

611 else: 

612 phi = float(np.arctan2(r[1, 0], r[0, 0]) / 2) 

613 desc.append(('mir', 1. if int(round((phi - phi0) * n / PI)) % 2 == 0 else -1.)) 

614 name = ('C{}v'.format(n) if n > 1 else 'Cs') if mirrors else 'C{}'.format(n) 

615 return name, [(label, np.array([f(x) for x in desc], dtype='c16')) 

616 for label, f in _table_2d(n, mirrors)] 

617 found = [_cubic_class(r) for r in rots] 

618 det3 = np.array([np.linalg.det(r) for r in rots]) 

619 if None in found or sum(c in ('C3', 'C3^2') for c, d in zip(found, det3) if d > 0) != 8: 

620 return None 

621 classes = [str(c) for c in found] 

622 parity = np.where(det3 > 0, 1., -1.) 

623 proper = bool(np.all(det3 > 0)) 

624 has_inv = any(np.allclose(r, -np.eye(3), atol=TOL) for r in rots) 

625 out = [] 

626 if not any(c in ('C4', "C2'") for c in classes): 

627 name = 'T' if proper else 'Th' 

628 idx = [_T_CLASSES.index(c) for c in classes] 

629 for label, row in _T_TABLE.items(): 

630 chi = np.array([row[i] for i in idx], dtype='c16') 

631 if proper: 

632 out.append((label, chi)) 

633 else: 

634 out += [(label + 'g', chi), (label + 'u', chi * parity)] 

635 return name, out 

636 name = 'O' if proper else ('Oh' if has_inv else 'Td') 

637 idx = [_O_CLASSES.index(c.replace('^2', '')) for c in classes] # C3 and C3^2 are one class in O 

638 for label, row_o in _O_TABLE.items(): 

639 chi = np.array([row_o[i] for i in idx], dtype='c16') 

640 if name == 'Oh': 

641 out += [(label + 'g', chi), (label + 'u', chi * parity)] 

642 else: 

643 out.append((label, chi)) 

644 return name, out 

645 

646 

647class Irreps(): 

648 r''' 

649 The irreducible representations of the bands at a k-point, see *irreps*. 

650 

651 Attributes 

652 ---------- 

653 k : Real ndarray, the k-point 

654 group : String 

655 Point group of the little group (Schoenflies: 'C6v', 'C3v', 'Oh', ...). 

656 operations : List of :class:`Operation` 

657 The little group of *k*. 

658 energies : Real ndarray 

659 Energy of each level (group of degenerate bands). 

660 bands : List of lists of band indices, one per level 

661 labels : List of strings, one per level 

662 The irrep (Mulliken label), or a sum 

663 such as 'A1+B2' for an accidental degeneracy. 

664 characters : Complex ndarray, shape (n_levels, n_operations) 

665 ''' 

666 

667 def __init__(self, k, group, operations, energies, bands, labels, characters) -> None: 

668 self.k = k 

669 self.group = group 

670 self.operations = operations 

671 self.energies = energies 

672 self.bands = bands 

673 self.labels = labels 

674 self.characters = characters 

675 

676 

677def _irreps(ks: KSpace, k: NDArray[np.float64], ops: list[Operation], deg_tol: float) -> Irreps | None: 

678 ''' 

679 Private function. *irreps*, or None if the point group of the little 

680 group is not tabulated. 

681 ''' 

682 little = [op for op in ops if not op.antiunitary and _invariant(ks, op, k)] 

683 rots = [op.rotation for op in little] 

684 a = np.array(ks.lat.prim_vec, dtype='f8') 

685 # symmorphic about a common centre c: t = c - R c for every operation 

686 stack = np.concatenate([np.eye(ks.space_dim) - r for r in rots]) 

687 t = np.concatenate([op.translation for op in little]) 

688 c = np.linalg.lstsq(stack, t, rcond=None)[0] 

689 error_handling.symmorphic(float(np.max(np.abs(stack @ c - t)))) 

690 table = _point_group(rots, a[0]) 

691 if table is None: 

692 return None 

693 name, irreps = table 

694 en, vec = ks._eigs(k[None], eigenvec=True) 

695 en, vec = en[0].real, vec[0] 

696 us = np.array([_representations(ks, op, k[None])[0][0] for op in little]) 

697 levels = np.split(np.arange(ks.norb), np.flatnonzero(np.diff(en) > deg_tol) + 1) 

698 chars = np.array([np.einsum('ia,gij,ja->g', vec[:, lv].conj(), us, vec[:, lv]) for lv in levels]) 

699 chi = np.array([c for _, c in irreps]) 

700 mult = (chi.conj() @ chars.T).T / len(little) 

701 error_handling.multiplicities(mult) 

702 labels = [] 

703 for row in np.round(mult.real).astype(int): 

704 labels.append('+'.join(('{}'.format(m) if m > 1 else '') + label 

705 for (label, _), m in zip(irreps, row) if m)) 

706 return Irreps(k, name, little, np.array([en[lv].mean() for lv in levels]), 

707 [lv.tolist() for lv in levels], labels, chars) 

708 

709 

710def irreps( 

711 ks: KSpace, k: ArrayLike, ops: list[Operation] | None = None, deg_tol: float = 1e-6, 

712) -> Irreps: 

713 r''' 

714 Get the irreducible representations of the bands at a k-point 

715 (Bouckaert, Smoluchowski and Wigner, Phys. Rev. 50, 58 (1936)): the 

716 little group of :math:`\mathbf{k}` (the unitary operations with 

717 :math:`g\mathbf{k} = \mathbf{k}` modulo a reciprocal lattice vector), 

718 the characters :math:`\chi(g) = \mathrm{Tr}\,V^\dagger U_g(\mathbf{k})V` 

719 on each level :math:`V` (degenerate bands within *deg_tol*), and their 

720 decomposition on the character table of the point group. 

721 

722 Tabulated: the ten 2D point groups (C1, C2, C3, C4, C6, Cs, C2v, C3v, 

723 C4v, C6v) and the five cubic ones (T, Th, O, Td, Oh, with the cube 

724 axes along x, y, z); spinless models; symmorphic little groups (every 

725 operation a rotation about one point, see *Operation*). Conventions: in 

726 C4v and C6v (and C2v), :math:`\sigma_v` is the class of the mirror 

727 lines closest to :math:`\mathbf{a}_1` (B1 is even under it); the 

728 complex pairs of the cyclic groups are ¹E (:math:`\chi(C_n) = 

729 e^{2\pi i/n}`, :math:`C_n` counterclockwise) and ²E; in T, :math:`C_3` 

730 is the counterclockwise rotation about [111]. 

731 

732 Parameters 

733 ---------- 

734 ks : **KSpace** instance, spinless, Hermitian, 2D or 3D (dim = space_dim) 

735 k : k-point (coordinates of *get_ham*) 

736 ops : List of :class:`Operation`, default None (*find_symmetries*) 

737 deg_tol : Positive real, default 1e-6 

738 Energies closer than this are one level. 

739 

740 Returns 

741 ------- 

742 result : :class:`Irreps` 

743 

744 Examples 

745 -------- 

746 Example usage:: 

747 

748 res = irreps(graphene, K) 

749 res.group, res.labels # 'C3v', ['E'] (the Dirac point) 

750 ''' 

751 error_handling.spinless_irreps(ks.spin) 

752 error_handling.full_dim(ks.dim, ks.space_dim) 

753 error_handling.dim_irreps(ks.dim) 

754 error_handling.hermitian_model(ks.is_hermitian()) 

755 error_handling.no_overlap(ks._overlap_hop) 

756 error_handling.k_vector(k, 'k', ks.dim) 

757 error_handling.positive_real(deg_tol, 'deg_tol') 

758 ops = find_symmetries(ks, antiunitary=False) if ops is None else ops 

759 error_handling.operations(ops) 

760 res = _irreps(ks, np.array(k, dtype='f8'), ops, deg_tol) 

761 error_handling.tabulated(res) 

762 assert res is not None 

763 return res 

764 

765 

766def _rotation_data(ks: KSpace, op: Operation, bands: list[int]) -> tuple[int, float, list, Callable]: 

767 r''' 

768 Private function. For a rotation :math:`C_n` of a 2D model: :math:`n`, 

769 the signed angle, the points with a nontrivial stabilizer, one per 

770 orbit, as (k, s) with :math:`C_n^s` the rotation that keeps k, and the 

771 function ``eig(s, k)``: the eigenvalues of :math:`C_n^s` on *bands* at k. 

772 ''' 

773 error_handling.dim_exact(ks.dim, 2) 

774 error_handling.full_dim(ks.dim, ks.space_dim) 

775 error_handling.is_operation(op) 

776 error_handling.proper_rotation(op) 

777 error_handling.band_indices(bands, ks.norb) 

778 error_handling.is_symmetry(ks.symmetry_error(op), 1e-8) 

779 theta = float(np.arctan2(op.rotation[1, 0], op.rotation[0, 0])) 

780 n = int(round(2 * PI / abs(theta))) 

781 rec = ks.rec_vec_k 

782 

783 def eig(power, k): 

784 v = ks._subspaces(k[None], bands)[0] 

785 u = _representations(ks, op ** power, k[None])[0][0] 

786 m = v.conj().T @ u @ v 

787 error_handling.invariant_bands(np.linalg.svd(m, compute_uv=False)) 

788 return np.linalg.eigvals(m) 

789 

790 def reduced(k): 

791 f = np.linalg.solve(rec.T, k) 

792 return (f - np.floor(f + TOL)) @ rec 

793 

794 seen: list = [] 

795 points = [] 

796 for k in np.array(list(itertools.product(np.arange(6) / 6, repeat=2))) @ rec: 

797 if any(np.allclose(k, p, atol=TOL) for p in seen): 

798 continue 

799 orbit = [k] 

800 while True: 

801 nxt = reduced(_representations(ks, op, orbit[-1][None])[1][0]) 

802 if np.allclose(nxt, k, atol=TOL): 

803 break 

804 orbit.append(nxt) 

805 seen += orbit 

806 if len(orbit) < n: 

807 points.append((k, len(orbit))) 

808 return n, theta, points, eig 

809 

810 

811def rotation_indicator(ks: KSpace, op: Operation, bands: list[int]) -> int: 

812 r''' 

813 Get the Chern number modulo :math:`n` of a group of bands of a 

814 :math:`C_n`-symmetric 2D model from its rotation eigenvalues (Fang, 

815 Gilbert and Bernevig, Phys. Rev. B 86, 115112 (2012)): 

816 

817 .. math:: 

818 

819 e^{2\pi i C/n} = (-1)^{FN}\prod_{\mathbf{k}_*}\ \prod_{m \in \mathrm{bands}} 

820 \lambda_m\big(\mathbf{k}_*, C_n^{s}\big)\, , 

821 

822 over one point :math:`\mathbf{k}_*` of each orbit of the points left 

823 invariant by some power of :math:`C_n` (:math:`s` the length of the 

824 orbit, :math:`C_n^s` the rotation that keeps it): :math:`\Gamma` and 

825 M, and X for :math:`C_4`; :math:`\Gamma`, K and K' for :math:`C_3`; 

826 :math:`\Gamma`, K and M for :math:`C_6`; the four time-reversal 

827 invariant momenta for :math:`C_2`. When :math:`U_{C_n}^n = -1` (spin 

828 1/2), the eigenvalues are those of :math:`e^{i\pi/n}C_n`, whose 

829 :math:`n`-th power is 1: this gives the factor :math:`(-1)^{FN} = 

830 (-1)^N`, :math:`N` = len(*bands*), for :math:`C_3`, :math:`C_4` and 

831 :math:`C_6`, and 1 for :math:`C_2`. No integral over the zone: only the 

832 eigenvalues at a few points. 

833 

834 Parameters 

835 ---------- 

836 ks : **KSpace** instance, 2D (dim = space_dim) 

837 op : :class:`Operation` 

838 A rotation :math:`C_n` (n = 2, 3, 4 or 6), 

839 unitary, a symmetry of the model, about its centre (see *Operation*). 

840 Its sense sets the sign: :math:`C` is that of *chern_number* for a 

841 counterclockwise rotation. 

842 bands : List of band indices (isolated from the others at the invariant points) 

843 

844 Returns 

845 ------- 

846 c : Integer, :math:`C \bmod n`, in [0, n) 

847 ''' 

848 n, theta, points, eig = _rotation_data(ks, op, bands) 

849 u_n = _representations(ks, op ** n, np.zeros((1, 2)))[0][0] 

850 # with U^n = -1 (spin 1/2), e^(i pi/n) U is a rotation with U^n = +1 

851 shift = 0. if error_handling.rotation_power(u_n) == 1 else np.sign(theta) * PI / n 

852 product = 1. + 0j 

853 for k, s in points: 

854 product *= complex(np.prod(np.exp(1j * shift * s) * eig(s, k))) 

855 x = float(np.angle(product)) / theta 

856 error_handling.quantized(x, 'rotation eigenvalues') 

857 return int(round(x)) % n 

858 

859 

860def inversion_indicators(ks: KSpace, op: Operation, bands: list[int]) -> tuple[int, int, int, int]: 

861 r''' 

862 Get the symmetry indicators of a 3D inversion- and time-reversal 

863 symmetric insulator (Khalaf, Po, Vishwanath and Watanabe, Phys. Rev. X 

864 8, 031070 (2018)) from the numbers :math:`n^\pm_{\mathbf{K}}` of 

865 occupied states of parity :math:`\pm1` at the eight time-reversal 

866 invariant momenta :math:`\mathbf{K}`: 

867 

868 .. math:: 

869 

870 z_4 = \sum_{\mathbf{K}} \frac{n^+_{\mathbf{K}} - n^-_{\mathbf{K}}}{4} \bmod 4\, ,\qquad 

871 z_{2,i} = \sum_{K_i = 1/2} \frac{n^+_{\mathbf{K}} - n^-_{\mathbf{K}}}{4} \bmod 2\, , 

872 

873 :math:`K_i` the fractional coordinate along :math:`\mathbf{b}_i`. 

874 :math:`z_4 \bmod 2` is the strong :math:`\mathbb{Z}_2` index 

875 :math:`\nu_0` and :math:`z_{2,i}` the weak ones :math:`\nu_i` (Fu and 

876 Kane 2007, see *z2_indices_3d*); :math:`z_4 = 2` (with 

877 :math:`\nu_0 = 0`) is an insulator that :math:`\mathbb{Z}_2` misses: a 

878 doubled strong topological insulator, with hinge states. 

879 

880 Parameters 

881 ---------- 

882 ks : **KSpace** instance, 3D 

883 op : :class:`Operation` 

884 The inversion (rotation :math:`-1`), unitary, a 

885 symmetry of the model, about its centre. 

886 bands : List of band indices (an even number: Kramers pairs) 

887 

888 Returns 

889 ------- 

890 indicators : Tuple of four integers :math:`(z_4, z_{2,1}, z_{2,2}, z_{2,3})` 

891 ''' 

892 error_handling.dim_exact(ks.dim, 3) 

893 error_handling.is_operation(op) 

894 error_handling.inversion_operation(op) 

895 error_handling.even_bands(bands) 

896 error_handling.band_indices(bands, ks.norb) 

897 error_handling.is_symmetry(ks.symmetry_error(op), 1e-8) 

898 fracs = np.array(list(itertools.product((0., 0.5), repeat=3))) 

899 ks_trim = fracs @ ks.rec_vec_k 

900 v = ks._subspaces(ks_trim, bands) 

901 u = _representations(ks, op, ks_trim)[0] 

902 diff = np.zeros(8) 

903 for p in range(8): 

904 xi = np.linalg.eigvals(v[p].conj().T @ u[p] @ v[p]) 

905 error_handling.parities(xi) 

906 diff[p] = np.sum(xi.real > 0) - np.sum(xi.real < 0) 

907 z4 = int(round(diff.sum() / 4)) % 4 

908 weak = [int(round(diff[fracs[:, i] == 0.5].sum() / 4)) % 2 for i in range(3)] 

909 return z4, weak[0], weak[1], weak[2] 

910 

911 

912def corner_charge(ks: KSpace, op: Operation, bands: list[int]) -> float: 

913 r''' 

914 Get the corner charge of a :math:`C_4`-symmetric 2D insulator from its 

915 rotation eigenvalues (Benalcazar, Li and Hughes, Phys. Rev. B 99, 

916 245151 (2019)): 

917 

918 .. math:: 

919 

920 Q^{(4)} = \tfrac{1}{4}\left([X_1^{(2)}] + 2[M_1^{(4)}] + 3[M_2^{(4)}]\right) \bmod 1\, , 

921 

922 :math:`[\Pi_p^{(m)}] = \#\Pi_p^{(m)} - \#\Gamma_p^{(m)}` the number of 

923 bands of eigenvalue :math:`e^{2\pi i(p-1)/m}` of the rotation 

924 :math:`C_m` that keeps :math:`\Pi` (:math:`C_4^2` at 

925 X :math:`= \mathbf{b}_1/2`, :math:`C_4` at M :math:`= 

926 (\mathbf{b}_1+\mathbf{b}_2)/2`), minus that at :math:`\Gamma`. It is 

927 the excess number of electrons (charge in units of :math:`-e`, as 

928 *higher_order.corner_charges*) in a quadrant of a square flake of whole 

929 unit cells, with *bands* filled in the bulk (and the edge states below 

930 the bulk gap) on an ionic background of len(*bands*) electrons per 

931 cell. The flake is built from the unit cell, so the rotation must be 

932 about its centre: it maps the orbitals of the unit cell onto 

933 themselves. The formula assumes a spinless model with time reversal. 

934 

935 (The :math:`C_2` formula of the same paper needs a vanishing 

936 polarization, and was not reproduced here by flakes: it is left out.) 

937 

938 Parameters 

939 ---------- 

940 ks : **KSpace** instance, 2D, spinless 

941 op : :class:`Operation` 

942 A rotation :math:`C_4` about the centre of the 

943 unit cell, unitary, a symmetry of the model. 

944 bands : List of band indices (the occupied bands) 

945 

946 Returns 

947 ------- 

948 q : Real number in [0, 1), a multiple of 1/4 

949 ''' 

950 error_handling.spinless_irreps(ks.spin) 

951 n, theta, _, eig = _rotation_data(ks, op, bands) 

952 error_handling.corner_rotation(n) 

953 error_handling.cell_rotation(_Action(ks, op).L) 

954 b1, b2 = ks.rec_vec_k 

955 gamma = np.zeros(2) 

956 

957 def count(k, s, p): 

958 '''[Pi_p] at k, whose stabilizer C_(n/s) is generated by g^s''' 

959 target = np.exp(1j * np.sign(theta) * 2 * PI * (p - 1) * s / n) 

960 return int(np.sum(np.abs(eig(s, k) - target) < 1e-4)) - int(np.sum(np.abs(eig(s, gamma) - target) < 1e-4)) 

961 

962 m = (b1 + b2) / 2 

963 q = (count(b1 / 2, 2, 1) + 2 * count(m, 1, 1) + 3 * count(m, 1, 2)) / 4 

964 return float(q % 1.) 

965 

966 

967def _closure(ks: KSpace, ops: list[Operation]) -> list[Operation]: 

968 ''' 

969 Private function. The group generated by *ops* (modulo lattice 

970 translations, and the phase of the orbital matrices). 

971 ''' 

972 a = np.array(ks.lat.prim_vec, dtype='f8') 

973 m = None if ops[0].orbitals is None else len(ops[0].orbitals) 

974 group = [Operation(np.eye(ks.space_dim), orbitals=None if m is None else np.eye(m))] 

975 

976 def same(g, h): 

977 if g.antiunitary != h.antiunitary or not np.allclose(g.rotation, h.rotation, atol=TOL): 

978 return False 

979 if not _lattice_vector(g.translation - h.translation, a): 

980 return False 

981 if g.orbitals is None: 

982 return True 

983 overlap = np.trace(g.orbitals.conj().T @ h.orbitals) / len(g.orbitals) 

984 return bool(np.allclose(h.orbitals, overlap * g.orbitals, atol=TOL)) 

985 

986 todo = list(ops) 

987 while todo: 

988 g = todo.pop() 

989 if any(same(g, h) for h in group): 

990 continue 

991 group.append(g) 

992 error_handling.group_size(len(group)) 

993 todo += [g @ h for h in group] + [h @ g for h in group] 

994 return group 

995 

996 

997def symmetrize(ks: KSpace, ops: list[Operation]) -> KSpace: 

998 r''' 

999 Symmetrize a model: the group average of its hoppings, 

1000 

1001 .. math:: 

1002 

1003 H_{\mathrm{sym}} = \frac{1}{|G|}\sum_{g\in G} g\,H\,g^{-1},\qquad 

1004 (gHg^{-1})_{\pi(a)\pi(b)}(R\mathbf{R} + \mathbf{L}_b - \mathbf{L}_a) = 

1005 D\,H_{ab}(\mathbf{R})\,D^\dagger 

1006 

1007 (D\,H_{ab}(\mathbf{R})^*D^\dagger \text{ if } g \text{ is antiunitary}), 

1008 

1009 over the group :math:`G` generated by *ops*, as 

1010 ``TBmodels.Model.symmetrize``. A model read from Wannier90, whose 

1011 symmetries are broken by numerical noise, gets them back exactly: its 

1012 degeneracies become exact, and *symmetry_error* zero. A symmetric model 

1013 is unchanged; the result is the projection of the hoppings onto the 

1014 symmetric ones (closest in the Frobenius norm). 

1015 

1016 Parameters 

1017 ---------- 

1018 ks : **KSpace** instance, without overlap 

1019 Value functions are evaluated with *params*. 

1020 ops : List of :class:`Operation`, the generators 

1021 

1022 Returns 

1023 ------- 

1024 ks_sym : **KSpace** instance, on the same lattice 

1025 ''' 

1026 error_handling.no_overlap(ks._overlap_hop) 

1027 error_handling.operations(ops) 

1028 group = _closure(ks, ops) 

1029 a = np.array(ks.lat.prim_vec, dtype='f8') 

1030 pinv = np.linalg.pinv(a) 

1031 # H(R) as a dictionary {integer R: (norb, norb) matrix} 

1032 hams: dict = {(0,) * ks.dim: np.diag(ks.onsite) + ks._onsite_offdiag} 

1033 for i, j, R, t in ks._hop: 

1034 key = tuple(int(x) for x in np.round(np.asarray(R) @ pinv)) 

1035 hams.setdefault(key, np.zeros((ks.norb, ks.norb), dtype='c16'))[i, j] += t 

1036 out: dict = {} 

1037 for g in group: 

1038 act = _Action(ks, g) 

1039 m = np.round(a @ g.rotation.T @ pinv) # integer rotation: R (n @ a) = (n @ m) @ a 

1040 for key, h in hams.items(): 

1041 h = h.conj() if g.antiunitary else h 

1042 for s, s_img in enumerate(act.perm): 

1043 for s2, s2_img in enumerate(act.perm): 

1044 new = tuple(int(x) for x in np.array(key) @ m + act.L[s2] - act.L[s]) 

1045 blk = act.D[s] @ h[np.ix_(act.idx[s], act.idx[s2])] @ act.D[s2].conj().T 

1046 mat = out.setdefault(new, np.zeros((ks.norb, ks.norb), dtype='c16')) 

1047 mat[np.ix_(act.idx[s_img], act.idx[s2_img])] += blk / len(group) 

1048 new_ks = KSpace(ks.lat, spin=ks.spin) 

1049 new_ks._nonreciprocal = ks._nonreciprocal 

1050 hops = [] 

1051 for key, mat in out.items(): 

1052 R_cart = np.array(key, dtype='f8') @ a 

1053 if not any(key): 

1054 new_ks.onsite = np.diag(mat).copy() 

1055 mat = mat - np.diag(np.diag(mat)) 

1056 for i, j in zip(*np.nonzero(np.abs(mat) > 1e-14)): 

1057 hops.append((int(i), int(j), R_cart, complex(mat[i, j]))) 

1058 new_ks._hop = hops 

1059 return new_ks