Coverage for tbkit/io.py: 100%

312 statements  

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

1r''' 

2Save and load models, and import models from other codes. 

3 

4*save_model* / *load_model* store a **Lattice**, **System** or **KSpace** 

5in a versioned NumPy ``.npz`` archive (no pickle, readable with NumPy 

6alone): the lattice (*unit_cell*, *prim_vec*, and the sites of 

7*get_lattice* if any), and for a System its onsite energies and hopping 

8array *sys.hop*, for a KSpace its onsite terms (with the spin-off-diagonal 

9block), hoppings, overlaps and *spin*. Every number is stored in binary, 

10so a loaded model reproduces the Hamiltonians exactly. 

11 

12Archive layout (format ``'tbkit-model'``, version :data:`VERSION`): 

13 

14* ``format``, ``version``, ``kind`` (``'Lattice'``, ``'System'`` or 

15 ``'KSpace'``), ``tbkit_version``; 

16* ``uc_tag`` (n_sites,), ``uc_r0`` (n_sites, space_dim), ``prim_vec`` 

17 (dim, space_dim), ``coor`` (the structured site array), ``n_cells`` (3,); 

18* System: ``onsite`` (sites,), ``hop`` (the structured *sys.hop*), and, 

19 from version 2, ``periodic`` (one boolean per primitive vector) for a 

20 System with periodic boundaries (every other model is still written as 

21 version 1, which older tbkit versions read); 

22* KSpace: ``spin``, ``onsite`` (norb,), ``onsite_offdiag`` (norb, norb), 

23 ``nonreciprocal``, and ``hop_i``, ``hop_j``, ``hop_R`` (Cartesian 

24 lattice vectors), ``hop_t`` for the hoppings, ``ovl_i``, ``ovl_j``, 

25 ``ovl_R``, ``ovl_t`` for the overlaps. 

26 

27A KSpace read from a Wannier90 ``_tb.dat`` file also stores its position 

28matrix elements: ``pos_i``, ``pos_j``, ``pos_R``, ``pos_r`` (the vectors 

29:math:`\langle i\mathbf{0}|\mathbf{r}|j\mathbf{R}\rangle`, complex, shape 

30(n, space_dim)). Versions of tbkit before 0.9 ignore them. 

31 

32Wannier90 (`wannier.org <https://wannier.org>`_): 

33 

34* *read_wannier90* imports a tight-binding model from Wannier90's 

35 ``seedname_hr.dat``, *read_wannier90_tb* from ``seedname_tb.dat``, with 

36 the matrix elements of the position operator (see there). 

37* *write_wannier90* writes a **KSpace** as ``seedname_hr.dat``, 

38 ``seedname_tb.dat``, ``seedname.win`` and ``seedname_centres.xyz`` 

39 (*write_hr*, *write_tb*). 

40 

41Other codes (ASE, PythTB, TBmodels, Z2Pack, qsymm, pybinding, Kwant): see 

42*tbkit.interop*. 

43''' 

44from __future__ import annotations 

45 

46import os 

47import time 

48from typing import Any, cast 

49 

50import numpy as np 

51from numpy.typing import ArrayLike, NDArray 

52 

53import tbkit 

54import tbkit.error_handling as error_handling 

55from tbkit.kspace import KSpace 

56from tbkit.lattice import Lattice 

57from tbkit.orbital import OrbitalSystem 

58from tbkit.system import System, HOP_DTYPE 

59 

60 

61#: Name of the archive format written by *save_model*. 

62FORMAT = 'tbkit-model' 

63#: Version of the archive format written by *save_model*; *load_model* 

64#: reads this version and every earlier one. 

65VERSION = 2 

66 

67 

68def _hop_arrays(hops: list, space_dim: int, prefix: str) -> dict: 

69 ''' 

70 Private function. A KSpace hopping list (i, j, R_cart, t) as arrays. 

71 ''' 

72 return {prefix + '_i': np.array([h[0] for h in hops], dtype='i8'), 

73 prefix + '_j': np.array([h[1] for h in hops], dtype='i8'), 

74 prefix + '_R': np.array([h[2] for h in hops], dtype='f8').reshape(len(hops), space_dim), 

75 prefix + '_t': np.array([h[3] for h in hops], dtype='c16')} 

76 

77 

78def _hop_list(data, prefix: str) -> list: 

79 ''' 

80 Private function. Inverse of *_hop_arrays*. 

81 ''' 

82 return [(int(i), int(j), R.copy(), complex(t)) 

83 for i, j, R, t in zip(data[prefix + '_i'], data[prefix + '_j'], 

84 data[prefix + '_R'], data[prefix + '_t'])] 

85 

86 

87def save_model(model: Lattice | System | KSpace, path: str | os.PathLike) -> str: 

88 ''' 

89 Save a **Lattice**, **System** or **KSpace** to a ``.npz`` archive (see 

90 the module docstring for its layout). Subclasses are saved as their 

91 base class (e.g. a *GrapheneSystem* as a *System*); an *OrbitalSystem* 

92 or a driven (Floquet) model cannot be saved. 

93 

94 Parameters 

95 ---------- 

96 model : **Lattice**, **System** or **KSpace** instance 

97 path : String or path 

98 File name; ``.npz`` is appended if missing. 

99 

100 Returns 

101 ------- 

102 path : String 

103 The file written. 

104 

105 Examples 

106 -------- 

107 Example usage:: 

108 

109 save_model(gra, 'graphene.npz') 

110 gra2 = load_model('graphene.npz') 

111 ''' 

