Coverage for tbkit/interop.py: 100%

294 statements  

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

1r''' 

2Exchange models with other codes: ASE, PythTB, TBmodels, Z2Pack, qsymm, 

3pybinding and Kwant (for Wannier90's files, see *tbkit.io*). 

4 

5None of these packages is a dependency of tbkit: each function imports 

6the one it needs when it is called, and ``import tbkit`` never does. The 

7importers only read attributes, so they also accept objects that look 

8like the package's. 

9 

10============================== ========================================== 

11Function Does 

12============================== ========================================== 

13:func:`lattice_from_ase` ASE ``Atoms`` -> **Lattice** 

14:func:`lattice_to_ase` **Lattice** -> ASE ``Atoms`` (unit cell or sites) 

15:func:`from_pythtb` PythTB ``TBModel`` (``tb_model`` in 1.x) -> **KSpace** 

16:func:`to_pythtb` **KSpace** -> PythTB ``TBModel`` (``tb_model`` in 1.x) 

17:func:`to_tbmodels` **KSpace** -> TBmodels ``Model`` (and its HDF5 file) 

18:func:`z2pack_hamiltonian` **KSpace** -> the callable :math:`H(\mathbf{k})` of Z2Pack 

19:func:`to_z2pack` **KSpace** -> ``z2pack.hm.System`` 

20:func:`to_qsymm` **KSpace** -> qsymm ``BlochModel`` 

21:func:`from_pybinding` pybinding ``Lattice`` -> **KSpace**; ``Model`` -> matrix, positions 

22:func:`to_pybinding` **KSpace** -> pybinding ``Lattice`` 

23:func:`to_kwant` **System** or **Transport** (with its leads) -> Kwant ``Builder`` 

24:func:`from_kwant` finalized Kwant system -> matrix, positions 

25============================== ========================================== 

26 

27**Conventions.** All these codes, and tbkit, store a hopping as the matrix 

28element :math:`t_{ij}(\mathbf{R}) = \langle i,\mathbf{0}|H|j,\mathbf{R}\rangle`, 

29so the hopping lists translate one to one. They differ in the Bloch 

30phases: tbkit's *get_ham* uses the periodic gauge 

31:math:`e^{i\mathbf{k}\cdot\mathbf{R}}` (Wannier90's and TBmodels' 

32"convention 2", Z2Pack's default), PythTB (1.x and 2.0) and qsymm include 

33the orbital positions, :math:`e^{i\mathbf{k}\cdot(\mathbf{R}+\boldsymbol\tau_j-\boldsymbol\tau_i)}` 

34("convention 1"), and pybinding uses :math:`e^{-i\mathbf{k}\cdot\mathbf{R}}`. 

35The matrices :math:`H(\mathbf{k})` then differ by a diagonal unitary (or by 

36:math:`\mathbf{k}\to-\mathbf{k}`), and the bands, Chern numbers and 

37:math:`\mathbb{Z}_2` invariants are the same. PythTB counts k in units of 

38the reciprocal vectors, tbkit in Cartesian coordinates. 

39 

40**What is not exchanged.** Value functions are written with the 

41parameters of *KSpace.set_params*; overlaps (*set_overlap*), driven models 

42and non-Hermitian models are refused by the exporters, which all need a 

43Hermitian, orthogonal tight-binding model. 

44''' 

45from __future__ import annotations 

46 

47import importlib 

48from typing import Any, Callable 

49 

50import numpy as np 

51from numpy.typing import ArrayLike, NDArray 

52import scipy.linalg as sla 

53import scipy.sparse as sp 

54 

55import tbkit.error_handling as error_handling 

56from tbkit.io import _hr_kspace 

57from tbkit.kspace import KSpace 

58from tbkit.lattice import Lattice 

59from tbkit.system import System 

60from tbkit.transport import Transport 

61 

62 

63def _import(name: str) -> Any: 

64 ''' 

65 Private function. Import an optional package on first use. 

66 ''' 

67 try: 

68 return importlib.import_module(name) 

69 except ImportError: 

70 raise ImportError('\n\nThis function needs the optional package {0} ' 

71 '(pip install {0}).\n'.format(name)) from None 

72 

73 

74def _default_tags(n: int) -> list[str]: 

75 ''' 

76 Private function. One tag per site: 'a', 'b', ..., 'z', then 's26', 's27', ... 

77 ''' 

78 return [chr(ord('a') + s) if s < 26 else 's{}'.format(s) for s in range(n)] 

79 

80 

81def _check_export(ks: KSpace) -> None: 

82 ''' 

83 Private function. Validate a **KSpace** to be exported: static, 

84 orthogonal and Hermitian. 

85 ''' 

86 error_handling.kspace(ks, KSpace) 

87 ks._check_static() 

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

89 error_handling.hermitian_model(ks.is_hermitian()) 

90 

91 

92def _site_positions(ks: KSpace) -> NDArray[np.float64]: 