112 error_handling.saveable_model(model, Lattice, System, KSpace, OrbitalSystem) 

113 error_handling.no_value_functions(model, 'save_model') 

114 error_handling.file_path(path, 'path') 

115 path = os.fspath(path) 

116 if not path.endswith('.npz'): 

117 path += '.npz' 

118 lat = model.lat if isinstance(model, (System, KSpace)) else model 

119 kind = 'System' if isinstance(model, System) else 'KSpace' if isinstance(model, KSpace) else 'Lattice' 

120 # only what needs version 2 (a periodic System) is written as such, so 

121 # that older tbkit versions keep reading everything else 

122 data: dict[str, Any] = {'format': np.array(FORMAT), 'version': np.array(1), 'kind': np.array(kind), 

123 'tbkit_version': np.array(tbkit.__version__), 

124 'uc_tag': np.array([dic['tag'] for dic in lat.unit_cell], dtype=str), 

125 'uc_r0': np.array([dic['r0'] for dic in lat.unit_cell], dtype='f8'), 

126 'prim_vec': np.array(lat.prim_vec, dtype='f8'), 

127 'coor': lat.coor, 

128 'n_cells': np.array([lat.n1, lat.n2, lat.n3], dtype='i8')} 

129 if isinstance(model, System): 

130 data['onsite'] = np.asarray(model.onsite, dtype='c16') 

131 data['hop'] = model.hop 

132 if any(model.periodic): 

133 data['periodic'] = np.array(model.periodic, dtype=bool) 

134 data['version'] = np.array(VERSION) 

135 elif isinstance(model, KSpace): 

136 data.update({'spin': np.array(model.spin), 'onsite': model.onsite, 

137 'onsite_offdiag': model._onsite_offdiag, 

138 'nonreciprocal': np.array(model._nonreciprocal)}) 

139 data.update(_hop_arrays(model._hop, model.space_dim, 'hop')) 

140 data.update(_hop_arrays(model._overlap_hop, model.space_dim, 'ovl')) 

141 if model._position_hop: 

142 elements = model._position_hop 

143 data['pos_i'] = np.array([e[0] for e in elements], dtype='i8') 

144 data['pos_j'] = np.array([e[1] for e in elements], dtype='i8') 

145 data['pos_R'] = np.array([e[2] for e in elements], dtype='f8') 

146 data['pos_r'] = np.array([e[3] for e in elements], dtype='c16') 

147 np.savez(path, **data) 

148 return path 

149 

150 

151def load_model(path: str | os.PathLike) -> Lattice | System | KSpace: 

152 ''' 

153 Load a model saved by *save_model*. 

154 

155 Parameters 

156 ---------- 

157 path : String or path 

158 File name. 

159 

160 Returns 

161 ------- 

162 model 

163 **Lattice**, **System** or **KSpace** instance, whose 

164 Hamiltonians (*get_ham*) are exactly those of the saved model. 

165 ''' 

166 error_handling.file_path(path, 'path') 

167 with np.load(path, allow_pickle=False) as data: 

168 error_handling.model_archive(data, FORMAT, VERSION) 

169 unit_cell = [{'tag': str(tag), 'r0': tuple(float(c) for c in r0)} 

170 for tag, r0 in zip(data['uc_tag'], data['uc_r0'])] 

171 prim_vec = [tuple(float(c) for c in a) for a in data['prim_vec']] 

172 lat = Lattice(unit_cell=unit_cell, prim_vec=prim_vec) 

173 lat.coor = data['coor'].astype(lat.dtype) 

174 lat.sites = len(lat.coor) 

175 lat.n1, lat.n2, lat.n3 = (int(n) for n in data['n_cells']) 

176 if lat.sites: 

177 lat.tags = np.unique(np.concatenate([lat.tags, lat.coor['tag']])) 

178 kind = str(data['kind']) 

179 if kind == 'Lattice': 

180 return lat 

181 if kind == 'System': 

182 periodic = tuple(bool(p) for p in data['periodic']) if 'periodic' in data.files else False 

183 sys = System(lat, periodic=periodic) 

184 sys.onsite = data['onsite'].copy() 

185 sys.hop = data['hop'].astype(HOP_DTYPE) # archives before 0.8 have a 'U2' tag 

186 return sys 

187 ks = KSpace(lat, spin=bool(data['spin'])) 

188 ks.onsite = data['onsite'].copy() 

189 ks._onsite_offdiag = data['onsite_offdiag'].copy() 

190 ks._nonreciprocal = bool(data['nonreciprocal']) 

191 ks._hop = _hop_list(data, 'hop') 

192 ks._overlap_hop = _hop_list(data, 'ovl') 

193 if 'pos_r' in data.files: 

194 ks._position_hop = [(int(i), int(j), R.copy(), r.copy()) for i, j, R, r in 

195 zip(data['pos_i'], data['pos_j'], data['pos_R'], data['pos_r'])] 

196 return ks 

197 

198 

199################################# 

200# WANNIER90 

201################################# 

202 

203#: Bohr radius in Angstrom (CODATA 2018), for ``unit_cell_cart`` given in bohr. 

204BOHR = 0.529177210903 

205 

206 

207def read_hr(path: str | os.PathLike) -> tuple[int, NDArray[np.int64], NDArray[np.int64], NDArray[np.complex128]]: 

208 r''' 

209 Read a Wannier90 ``seedname_hr.dat`` file: a header line, the number of 

210 Wannier functions, the number of lattice vectors :math:`\mathbf{R}`, 

211 their degeneracy weights (15 per line), then one line 

212 ``R1 R2 R3 m n Re Im`` per matrix element 

213 :math:`H_{mn}(\mathbf{R}) = \langle m\mathbf{0}|H|n\mathbf{R}\rangle` 

214 (m, n counted from 1). 

215 

216 Parameters 

217 ---------- 

218 path : String or path 

219 The ``_hr.dat`` file. 

220 

221 Returns 

222 ------- 

223 num_wann : Integer 

224 Number of Wannier functions. 

225 R : Integer ndarray, shape (nrpts, 3) 

226 Lattice vectors (in 

227 units of the primitive vectors). 

228 ndegen : Integer ndarray, shape (nrpts,) 

229 Degeneracy weights. 

230 ham : Complex ndarray, shape (nrpts, num_wann, num_wann) 

231 :math:`H_{mn}(\mathbf{R})` as written in the file (not divided by 

232 the weights). 

233 ''' 

234 error_handling.file_path(path, 'path') 

235 with open(path) as f: 

236 lines = f.read().splitlines()[1:] # the first line is a free comment 

237 tokens = ' '.join(lines).split() 

238 error_handling.hr_header(tokens) 

239 num_wann, nrpts = int(tokens[0]), int(tokens[1]) 

240 ndegen = np.array(tokens[2:2 + nrpts], dtype='i8') 

241 body = tokens[2 + nrpts:] 

242 error_handling.hr_body(len(body), nrpts, num_wann) 

243 rows = np.array(body, dtype='f8').reshape(nrpts * num_wann ** 2, 7) 

244 R = rows[::num_wann ** 2, :3].astype('i8') 

245 block = np.repeat(np.arange(nrpts), num_wann ** 2) 

246 error_handling.hr_blocks(np.array_equal(rows[:, :3].astype('i8'), R[block])) 

247 m, n = rows[:, 3].astype('i8') - 1, rows[:, 4].astype('i8') - 1 

248 ham = np.zeros((nrpts, num_wann, num_wann), 'c16') 

249 ham[block, m, n] = rows[:, 5] + 1j * rows[:, 6] 

250 return num_wann, R, ndegen, ham 

251 

252 

253def read_win_cell(path: str | os.PathLike) -> NDArray[np.float64]: 

254 r''' 

255 Read the lattice vectors of a Wannier90 ``seedname.win`` file (block 

256 ``unit_cell_cart``, in Angstrom, or in bohr if its first line says 

257 ``bohr``). Comments (``!``, ``#``) are ignored. 

258 

259 Parameters 

260 ---------- 

261 path : String or path 

262 The ``.win`` file. 

263 

264 Returns 

265 ------- 

266 cell : Real ndarray, shape (3, 3) 

267 The rows are 

268 :math:`\mathbf{a}_1, \mathbf{a}_2, \mathbf{a}_3`, in Angstrom. 

269 ''' 

270 error_handling.file_path(path, 'path') 

271 with open(path) as f: 

272 lines = [line.split('!')[0].split('#')[0].strip() for line in f] 

273 lines = [line for line in lines if line] 

274 low = [line.lower().replace(' ', '') for line in lines] 

275 error_handling.win_block('beginunit_cell_cart' in low and 'endunit_cell_cart' in low) 

276 block = lines[low.index('beginunit_cell_cart') + 1:low.index('endunit_cell_cart')] 

277 scale = 1. 

278 if block and block[0].lower() in ('bohr', 'ang'): 

279 scale = BOHR if block[0].lower() == 'bohr' else 1. 

280 block = block[1:] 

281 cell = [line.split() for line in block] 

282 error_handling.win_cell(cell) 

283 return scale * np.array(cell, dtype='f8') 

284 

285 

286def read_centres(path: str | os.PathLike, num_wann: int) -> NDArray[np.float64]: 

287 ''' 

288 Read the Wannier centres of a Wannier90 ``seedname_centres.xyz`` file 

289 (the first *num_wann* atoms labelled ``X``, in Angstrom). 

290 

291 Parameters 

292 ---------- 

293 path : String or path 

294 The ``_centres.xyz`` file. 

295 num_wann : Positive integer 

296 Number of Wannier functions. 

297 

298 Returns 

299 ------- 

300 centres : Real ndarray, shape (num_wann, 3) 

301 ''' 

302 error_handling.file_path(path, 'path') 

303 error_handling.positive_int(num_wann, 'num_wann') 

304 with open(path) as f: 

305 lines = f.read().splitlines()[2:] # atom count and comment 

306 xs = [line.split()[1:4] for line in lines if line.split() and line.split()[0] == 'X'] 

307 error_handling.centres_count(len(xs), num_wann) 

308 return np.array(xs[:num_wann], dtype='f8') 

309 

310 

311def read_wannier90( 

312 hr: str | os.PathLike, 

313 prim_vec: list[tuple[float, ...]] | None = None, 

314 win: str | os.PathLike | None = None, 

315 centres: str | os.PathLike | None = None, 

316 positions: ArrayLike | None = None, 

317 tags: list[str] | None = None, 

318 dim: int = 3, 

319 cutoff: float = 0., 

320 tol: float = 1e-6, 

321) -> KSpace: 