93 ''' 

94 Private function. The positions of the sites of the unit cell, shape (n_sites, space_dim). 

95 ''' 

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

97 

98 

99def _forward(u: int, v: int, R: tuple[int, ...]) -> bool: 

100 ''' 

101 Private function. Whether the hopping (u, v, R) is the representative 

102 of the pair it forms with its conjugate (v, u, -R): the first nonzero 

103 component of R positive, or R = 0 and u < v. 

104 ''' 

105 nonzero = [c for c in R if c != 0] 

106 return nonzero[0] > 0 if nonzero else u < v 

107 

108 

109def _site_blocks(ks: KSpace, nb: int) -> tuple[NDArray[np.complex128], dict]: 

110 r''' 

111 Private function. The onsite blocks (shape (units, nb, nb)) and one 

112 hopping block :math:`\langle u,\mathbf{0}|H|v,\mathbf{R}\rangle` (nb x nb) 

113 per conjugate pair, keyed by (u, v, R), of a Hermitian **KSpace**, with 

114 units of *nb* orbitals: the sites (*nb* = 2 for a spinful model) or the 

115 orbitals (*nb* = 1). 

116 ''' 

117 units = ks.norb // nb 

118 onsite = np.zeros((units, nb, nb), dtype='c16') 

119 blocks: dict = {} 

120 zero = (0,) * ks.dim 

121 full = np.diag(ks.onsite) + ks._onsite_offdiag 

122 terms = [(int(i), int(j), zero, full[i, j]) for i, j in zip(*np.nonzero(full))] 

123 for i, j, R, t in terms + ks._hop_cells(): 

124 u, v = i // nb, j // nb 

125 if u == v and not any(R): 

126 onsite[u, i % nb, j % nb] += t 

127 else: 

128 blocks.setdefault((u, v, R), np.zeros((nb, nb), dtype='c16'))[i % nb, j % nb] += t 

129 return onsite, {key: b for key, b in blocks.items() if _forward(*key)} 

130 

131 

132def _full_basis(ks: KSpace) -> NDArray[np.float64]: 

133 ''' 

134 Private function. The primitive vectors, completed by an orthonormal 

135 basis of their orthogonal complement (shape (space_dim, space_dim), rows). 

136 ''' 

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

138 if ks.dim == ks.space_dim: 

139 return a 

140 return np.concatenate([a, sla.null_space(a).T]) 

141 

142 

143def _reduced_positions(ks: KSpace) -> NDArray[np.float64]: 

144 r''' 

145 Private function. The orbital positions in units of the primitive 

146 vectors, in the plane (or along the line) of the lattice: shape (norb, dim). 

147 ''' 

148 a = np.array(ks.lat.prim_vec, dtype='f8') @ ks.k_basis 

149 return ks.orbital_positions() @ ks.k_basis @ np.linalg.inv(a) 

150 

151 

152################################# 

153# ASE 

154################################# 

155 

156 

157def lattice_from_ase(atoms: Any, tags: list[str] | None = None, space_dim: int | None = None) -> Lattice: 

158 r''' 

159 Get the **Lattice** of an ASE ``Atoms`` object (`ase-lib.org 

160 <https://ase-lib.org>`_): its periodic cell vectors (those with 

161 ``pbc`` True) are the primitive vectors, its atoms the sites of the 

162 unit cell, in the same order and units (Angstrom). 

163 

164 Parameters 

165 ---------- 

166 atoms : ``ase.Atoms`` 

167 At least one periodic direction. 

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

169 One per atom; 

170 the chemical symbols by default. 

171 space_dim : 2, 3 or None, default None 

172 2 keeps the x and y coordinates only, for a 

173 lattice in the plane: the periodic vectors must lie in the plane and 

174 the atoms at the same height (dropped). None takes 2 when this is the 

175 case (at most two periodic directions), 3 otherwise. 

176 

177 Returns 

178 ------- 

179 lat : **Lattice** instance 

180 

181 Examples 

182 -------- 

183 Example usage:: 

184 

185 from ase.build import graphene 

186 lat = lattice_from_ase(graphene(a=2.46, vacuum=None)) # 2 sites 'C' 

187 ''' 

188 cell = np.asarray(atoms.get_cell(), dtype='f8').reshape(3, 3) 

189 pbc = np.asarray(atoms.get_pbc(), dtype=bool).reshape(3) 

190 pos = np.asarray(atoms.get_positions(), dtype='f8').reshape(-1, 3) 

191 error_handling.ase_periodic(pbc) 

192 tags = list(atoms.get_chemical_symbols()) if tags is None else tags 

193 error_handling.site_tags(tags, len(pos)) 

194 a = cell[pbc] 

195 scale = max(1., float(np.abs(pos).max(initial=0.)), float(np.abs(a).max())) 

196 planar = len(a) <= 2 and bool(np.all(np.abs(a[:, 2]) <= 1e-9 * scale)) \ 

197 and float(np.ptp(pos[:, 2])) <= 1e-9 * scale if len(pos) else False 

198 if space_dim is None: 

199 space_dim = 2 if planar else 3 

200 error_handling.ase_space_dim(space_dim, planar) 

201 prim_vec = [tuple(float(c) for c in v[:space_dim]) for v in a] 

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

203 return Lattice(unit_cell=unit_cell, prim_vec=prim_vec) 

204 

205 

206def lattice_to_ase(lat: Lattice, symbols: dict[str, str] | None = None, sites: bool = False) -> Any: 

207 r''' 

208 Get an ASE ``Atoms`` object of a **Lattice**: its unit cell, periodic 

209 along the primitive vectors (the other cell vectors zero and not 

210 periodic), or, with *sites*, the finite sample of *get_lattice* as a 

211 cluster (no periodic direction). A 2D lattice is placed at z = 0. 

212 

213 Parameters 

214 ---------- 

215 lat : **Lattice** instance 

216 symbols : Dictionary, default None 

217 Chemical symbol of each tag 

218 (``{'a': 'C', 'b': 'N'}``). By default, the tags themselves, which 

219 must then be chemical symbols. 

220 sites : Boolean, default False 

221 The sites of *lat.coor* instead of the unit cell. 

222 

223 Returns 

224 ------- 

225 atoms : ``ase.Atoms`` 

226 ''' 

227 error_handling.lat(lat) 

228 error_handling.boolean(sites, 'sites') 

229 ase = _import('ase') 

230 if sites: 

231 error_handling.empty_coor(lat.coor) 

232 tags = [str(t) for t in lat.coor['tag']] 

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

234 else: 

235 tags = [dic['tag'] for dic in lat.unit_cell] 

236 pos = np.array([dic['r0'] for dic in lat.unit_cell], dtype='f8').reshape(len(tags), -1) 

237 names = [symbols.get(t, t) for t in tags] if symbols is not None else tags 

238 error_handling.chemical_symbols(names, ase.data.chemical_symbols) 

239 pos = np.concatenate([pos, np.zeros((len(pos), 3 - pos.shape[1]))], axis=1) 

240 cell = np.zeros((3, 3)) 

241 pbc = [False] * 3 

242 if not sites: 

243 for c, v in enumerate(lat.prim_vec): 

244 cell[c, :len(v)] = v 

245 pbc[c] = True 

246 return ase.Atoms(symbols=names, positions=pos, cell=cell, pbc=pbc) 

247 

248 

249################################# 

250# PYTHTB 

251################################# 

252 

253 

254def from_pythtb(model: Any, tags: list[str] | None = None) -> KSpace: 

255 r''' 

256 Get the **KSpace** of a PythTB model (`pythtb.readthedocs.io 

257 <https://pythtb.readthedocs.io>`_): a ``TBModel`` of PythTB 2, or a 

258 ``tb_model`` of PythTB 1.x. The periodic lattice vectors become the 

259 primitive vectors, the orbitals the sites (spinful models give a 

260 spinful **KSpace**), and every hopping, with its conjugate, a hopping 

261 of tbkit: both codes store :math:`\langle i,\mathbf{0}|H|j,\mathbf{R}\rangle`. 

262 The bands and the topological invariants are those of PythTB; its 

263 :math:`H(\mathbf{k})` includes the orbital positions (convention 1) and 

264 tbkit's does not (see the module docstring). A model of 1D space is 

265 placed along x in the plane. 

266 

267 Parameters 

268 ---------- 

269 model : ``pythtb.TBModel`` or ``pythtb.tb_model`` 

270 With at least one 

271 periodic direction and numbers only (no parametric terms). 

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

273 One per orbital 

274 (per site for a spinful model); 'a', 'b', ... by default. 

275 

276 Returns 

277 ------- 

278 ks : **KSpace** instance 

279 ''' 

280 if hasattr(model, 'hoppings'): # PythTB 2 

281 lat_vecs = np.asarray(model.lat_vecs, dtype='f8') 

282 per = [int(p) for p in model.lattice.periodic_dirs] 

283 positions = np.asarray(model.get_orb_vecs(cartesian=True), dtype='f8') 

284 spin = bool(model.spinful) 

285 onsite = list(model.onsite) 

286 hops = [(h['amplitude'], h['from_orbital'], h['to_orbital'], # no vector within the cell 

287 h.get('lattice_vector', np.zeros(len(lat_vecs)))) for h in model.hoppings] 

288 else: # PythTB 1.x 

289 lat_vecs = np.asarray(model._lat, dtype='f8') 

290 per = [int(p) for p in model._per] 

291 positions = np.asarray(model._orb, dtype='f8') @ lat_vecs 

292 spin = model._nspin == 2 

293 onsite = list(model._site_energies) 

294 hops = [(h[0], h[1], h[2], h[3]) for h in model._hoppings] 

295 error_handling.pythtb_periodic(len(per)) 

296 error_handling.numeric_terms([e for e in onsite] + [h[0] for h in hops], 'PythTB') 

297 n_sites = len(positions) 

298 tags = _default_tags(n_sites) if tags is None else tags 