322 r''' 

323 Import a tight-binding model from Wannier90's ``seedname_hr.dat``, 

324 the Hamiltonian in a basis of (maximally localized) Wannier functions: 

325 

326 .. math:: 

327 

328 H_{mn}(\mathbf{k}) = \sum_{\mathbf{R}} \frac{H_{mn}(\mathbf{R})}{N_{\mathbf{R}}}\, 

329 e^{i\mathbf{k}\cdot\mathbf{R}}\, , 

330 

331 :math:`N_{\mathbf{R}}` being the degeneracy weight of :math:`\mathbf{R}` 

332 (lattice vectors on the boundary of the Wigner-Seitz supercell appear 

333 several times). The Wannier functions become the orbitals of a 

334 **KSpace**, in the file's order: :math:`H_{mm}(\mathbf{0})` the onsite 

335 energies, the other elements the hoppings 

336 :math:`t_{mn}(\mathbf{R})` of *KSpace.set_hopping*. If the file is 

337 Hermitian (within *tol*), one element of each conjugate pair is kept 

338 and the model is Hermitian (with real onsite energies); otherwise every 

339 element is kept, with ``hermitian=False``. 

340 

341 Parameters 

342 ---------- 

343 hr : String or path 

344 The ``seedname_hr.dat`` file. 

345 prim_vec : List of *dim* tuples of *dim* real numbers 

346 Default 

347 value None. Primitive vectors, in the units of the positions 

348 (Angstrom for Wannier90). If None, read from *win*. 

349 win : String or path, default None 

350 The ``seedname.win`` 

351 file, for its ``unit_cell_cart`` block (if *prim_vec* is None). 

352 centres : String or path, default None 

353 The 

354 ``seedname_centres.xyz`` file: the Wannier centres become the 

355 orbital positions (used by the Wilson-loop tools, the Peierls 

356 phases, *bridges.finite_system*, ...). 

357 positions : Array, shape (num_wann, dim) or (num_wann, 3), default None 

358 Orbital positions, instead of *centres*. With 

359 neither, every orbital sits at the origin of the cell. 

360 tags : List of num_wann strings (1 to 8 characters) 

361 Default value 

362 None (every orbital tagged ``'a'``). Sublattice tags. 

363 dim : 2 or 3, default 3 

364 A 2D model (a layer) keeps only 

365 :math:`(R_1, R_2)`: every element with :math:`R_3\neq 0` must vanish 

366 (within *tol*), and the lattice lies in the :math:`(x, y)` plane 

367 (the z components of the vectors read from *win* must vanish; those 

368 of the positions are dropped). 

369 cutoff : Positive real number or zero, default 0 

370 Drop the 

371 hoppings with :math:`|t| \le` *cutoff* (the exact zeros by default). 

372 tol : Positive real number, default 1e-6 

373 Tolerance of the 

374 Hermiticity and 2D checks (the file has 6 decimals). 

375 

376 Returns 

377 ------- 

378 ks : **KSpace** instance, with num_wann orbitals 

379 

380 Examples 

381 -------- 

382 Example usage:: 

383 

384 ks = read_wannier90('graphene_hr.dat', win='graphene.win', 

385 centres='graphene_centres.xyz', dim=2) 

386 ''' 

387 error_handling.file_path(hr, 'hr') 

388 error_handling.wannier_dim(dim) 

389 error_handling.positive_real_zero(cutoff, 'cutoff') 

390 error_handling.positive_real(tol, 'tol') 

391 num_wann, R, ndegen, ham = read_hr(hr) 

392 if prim_vec is None: 

393 error_handling.win_given(win) 

394 cell = read_win_cell(cast('str | os.PathLike', win)) 

395 error_handling.layer_cell(cell, dim) 

396 prim_vec = [tuple(float(c) for c in a[:dim]) for a in cell[:dim]] 

397 error_handling.prim_vec(prim_vec) 

398 error_handling.wannier_prim_vec(prim_vec, dim) 

399 if positions is None and centres is not None: 

400 positions = read_centres(centres, num_wann) 

401 if positions is None: 

402 positions = np.zeros((num_wann, dim)) 

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

404 error_handling.wannier_positions(positions.shape, num_wann, dim) 

405 tags = ['a'] * num_wann if tags is None else tags 

406 error_handling.wannier_tags(tags, num_wann) 

407 if dim == 2: 

408 error_handling.layer_hoppings(float(np.abs(ham[R[:, 2] != 0]).max(initial=0.)), tol) 

409 keep = R[:, 2] == 0 

410 R, ndegen, ham = R[keep, :2], ndegen[keep], ham[keep] 

411 return _hr_kspace(prim_vec, positions[:, :dim], tags, R, ham / ndegen[:, None, None], cutoff, tol) 

412 

413 

414def _hr_kspace( 

415 prim_vec: list[tuple[float, ...]], positions: NDArray[np.float64], tags: list[str], 

416 R: NDArray[np.int_], ham: NDArray[np.complex128], cutoff: float, tol: float, 

417 spin: bool = False, 

418) -> KSpace: 

419 r''' 

420 Private function. The **KSpace** of the matrices :math:`H(\mathbf{R})` 

421 (*ham*, shape (nR, num_wann, num_wann), degeneracy weights already 

422 divided out) at the lattice vectors *R* (integers, shape (nR, dim)), 

423 with orbitals at *positions*, for *read_wannier90*, *read_wannier90_tb*, 

424 *WannierFunctions.kspace* and the importers of *tbkit.interop*. It is 

425 Hermitian (with real onsite energies) when every :math:`H(\mathbf{R})` 

426 has its partner :math:`H(-\mathbf{R}) = H(\mathbf{R})^\dagger` within 

427 *tol*. With *spin*, *positions* and *tags* are those of the sites, and 

428 the orbitals their spin components (site-major, see *KSpace*). 

429 ''' 

430 num_wann = ham.shape[1] 

431 unit_cell = [{'tag': tag, 'r0': tuple(float(c) for c in r)} for tag, r in zip(tags, positions)] 