299 error_handling.site_tags(tags, n_sites) 

300 pad = max(0, 2 - lat_vecs.shape[1]) # a model of 1D space lies along x 

301 lat_vecs = np.pad(lat_vecs, ((0, 0), (0, pad))) 

302 positions = np.pad(positions.reshape(n_sites, -1), ((0, 0), (0, pad))) 

303 nb = 2 if spin else 1 

304 blocks: dict = {} 

305 

306 def add(R, i, j, value): 

307 block = np.asarray(value, dtype='c16') 

308 block = block * np.eye(nb) if block.ndim == 0 else block.reshape(nb, nb) 

309 mat = blocks.setdefault(R, np.zeros((nb * n_sites, nb * n_sites), dtype='c16')) 

310 mat[nb * i:nb * (i + 1), nb * j:nb * (j + 1)] += block 

311 return block 

312 

313 for s, e in enumerate(onsite): 

314 add((0,) * len(per), s, s, e) 

315 for amp, i, j, R in hops: 

316 R = tuple(int(round(float(np.ravel(R)[p]))) for p in per) 

317 block = add(R, i, j, amp) 

318 add(tuple(-c for c in R), j, i, block.conj().T) 

319 R_arr = np.array(sorted(blocks), dtype='i8').reshape(len(blocks), len(per)) 

320 ham = np.array([blocks[tuple(r)] for r in R_arr.tolist()]) 

321 prim_vec = [tuple(float(c) for c in lat_vecs[p]) for p in per] 

322 return _hr_kspace(prim_vec, positions, tags, R_arr, ham, 0., 1e-10, spin) 

323 

324 

325def to_pythtb(ks: KSpace) -> Any: 

326 r''' 

327 Get the PythTB model of a **KSpace**: a ``TBModel`` with PythTB 2, a 

328 ``tb_model`` with PythTB 1.x. The lattice vectors are the primitive 

329 vectors, completed by orthonormal non-periodic ones for a lattice of 

330 lower dimension than its space (a chain in the plane, a slab); the 

331 sites become the orbitals (spinful with ``spin=True``), and one 

332 hopping of each conjugate pair is set (PythTB adds the other). See 

333 *from_pythtb* for the conventions. 

334 

335 Parameters 

336 ---------- 

337 ks : **KSpace** instance 

338 Hermitian, without overlap. 

339 

340 Returns 

341 ------- 

342 model : ``pythtb.TBModel`` (or ``pythtb.tb_model``) 

343 

344 Examples 

345 -------- 

346 Example usage:: 

347 

348 model = to_pythtb(models.haldane()) 

349 model.chern_number((0, 1), (60, 60), occ_idxs=[0]) # 1.0 

350 ''' 

351 _check_export(ks) 

352 pythtb = _import('pythtb') 

353 nb = 2 if ks.spin else 1 

354 vecs = _full_basis(ks) 

355 reduced = _site_positions(ks) @ np.linalg.inv(vecs) 

356 onsite, hops = _site_blocks(ks, nb) 

357 per = list(range(ks.dim)) 

358 if hasattr(pythtb, 'TBModel'): 

359 model = pythtb.TBModel(pythtb.Lattice(vecs, reduced, periodic_dirs=per), spinful=ks.spin) 

360 else: 

361 model = pythtb.tb_model(ks.dim, ks.space_dim, vecs.tolist(), reduced.tolist(), per=per, nspin=nb) 

362 model.set_onsite([float(b[0, 0].real) if nb == 1 else b for b in onsite]) 

363 for (u, v, R), b in hops.items(): 

364 model.set_hop(complex(b[0, 0]) if nb == 1 else b, u, v, list(R) + [0] * (ks.space_dim - ks.dim)) 

365 return model 

366 

367 

368################################# 

369# TBMODELS, Z2PACK, QSYMM 

370################################# 

371 

372 

373def to_tbmodels(ks: KSpace, path: str | None = None) -> Any: 

374 r''' 

375 Get the TBmodels ``Model`` of a **KSpace** (`tbmodels.greschd.ch 

376 <https://tbmodels.greschd.ch>`_), and write its HDF5 file with *path*. 

377 The orbitals keep their order; the unit cell and the positions are 

378 those of the plane (or line) of the lattice, in its own coordinates 

379 (*KSpace.k_basis*): a slab's positions out of its plane are dropped. 

380 TBmodels' default (convention 2) is the Bloch Hamiltonian of tbkit. 

381 

382 Parameters 

383 ---------- 

384 ks : **KSpace** instance 

385 Hermitian, without overlap. 

386 path : String or None, default None 

387 HDF5 file to write (needs h5py). 

388 

389 Returns 

390 ------- 

391 model : ``tbmodels.Model`` 

392 ''' 

393 _check_export(ks) 

394 if path is not None: 

395 error_handling.file_path(path, 'path') 

396 tbmodels = _import('tbmodels') 

397 onsite, hops = _site_blocks(ks, 1) 

398 uc = np.array(ks.lat.prim_vec, dtype='f8') @ ks.k_basis 

399 model = tbmodels.Model.from_hop_list( 

400 hop_list=[(complex(b[0, 0]), u, v, R) for (u, v, R), b in hops.items()], 

401 size=ks.norb, dim=ks.dim, on_site=onsite[:, 0, 0].real, pos=_reduced_positions(ks), uc=uc, 

402 contains_cc=False) 

403 if path is not None: 

404 model.to_hdf5_file(path) 

405 return model 

406 

407 

408def z2pack_hamiltonian(ks: KSpace) -> Callable[[ArrayLike], NDArray[np.complex128]]: 

409 r''' 

410 Get the Bloch Hamiltonian of a **KSpace** as the function of 

411 ``z2pack.hm.System``: :math:`\mathbf{k}` in units of the reciprocal 

412 vectors (*dim* numbers) to the matrix of *get_ham* (the periodic gauge, 

413 Z2Pack's ``convention=2``). Z2Pack then needs the orbital positions 

414 (*to_z2pack* passes them). 

415 

416 Parameters 

417 ---------- 

418 ks : **KSpace** instance 

419 Hermitian, without overlap. 

420 

421 Returns 

422 ------- 

423 hamilton : Function 

424 ``hamilton(k)``, *k* a sequence of *dim* real numbers. 

425 ''' 

426 _check_export(ks) 

427 rec = np.array(ks.rec_vec_k) 

428 

429 def hamilton(k: ArrayLike) -> NDArray[np.complex128]: 

430 return ks.get_ham(np.asarray(k, dtype='f8') @ rec) 

431 return hamilton 

432 

433 

434def to_z2pack(ks: KSpace, bands: int | list[int] | None = None, **kwargs) -> Any: 

435 r''' 

436 Get the ``z2pack.hm.System`` of a **KSpace** (`z2pack.greschd.ch 

437 <https://z2pack.greschd.ch>`_), for its Wilson loops, Chern numbers and 

438 :math:`\mathbb{Z}_2` invariants: the function of *z2pack_hamiltonian*, 

439 the dimension *dim* and the reduced orbital positions, with 

440 ``convention=2``. Z2Pack's Chern number has the sign of *chern_number* 

441 on the surface ``lambda t1, t2: [t2, t1]`` (Wilson loops along 

442 :math:`\mathbf{b}_1`, moved along :math:`\mathbf{b}_2`), the opposite 

443 one on ``[t1, t2]``. 

444 

445 Parameters 

446 ---------- 

447 ks : **KSpace** instance 

448 Hermitian, without overlap. 

449 bands : Integer, list of integers or None, default None 

450 The occupied bands (Z2Pack's 

451 default, None, is the lower half). 

452 kwargs 

453 Passed to ``z2pack.hm.System`` (*hermitian_tol*, ...). 

454 

455 Returns 

456 ------- 

457 system : ``z2pack.hm.System`` 

458 

459 Examples 

460 -------- 

461 Example usage:: 

462 

463 system = to_z2pack(models.haldane(), bands=[0]) 

464 result = z2pack.surface.run(system=system, surface=lambda t1, t2: [t2, t1]) 

465 z2pack.invariant.chern(result) # 1, as chern_number(0) 

466 ''' 

467 hamilton = z2pack_hamiltonian(ks) 

468 z2pack = _import('z2pack') 

469 return z2pack.hm.System(hamilton, dim=ks.dim, pos=_reduced_positions(ks), bands=bands, 

470 convention=2, **kwargs) 

471 

472 

473def to_qsymm(ks: KSpace) -> Any: 

474 r''' 

475 Get the qsymm ``BlochModel`` of a **KSpace** (`qsymm 

476 <https://qsymm.readthedocs.io>`_), for qsymm's symmetry finder 

477 (``qsymm.symmetries``): :math:`H(\mathbf{k}) = \sum_{\mathbf{d}} 

478 H_{\mathbf{d}}\,e^{i\mathbf{k}\cdot\mathbf{d}}` over the bond vectors 

479 :math:`\mathbf{d} = \mathbf{R}+\boldsymbol\tau_j-\boldsymbol\tau_i` 

480 (orbital positions included, as qsymm expects), in the coordinates of 

481 *KSpace.k_basis* (Cartesian when the lattice fills its space), with the 

482 momenta ``k_x``, ``k_y`` (, ``k_z``). Needs sympy. 

483 

484 Parameters 

485 ---------- 

486 ks : **KSpace** instance 

487 Hermitian, without overlap. 

488 

489 Returns 

490 ------- 

491 model : ``qsymm.BlochModel`` 

492 ''' 

493 _check_export(ks) 

494 qsymm = _import('qsymm') 

495 sympy = _import('sympy') 

496 tau = ks.orbital_positions() 

497 full = np.diag(ks.onsite) + ks._onsite_offdiag 

498 terms = [(int(i), int(j), np.zeros(ks.space_dim), full[i, j]) for i, j in zip(*np.nonzero(full))] 