432 lat = Lattice(unit_cell=unit_cell, prim_vec=list(prim_vec)) 

433 ks = KSpace(lat, spin=spin) 

434 # Hermitian: every H(R) has its partner H(-R) = H(R)^dagger 

435 index = {tuple(r): p for p, r in enumerate(R.tolist())} 

436 partner = [index.get(tuple(-c for c in r)) for r in R.tolist()] 

437 hermitian = None not in partner and bool( 

438 np.abs(ham - ham[np.array(partner)].conj().transpose(0, 2, 1)).max() <= tol) 

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

440 hops = [] 

441 for r, h in zip(R.tolist(), ham): 

442 nonzero = [c for c in r if c != 0] 

443 R_cart = np.array(r, dtype='f8') @ a 

444 for m in range(num_wann): 

445 for n in range(num_wann): 

446 t = complex(h[m, n]) 

447 if m == n and not nonzero: 

448 ks.onsite[m] = t.real if hermitian else t 

449 elif abs(t) > cutoff and (not hermitian or (nonzero and nonzero[0] > 0) 

450 or (not nonzero and m < n)): 

451 # as set_hopping stores them: the element, then its conjugate 

452 hops.append((m, n, R_cart, t)) 

453 if hermitian: 

454 hops.append((n, m, -R_cart, t.conjugate())) 

455 ks._hop = hops 

456 ks._nonreciprocal = not hermitian 

457 return ks 

458 

459 

460def _integer_vectors(ks: KSpace, R_cart: NDArray[np.float64]) -> NDArray[np.int64]: 

461 r''' 

462 Private function. Cartesian lattice vectors (shape (n, space_dim)) as 

463 integers :math:`(n_1, ..., n_{dim})`, as in *KSpace._hop_cells*. 

464 ''' 

465 rec = np.array(ks.rec_vec, dtype='f8') 

466 return np.rint(np.reshape(R_cart, (-1, ks.space_dim)) @ rec.T / (2 * np.pi)).astype('i8') 

467 

468 

469def _wannier_cell(ks: KSpace) -> tuple[NDArray[np.float64], NDArray[np.float64]]: 

470 r''' 

471 Private function. The Wannier90 cell (rows :math:`\mathbf{a}_1, 

472 \mathbf{a}_2, \mathbf{a}_3`, shape (3, 3)) and the orbital positions 

473 (shape (norb, 3)) of a 2D (in the plane) or 3D **KSpace**. A 2D model 

474 gets :math:`\mathbf{a}_3 = (0, 0, c)`, *c* its longest primitive vector. 

475 ''' 

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

477 tau = ks.orbital_positions() 

478 if ks.dim == 3: 

479 return a, tau 

480 c = float(np.linalg.norm(a, axis=1).max()) 

481 cell = np.array([[*a[0], 0.], [*a[1], 0.], [0., 0., c]]) 

482 return cell, np.concatenate([tau, np.zeros((len(tau), 1))], axis=1) 

483 

484 