499 groups: dict = {} 

500 for i, j, R, t in terms + ks._hop: 

501 d = (R + tau[j] - tau[i]) @ ks.k_basis 

502 key = tuple(np.round(d, 10) + 0.) 

503 groups.setdefault(key, (d, np.zeros((ks.norb, ks.norb), dtype='c16')))[1][i, j] += t 

504 ham = {qsymm.model.BlochCoeff(d, sympy.Integer(1)): mat for d, mat in groups.values()} 

505 return qsymm.BlochModel(ham, momenta=['k_x', 'k_y', 'k_z'][:ks.dim]) 

506 

507 

508################################# 

509# PYBINDING 

510################################# 

511 

512 

513def from_pybinding(obj: Any, spin: bool = False) -> KSpace | tuple[sp.csr_matrix, NDArray[np.float64]]: 

514 r''' 

515 Get the **KSpace** of a pybinding ``Lattice`` (`pybinding 

516 <https://docs.pybinding.site>`_), or the Hamiltonian and orbital 

517 positions of a pybinding ``Model`` (a finite sample, as pybinding 

518 builds it from a lattice, a shape and modifiers). 

519 

520 The sublattices of a ``Lattice`` become the sites, in the order they 

521 were added, at their positions, with their names as tags; a sublattice 

522 of several orbitals gives one site per orbital, tagged by its name and 

523 the orbital index (``'A0'``, ``'A1'``), unless *spin* asks for one 

524 spinful site per sublattice (each must then have 2 orbitals). Both 

525 codes store :math:`\langle i,\mathbf{0}|H|j,\mathbf{R}\rangle`; pybinding's 

526 Bloch phases are :math:`e^{-i\mathbf{k}\cdot\mathbf{R}}`, so its 

527 :math:`H(\mathbf{k})` is tbkit's :math:`H(-\mathbf{k})` (to its single 

528 precision, pybinding's default). 

529 

530 Parameters 

531 ---------- 

532 obj : ``pybinding.Lattice`` or ``pybinding.Model`` 

533 Without sublattice aliases. 

534 spin : Boolean, default False 

535 See above. 

536 

537 Returns 

538 ------- 

539 ks : **KSpace** instance, for a ``Lattice`` 

540 ham, positions : Sparse CSR complex matrix and real ndarray of shape (n, 3), for a ``Model`` 

541 ''' 

542 error_handling.boolean(spin, 'spin') 

543 if hasattr(obj, 'hamiltonian') and hasattr(obj, 'system'): 

544 ham = sp.csr_matrix(obj.hamiltonian, dtype='c16') 

545 xyz = obj.system.expanded_positions # one per orbital 

546 return ham, np.stack([np.asarray(xyz.x, dtype='f8'), np.asarray(xyz.y, dtype='f8'), 

547 np.asarray(xyz.z, dtype='f8')], axis=1) 

548 ndim = int(obj.ndim) 

549 vectors = np.array([np.asarray(v, dtype='f8') for v in obj.vectors]).reshape(ndim, -1) 

550 subs = sorted(obj.sublattices.items(), key=lambda item: item[1].unique_id) 

551 error_handling.pybinding_aliases([s.alias_id == s.unique_id for _, s in subs]) 

552 energies = [np.atleast_2d(np.asarray(s.energy, dtype='c16')) for _, s in subs] 

553 sizes = [len(e) for e in energies] 

554 if spin: 

555 error_handling.pybinding_spin(sizes) 

556 offsets = np.concatenate([[0], np.cumsum(sizes)]) 

557 index = {s.unique_id: p for p, (_, s) in enumerate(subs)} 

558 pos = np.array([np.asarray(s.position, dtype='f8') for _, s in subs]).reshape(len(subs), -1) 

559 pos = np.pad(pos, ((0, 0), (0, 3 - pos.shape[1]))) 

560 vectors = np.pad(vectors, ((0, 0), (0, 3 - vectors.shape[1]))) 

561 space_dim = 3 if ndim == 3 or np.any(vectors[:, 2] != 0) or np.any(pos[:, 2] != 0) else 2 

562 n = int(offsets[-1]) 

563 blocks: dict = {} 

564 

565 def add(R, p, q, e): 

566 mat = blocks.setdefault(R, np.zeros((n, n), dtype='c16')) 

567 mat[offsets[p]:offsets[p + 1], offsets[q]:offsets[q + 1]] += e 

568 

569 for p, e in enumerate(energies): 

570 add((0,) * ndim, p, p, e) 

571 for family in obj.hoppings.values(): 

572 e = np.atleast_2d(np.asarray(family.energy, dtype='c16')) 

573 for term in family.terms: 

574 R = tuple(int(c) for c in np.asarray(term.relative_index)[:ndim]) 

575 p, q = index[term.from_id], index[term.to_id] 

576 add(R, p, q, e) 

577 add(tuple(-c for c in R), q, p, e.conj().T) 

578 R_arr = np.array(sorted(blocks), dtype='i8').reshape(len(blocks), ndim) 

579 ham = np.array([blocks[tuple(r)] for r in R_arr.tolist()]) 

580 prim_vec = [tuple(float(c) for c in v[:space_dim]) for v in vectors] 

581 names = [str(name) for name, _ in subs] 

582 if spin: 

583 return _hr_kspace(prim_vec, pos[:, :space_dim], names, R_arr, ham, 0., 1e-10, True) 

584 tags = [name if size == 1 else '{}{}'.format(name, o) for name, size in zip(names, sizes) 

585 for o in range(size)] 

586 positions = np.repeat(pos[:, :space_dim], sizes, axis=0) 

587 return _hr_kspace(prim_vec, positions, tags, R_arr, ham, 0., 1e-10) 

588 

589 

590def to_pybinding(ks: KSpace) -> Any: 

591 r''' 

592 Get the pybinding ``Lattice`` of a **KSpace**: one sublattice per site 

593 (with a 2 x 2 onsite matrix for a spinful model), named by its tag (by 

594 its tag and index when tags repeat), and one hopping of each conjugate 

595 pair (pybinding adds the other). See *from_pybinding* for the conventions. 

596 pybinding then builds finite samples (``pb.Model(lattice, shape)``) 

597 and its KPM tools on it. 

598 

599 Parameters 

600 ---------- 

601 ks : **KSpace** instance 

602 Hermitian, without overlap. 

603 

604 Returns 

605 ------- 

606 lattice : ``pybinding.Lattice`` 

607 ''' 

608 _check_export(ks) 

609 pb = _import('pybinding') 

610 nb = 2 if ks.spin else 1 

611 onsite, hops = _site_blocks(ks, nb) 

612 tags = [str(t) for t in ks.tags] 

613 names = tags if len(set(tags)) == len(tags) else ['{}{}'.format(t, s) for s, t in enumerate(tags)] 

614 lattice = pb.Lattice(*[list(v) for v in ks.lat.prim_vec]) 

615 lattice.add_sublattices(*[(name, list(r), float(b[0, 0].real) if nb == 1 else b) 

616 for name, r, b in zip(names, _site_positions(ks), onsite)]) 

617 lattice.add_hoppings(*[(list(R), names[u], names[v], complex(b[0, 0]) if nb == 1 else b) 

618 for (u, v, R), b in hops.items()]) 

619 return lattice 

620 

621 

622################################# 

623# KWANT 

624################################# 

625 

626 

627def _site_family(kwant: Any, tinyarray: Any, positions: NDArray[np.float64], name: str) -> Any: 

628 ''' 

629 Private function. A Kwant site family of one orbital per site, whose 

630 tags (i,) index *positions*. 

631 ''' 

632 class Sites(kwant.builder.SiteFamily): 

633 

634 def __init__(self) -> None: 

635 super().__init__('tbkit.interop.{}.{}'.format(name, id(self)), name, 1) 

636 

637 def normalize_tag(self, tag): 

638 return tinyarray.array((int(tag[0]),)) 

639 

640 def pos(self, tag): 

641 return positions[tag[0]] 

642 

643 return Sites() 

644 

645 

646def to_kwant(model: System | Transport, sys: System | None = None) -> Any: 

647 r''' 

648 Get a Kwant ``Builder`` (`kwant-project.org <https://kwant-project.org>`_) 

649 of a **System**, or of a **Transport** device with its leads. 

650 

651 Every site (orbital) of the model becomes a Kwant site of one orbital 

652 at its position, with the onsite energies and hoppings of the 

653 Hamiltonian (*System.ham*, after *get_ham*, or the device of the 

654 *Transport*). Each lead of a *Transport* becomes a copy of its first 

655 cell, joined to the device by the lead's coupling, followed by a 

656 ``kwant.builder.ModesLead`` whose modes Kwant computes from the lead's 

657 :math:`h_0` and :math:`v` (and its conservation law, so that 

658 ``smatrix.submatrix((lead, block), ...)`` resolves its blocks). The 

659 added cell does not change the transmissions; the phases of the 

660 scattering amplitudes are those of Kwant's modes. 

661 

662 Parameters 

663 ---------- 

664 model : **System** or **Transport** instance 

665 Hermitian. 

666 sys : **System** instance or None, default None 

667 For a *Transport*: the 

668 system its device was built from, for the site positions (those 

669 added by *attach_lead* with ``extend=True`` included). Without it, 

670 site *i* sits at :math:`(i, 0)`. 

671 

672 Returns 

673 ------- 

674 builder : ``kwant.Builder`` 

675 Finalize it (``builder.finalized()``) to compute. 

676 

677 Examples 

678 -------- 

679 Example usage:: 

680 

681 fsys = to_kwant(tr, sys).finalized() 

682 kwant.smatrix(fsys, 0.3).transmission(1, 0) # = tr.transmission([0.3])[0] 

683 ''' 

684 if isinstance(model, Transport): 