485def _wannier_blocks( 

486 ks: KSpace, 

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

488 r''' 

489 Private function. The matrices :math:`H_{mn}(\mathbf{R}) = 

490 \langle m\mathbf{0}|H|n\mathbf{R}\rangle` (onsite terms at 

491 :math:`\mathbf{R} = 0`) and :math:`\langle m\mathbf{0}|\mathbf{r}|n\mathbf{R}\rangle` 

492 (the orbital positions on the diagonal at :math:`\mathbf{R} = 0`, plus 

493 *_position_hop*) of a **KSpace**, at the lattice vectors *R* (shape 

494 (nR, 3), each with its opposite, sorted; zero for a 2D model's third 

495 component): shapes (nR, norb, norb) and (nR, norb, norb, 3). 

496 ''' 

497 n = ks.norb 

498 _, tau = _wannier_cell(ks) 

499 hops, elements = ks._hop, ks._position_hop 

500 cells = np.zeros((len(hops) + len(elements), 3), dtype='i8') 

501 cells[:len(hops), :ks.dim] = _integer_vectors(ks, np.array([h[2] for h in hops])) 

502 cells[len(hops):, :ks.dim] = _integer_vectors(ks, np.array([e[2] for e in elements])) 

503 R = np.unique(np.concatenate([cells, -cells, np.zeros((1, 3), dtype='i8')]), axis=0) 

504 index = {tuple(r): p for p, r in enumerate(R.tolist())} 

505 ham = np.zeros((len(R), n, n), dtype='c16') 

506 pos = np.zeros((len(R), n, n, 3), dtype='c16') 

507 origin = index[(0, 0, 0)] 

508 ham[origin] += np.diag(ks.onsite) + ks._onsite_offdiag 

509 pos[origin, np.arange(n), np.arange(n)] = tau 

510 for (i, j, _, t), cell in zip(hops, cells[:len(hops)]): 

511 ham[index[tuple(cell.tolist())], i, j] += t 

512 for (i, j, _, r), cell in zip(elements, cells[len(hops):]): 

513 pos[index[tuple(cell.tolist())], i, j, :ks.space_dim] += r 

514 return R, ham, pos 

515 

516 

517def _header() -> str: 

518 ''' 

519 Private function. The first line of the files written by tbkit. 

520 ''' 

521 return ' written by tbkit {} on {}'.format(tbkit.__version__, time.strftime('%d%b%Y at %H:%M:%S')) 

522 

523 

524def _weights_lines(nrpts: int) -> list[str]: 

525 ''' 

526 Private function. The degeneracy weights (all 1), 15 per line. 

527 ''' 

528 return [''.join('{:5d}'.format(1) for _ in range(k, min(k + 15, nrpts))) for k in range(0, nrpts, 15)] 

529 

530 

531def _check_wannier_export(ks: KSpace) -> None: 

532 ''' 

533 Private function. Validate a **KSpace** to be written in the Wannier90 formats. 

534 ''' 

535 error_handling.kspace(ks, KSpace) 

536 ks._check_static() 

537 error_handling.no_overlap(bool(ks._overlap_hop)) 

538 error_handling.wannier_export_dim(ks.dim, ks.space_dim) 

539 

540 

541def write_hr(ks: KSpace, path: str | os.PathLike) -> str: 

542 r''' 

543 Write a **KSpace** as a Wannier90 ``seedname_hr.dat`` file (see 

544 *read_hr*): every matrix :math:`H_{mn}(\mathbf{R}) = 

545 \langle m\mathbf{0}|H|n\mathbf{R}\rangle`, the onsite terms at 

546 :math:`\mathbf{R} = 0`, with degeneracy weights 1, at the lattice 

547 vectors of the hoppings and their opposites. The values are written 

548 with 12 decimals, so *read_wannier90* gives the model back to 

549 :math:`10^{-12}`. The value functions are written with the parameters 

550 of *set_params*. 

551 

552 Parameters 

553 ---------- 

554 ks : **KSpace** instance 

555 2D (in the plane) or 3D, without overlap (*set_overlap*). A spinful 

556 model is written orbital by orbital (site-major). 

557 path : String or path 

558 The file to write. 

559 

560 Returns 

561 ------- 

562 path : String 

563 The file written. 

564 ''' 

565 _check_wannier_export(ks) 

566 error_handling.file_path(path, 'path') 

567 R, ham, _ = _wannier_blocks(ks) 

568 lines = [_header(), '{:12d}'.format(ks.norb), '{:12d}'.format(len(R))] + _weights_lines(len(R)) 

569 for r, h in zip(R.tolist(), ham): 

570 for n in range(ks.norb): 

571 for m in range(ks.norb): 

572 lines.append('{:5d}{:5d}{:5d}{:5d}{:5d}{:20.12f}{:20.12f}'.format( 

573 *r, m + 1, n + 1, h[m, n].real, h[m, n].imag)) 

574 path = os.fspath(path) 

575 with open(path, 'w') as f: 

576 f.write('\n'.join(lines) + '\n') 

577 return path 

578 

579 

580def write_tb(ks: KSpace, path: str | os.PathLike) -> str: 

581 r''' 

582 Write a **KSpace** as a Wannier90 ``seedname_tb.dat`` file (see 

583 *read_tb*): the cell, the matrices :math:`H_{mn}(\mathbf{R})` of 

584 *write_hr* and the position matrix elements 

585 :math:`\langle m\mathbf{0}|\mathbf{r}|n\mathbf{R}\rangle`: the orbital 

586 positions on the diagonal at :math:`\mathbf{R} = 0`, and the other 

587 elements of a model read by *read_wannier90_tb*. A 2D model gets a 

588 third cell vector :math:`(0, 0, c)`, *c* its longest primitive vector. 

589 

590 Parameters 

591 ---------- 

592 ks : **KSpace** instance 

593 See *write_hr*. 

594 path : String or path 

595 The file to write. 

596 

597 Returns 

598 ------- 

599 path : String 

600 The file written. 

601 ''' 

602 _check_wannier_export(ks) 

603 error_handling.file_path(path, 'path') 

604 cell, _ = _wannier_cell(ks) 

605 R, ham, pos = _wannier_blocks(ks) 

606 lines = [_header()] + [''.join('{:20.12f}'.format(c) for c in a) for a in cell] 

607 lines += ['{:12d}'.format(ks.norb), '{:12d}'.format(len(R))] + _weights_lines(len(R)) 

608 for r, h in zip(R.tolist(), ham): 

609 lines += ['', '{:5d}{:5d}{:5d}'.format(*r)] 

610 lines += ['{:5d}{:5d}{:20.12f}{:20.12f}'.format(m + 1, n + 1, h[m, n].real, h[m, n].imag) 

611 for n in range(ks.norb) for m in range(ks.norb)] 

612 for r, p in zip(R.tolist(), pos): 

613 lines += ['', '{:5d}{:5d}{:5d}'.format(*r)] 

614 lines += ['{:5d}{:5d}'.format(m + 1, n + 1) 

615 + ''.join('{:20.12f}{:20.12f}'.format(c.real, c.imag) for c in p[m, n]) 

616 for n in range(ks.norb) for m in range(ks.norb)] 

617 path = os.fspath(path) 

618 with open(path, 'w') as f: 

619 f.write('\n'.join(lines) + '\n') 

620 return path 

621 

622 

623def write_wannier90(ks: KSpace, seedname: str | os.PathLike) -> list[str]: 

624 r''' 

625 Write a **KSpace** in the files of Wannier90 that *read_wannier90* and 

626 *read_wannier90_tb* read, and that other codes read too (PythTB's 

627 ``W90``, TBmodels, WannierTools, WannierBerri, Z2Pack through 

628 TBmodels): 

629 

630 * ``seedname_hr.dat``, the Hamiltonian (*write_hr*); 

631 * ``seedname_tb.dat``, the cell, the Hamiltonian and the position 

632 matrix elements (*write_tb*); 

633 * ``seedname.win``, with ``num_wann`` and the ``unit_cell_cart`` block; 

634 * ``seedname_centres.xyz``, the orbital positions as Wannier centres. 

635 

636 Wannier90's units are Angstrom and eV: the numbers are written as they 

637 are, in the units of the model. 

638 

639 Parameters 

640 ---------- 

641 ks : **KSpace** instance 

642 See *write_hr*. 

643 seedname : String or path 

644 The common prefix of the files. 

645 

646 Returns 

647 ------- 

648 paths : List of 4 strings 

649 The files written, in the order above. 

650 

651 Examples 

652 -------- 

653 Example usage:: 

654 

655 write_wannier90(haldane, 'haldane') 

656 ks = read_wannier90('haldane_hr.dat', win='haldane.win', 

657 centres='haldane_centres.xyz', dim=2) 

658 ''' 

659 _check_wannier_export(ks) 

660 error_handling.file_path(seedname, 'seedname') 

661 seedname = os.fspath(seedname) 

662 cell, tau = _wannier_cell(ks) 

663 hr = write_hr(ks, seedname + '_hr.dat') 

664 tb = write_tb(ks, seedname + '_tb.dat') 

665 win = seedname + '.win' 

666 with open(win, 'w') as f: 

667 f.write('!' + _header() + '\nnum_wann = {}\n\nbegin unit_cell_cart\nang\n'.format(ks.norb) 

668 + '\n'.join(''.join('{:20.12f}'.format(c) for c in a) for a in cell) 

669 + '\nend unit_cell_cart\n') 

670 xyz = seedname + '_centres.xyz' 

671 with open(xyz, 'w') as f: 

672 f.write('{:6d}\n'.format(ks.norb) + _header() + '\n' 

673 + ''.join('X' + ''.join('{:20.12f}'.format(c) for c in r) + '\n' for r in tau)) 

674 return [hr, tb, win, xyz] 

675 

676 

677def read_tb( 

678 path: str | os.PathLike, 

679) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64], NDArray[np.complex128], 

680 NDArray[np.complex128]]: 

681 r''' 

682 Read a Wannier90 ``seedname_tb.dat`` file: a header line, the three 

683 lattice vectors (Angstrom, one per line), the number of Wannier 

684 functions, the number of lattice vectors :math:`\mathbf{R}` and their 

685 degeneracy weights (15 per line), then, for each :math:`\mathbf{R}`, an 

686 empty line, ``R1 R2 R3`` and one line ``m n Re Im`` per element of 

687 :math:`H_{mn}(\mathbf{R})` (as in ``_hr.dat``), and again, for each 

688 :math:`\mathbf{R}`, an empty line, ``R1 R2 R3`` and one line 

689 ``m n Re(x) Im(x) Re(y) Im(y) Re(z) Im(z)`` per position matrix element 

690 :math:`\mathbf{r}_{mn}(\mathbf{R}) = \langle m\mathbf{0}|\mathbf{r}|n\mathbf{R}\rangle` 

691 (m, n counted from 1; Wannier90's ``hamiltonian_write_tb``). 

692 

693 Parameters 

694 ---------- 

695 path : String or path 

696 The ``_tb.dat`` file. 

697 

698 Returns 

699 ------- 

700 cell : Real ndarray, shape (3, 3) 

701 The rows are :math:`\mathbf{a}_1, \mathbf{a}_2, \mathbf{a}_3`. 

702 R : Integer ndarray, shape (nrpts, 3) 

703 Lattice vectors (in units of the primitive vectors). 

704 ndegen : Integer ndarray, shape (nrpts,) 

705 Degeneracy weights. 

706 ham : Complex ndarray, shape (nrpts, num_wann, num_wann) 

707 :math:`H_{mn}(\mathbf{R})` as written in the file (not divided by 

708 the weights). 

709 pos : Complex ndarray, shape (nrpts, num_wann, num_wann, 3) 

710 :math:`\mathbf{r}_{mn}(\mathbf{R})` as written (not divided by the weights). 

711 ''' 

712 error_handling.file_path(path, 'path') 

713 with open(path) as f: 

714 lines = f.read().splitlines()[1:] # the first line is a free comment 

715 cell_lines = [line.split()[:3] for line in lines[:3]] 

716 error_handling.win_cell(cell_lines, 'The first three lines after the header of a _tb.dat file') 

717 tokens = ' '.join(lines[3:]).split() 

718 error_handling.hr_header(tokens, '_tb.dat') 

719 num_wann, nrpts = int(tokens[0]), int(tokens[1]) 

720 ndegen = np.array(tokens[2:2 + nrpts], dtype='i8') 

721 body = tokens[2 + nrpts:] 

722 size_h, size_r = 3 + 4 * num_wann ** 2, 3 + 8 * num_wann ** 2 

723 error_handling.tb_body(len(body), nrpts, num_wann) 

724 rows_h = np.array(body[:nrpts * size_h], dtype='f8').reshape(nrpts, size_h) 

725 rows_r = np.array(body[nrpts * size_h:], dtype='f8').reshape(nrpts, size_r) 

726 R = rows_h[:, :3].astype('i8') 

727 error_handling.tb_vectors(np.array_equal(rows_r[:, :3].astype('i8'), R)) 

728 elem_h = rows_h[:, 3:].reshape(nrpts, num_wann ** 2, 4) 

729 elem_r = rows_r[:, 3:].reshape(nrpts, num_wann ** 2, 8) 

730 block = np.repeat(np.arange(nrpts), num_wann ** 2) 

731 ham = np.zeros((nrpts, num_wann, num_wann), 'c16') 

732 m, n = elem_h[..., 0].astype('i8').ravel() - 1, elem_h[..., 1].astype('i8').ravel() - 1 