685 ham = model._ham 

686 if sys is None: 

687 positions = np.stack([np.arange(ham.shape[0], dtype='f8'), np.zeros(ham.shape[0])], axis=1) 

688 else: 

689 error_handling.sys(sys) 

690 error_handling.lead_device_size(sys.lat.sites + len(model._added_tags), ham.shape[0]) 

691 positions = model._site_positions(sys) 

692 leads, laws = model.leads, model._laws 

693 else: 

694 error_handling.sys(model) 

695 error_handling.empty_hop(model.hop) 

696 error_handling.kwant_ham(model.ham.shape[0], model.lat.sites) 

697 ham = sp.csr_matrix(model.ham, dtype='c16') 

698 positions = model._coords() 

699 leads, laws = [], [] 

700 error_handling.hermitian_matrix(ham, leads) 

701 kwant = _import('kwant') 

702 tinyarray = _import('tinyarray') 

703 family = _site_family(kwant, tinyarray, positions, 'device') 

704 builder = kwant.Builder() 

705 sites = [family(i) for i in range(ham.shape[0])] 

706 _fill(builder, sites, sp.csr_matrix(ham)) 

707 for l, ((h0, v, tau, lead_sites), law) in enumerate(zip(leads, laws)): 

708 centre = positions[lead_sites].mean(axis=0) 

709 cell_family = _site_family(kwant, tinyarray, np.repeat(centre[None], len(h0), axis=0), 'lead{}'.format(l)) 

710 cell = [cell_family(q) for q in range(len(h0))] 

711 _fill(builder, cell, sp.csr_matrix(h0)) 

712 for p, s in enumerate(lead_sites): 

713 for q in np.flatnonzero(tau[p]): 

714 builder[sites[s], cell[q]] = complex(tau[p, q]) 

715 builder.leads.append(kwant.builder.ModesLead(_modes(kwant, h0, v, law), cell, ())) 

716 return builder 

717 

718 

719def _fill(builder: Any, sites: list, ham: sp.csr_matrix) -> None: 

720 ''' 

721 Private function. Set the onsite energies and the hoppings (one 

722 triangle; Kwant adds the conjugates) of the Hermitian *ham* on *sites*. 

723 ''' 

724 diag = ham.diagonal() 

725 for i, site in enumerate(sites): 

726 builder[site] = complex(diag[i]) 

727 upper = sp.triu(ham, 1).tocoo() 

728 for i, j, t in zip(upper.row, upper.col, upper.data): 

729 builder[sites[i], sites[j]] = complex(t) 

730 

731 

732def _modes(kwant: Any, h0: NDArray[np.complex128], v: NDArray[np.complex128], 

733 law: list | None) -> Callable: 

734 r''' 

735 Private function. The modes function of a Kwant ``ModesLead`` for the 

736 lead :math:`(h_0, v)`: Kwant's hopping towards the scattering region is 

737 :math:`\langle n|H|n-1\rangle = v^\dagger`. 

738 ''' 

739 symmetry = None if law is None else kwant.physics.DiscreteSymmetry( 

740 projectors=[sp.csr_matrix(p) for p in law]) 

741 

742 def modes(energy, args=(), *, params=None): 

743 return kwant.physics.modes(h0 - energy * np.eye(len(h0)), v.conj().T, discrete_symmetry=symmetry) 

744 return modes 

745 

746 

747def from_kwant(fsys: Any, params: dict | None = None) -> tuple[sp.csr_matrix, NDArray[np.float64]]: 

748 r''' 

749 Get the Hamiltonian matrix and the orbital positions of a finalized 

750 Kwant system (``builder.finalized()``), with the parameters *params* of 

751 its value functions. Its leads are not imported (attach tbkit leads to 

752 the result with *Transport*). Build a **Transport** (``Transport(ham)``) 

753 or a *System* from them. 

754 

755 Parameters 

756 ---------- 

757 fsys : ``kwant.system.FiniteSystem`` 

758 Finalized, finite. 

759 params : Dictionary or None, default None 

760 Passed to ``hamiltonian_submatrix``. 

761 

762 Returns 

763 ------- 

764 ham : Sparse CSR complex matrix 

765 positions : Real ndarray, shape (n_orbitals, space dimension) 

766 The position of the site of each orbital. 

767 ''' 

768 error_handling.kwant_finite(fsys) 

769 ham = sp.csr_matrix(fsys.hamiltonian_submatrix(sparse=True, params=params), dtype='c16') 

770 pos = np.array([np.asarray(s.pos, dtype='f8') for s in fsys.sites]) 

771 counts = np.ones(len(pos), dtype=int) 

772 if getattr(fsys, 'site_ranges', None) is not None: 

773 ranges = np.asarray(fsys.site_ranges) 

774 counts = np.repeat(ranges[:-1, 1], np.diff(ranges[:, 0])) 

775 error_handling.kwant_orbitals(int(counts.sum()), ham.shape[0]) 

776 return ham, np.repeat(pos, counts, axis=0)