733 ham[block, m, n] = (elem_h[..., 2] + 1j * elem_h[..., 3]).ravel() 

734 pos = np.zeros((nrpts, num_wann, num_wann, 3), 'c16') 

735 m, n = elem_r[..., 0].astype('i8').ravel() - 1, elem_r[..., 1].astype('i8').ravel() - 1 

736 pos[block, m, n] = (elem_r[..., 2::2] + 1j * elem_r[..., 3::2]).reshape(-1, 3) 

737 cell = np.array(cell_lines, dtype='f8') 

738 return cell, R, ndegen, ham, pos 

739 

740 

741def read_wannier90_tb( 

742 tb: str | os.PathLike, 

743 tags: list[str] | None = None, 

744 dim: int = 3, 

745 cutoff: float = 0., 

746 tol: float = 1e-6, 

747 elements: bool = True, 

748) -> KSpace: 

749 r''' 

750 Import a tight-binding model from Wannier90's ``seedname_tb.dat`` 

751 (see *read_tb*), which holds, besides the Hamiltonian of 

752 ``seedname_hr.dat``, the cell and the matrix elements of the position 

753 operator between the Wannier functions, 

754 :math:`\mathbf{r}_{mn}(\mathbf{R}) = \langle m\mathbf{0}|\mathbf{r}|n\mathbf{R}\rangle`. 

755 The Hamiltonian becomes a **KSpace** as in *read_wannier90*, and 

756 the Wannier centres :math:`\mathbf{r}_{mm}(\mathbf{0})` its orbital 

757 positions. 

758 

759 With *elements*, the model also keeps the other position matrix 

760 elements, and the responses that take ``positions=True`` use the whole 

761 position operator instead of the centres alone: the velocity is 

762 :math:`i[H, \mathbf{r}]` (in *hall_conductivity* and the other 

763 Berry-curvature responses, *tbkit.optics.optical_conductivity*), and the 

764 band curvature includes that of the Wannier functions' own Berry 

765 connection (Wang, Yates, Souza and Vanderbilt, Phys. Rev. B 74, 195118 

766 (2006)). *KSpace.spin_hall_conductivity*, *orbital_magnetization*, 

767 *axion_angle* and the Berry curvature dipole and shift current of 

768 *tbkit.optics* refuse them; the Wilson loops and the quantum geometric 

769 tensor use the centres only. *tbkit.io.save_model* keeps them. 

770 

771 Parameters 

772 ---------- 

773 tb : String or path 

774 The ``seedname_tb.dat`` file. 

775 tags : List of num_wann strings (1 to 8 characters), default None 

776 See *read_wannier90*. 

777 dim : 2 or 3, default 3 

778 See *read_wannier90*. For a 2D model, the position elements with 

779 :math:`R_3 \neq 0` must vanish too, and their z components are dropped. 

780 cutoff : Positive real number or zero, default 0 

781 Drop the hoppings 

782 and the position elements (by the norm of the vector) of size at 

783 most *cutoff*. 

784 tol : Positive real number, default 1e-6 

785 See *read_wannier90*. 

786 elements : Boolean, default True 

787 Keep the position matrix elements other than the centres. 

788 

789 Returns 

790 ------- 

791 ks : **KSpace** instance, with num_wann orbitals 

792 

793 Examples 

794 -------- 

795 Example usage:: 

796 

797 ks = read_wannier90_tb('wannier90_tb.dat', dim=2) 

798 sigma = ks.hall_conductivity(e_fermi, nk=200) # with i[H, r] 

799 ''' 

800 error_handling.file_path(tb, 'tb') 

801 error_handling.wannier_dim(dim) 

802 error_handling.positive_real_zero(cutoff, 'cutoff') 

803 error_handling.positive_real(tol, 'tol') 

804 error_handling.boolean(elements, 'elements') 

805 cell, R, ndegen, ham, pos = read_tb(tb) 

806 num_wann = ham.shape[1] 

807 error_handling.layer_cell(cell, dim) 

808 prim_vec = [tuple(float(c) for c in a[:dim]) for a in cell[:dim]] 

809 error_handling.prim_vec(prim_vec) 

810 error_handling.wannier_prim_vec(prim_vec, dim) 

811 tags = ['a'] * num_wann if tags is None else tags 

812 error_handling.wannier_tags(tags, num_wann) 

813 ham = ham / ndegen[:, None, None] 

814 pos = pos / ndegen[:, None, None, None] 

815 origin = np.flatnonzero((R == 0).all(axis=1)) 

816 error_handling.tb_origin(len(origin)) 

817 diag = np.arange(num_wann) 

818 centres = pos[origin[0], diag, diag].real 

819 if dim == 2: 

820 out = R[:, 2] != 0 

821 error_handling.layer_hoppings(float(max(np.abs(ham[out]).max(initial=0.), 

822 np.abs(pos[out]).max(initial=0.))), tol) 

823 R, ham, pos = R[~out, :2], ham[~out], pos[~out, :, :, :2] 

824 origin = np.flatnonzero((R == 0).all(axis=1)) 

825 ks = _hr_kspace(prim_vec, centres[:, :dim], tags, R, ham, cutoff, tol) 

826 if elements: 

827 pos[origin[0], diag, diag] = 0. 

828 a = np.array(prim_vec, dtype='f8') 

829 size = np.linalg.norm(pos, axis=-1) 

830 ks._position_hop = [(int(m), int(n), R[p].astype('f8') @ a, pos[p, m, n].copy()) 

831 for p, m, n in zip(*np.nonzero(size > cutoff))] 

832 return ks