-
Notifications
You must be signed in to change notification settings - Fork 27
/
_tb_model.py
2119 lines (1909 loc) · 80.9 KB
/
_tb_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <[email protected]>
# pylint: disable=too-many-lines,invalid-name
"""
Implements the Model class, which describes a tight-binding model.
"""
from __future__ import annotations
import re
import os
import copy
import time
import warnings
import itertools
import contextlib
import typing as ty
import collections as co
import h5py
import numpy as np
import scipy.linalg as la
from scipy.special import factorial
from fsc.export import export
from fsc.hdf5_io import subscribe_hdf5, HDF5Enabled
if ty.TYPE_CHECKING:
# Replace with typing.Literal once Python 3.7 support is dropped.
from typing_extensions import Literal
import symmetry_representation # pylint: disable=unused-import
from .kdotp import KdotpModel
from .exceptions import (
TbmodelsException,
ParseExceptionMarker,
SymmetrizeExceptionMarker,
)
from . import _check_compatibility
from . import _sparse_matrix as sp
__all__ = ("Model",)
HoppingType = ty.Dict[ty.Tuple[int, ...], ty.Any]
@export
@subscribe_hdf5("tbmodels.model", check_on_load=False)
class Model(HDF5Enabled):
"""
A class describing a tight-binding model. It contains methods for modifying the model, evaluating the Hamiltonian or eigenvalues at specific k-points, and writing to and from different file formats.
Parameters
----------
on_site :
On-site energy of the states. This is equivalent to having a
hopping within the same state and the same unit cell (diagonal
terms of the R=(0, 0, 0) hopping matrix). The length of the list
must be the same as the number of states.
hop :
Hopping matrices, as a dict containing the corresponding lattice
vector R as a key.
size :
Number of states. Defaults to the size of the hopping matrices,
if such are given.
dim :
Dimension of the tight-binding model. By default, the dimension
is guessed from the other parameters if possible.
occ :
Number of occupied states.
pos :
Positions of the orbitals, in reduced coordinates. By default,
all orbitals are set to be at the origin, i.e. at [0., 0., 0.].
uc :
Unit cell of the system. The unit cell vectors are given as rows
in a ``dim`` x ``dim`` array
contains_cc :
Specifies whether the hopping matrices and on-site energies are
given fully (``contains_cc=True``), or the complex conjugate
should be added for each term to obtain the full model. The
``on_site`` parameter is not affected by this.
cc_check_tolerance :
Tolerance when checking if the complex conjugate values (if
given) match.
sparse :
Specifies whether the hopping matrices should be saved in sparse
format.
"""
def __init__(
self,
*,
on_site: ty.Optional[ty.Sequence[float]] = None,
hop: ty.Optional[HoppingType] = None,
size: ty.Optional[int] = None,
dim: ty.Optional[int] = None,
occ: ty.Optional[int] = None,
pos: ty.Optional[ty.Sequence[ty.Sequence[float]]] = None,
uc: ty.Optional[np.ndarray] = None,
contains_cc: bool = True,
cc_check_tolerance: float = 1e-12,
sparse: bool = False,
):
if hop is None:
hop = dict()
# ---- SPARSITY ----
self._sparse: bool
self._matrix_type: ty.Callable[..., ty.Any]
self.set_sparse(sparse)
# ---- SIZE ----
self._init_size(size=size, on_site=on_site, hop=hop, pos=pos)
# ---- DIMENSION ----
self._init_dim(dim=dim, hop=hop, pos=pos, uc=uc)
# ---- UNIT CELL ----
self.uc = None if uc is None else np.array(uc) # implicit copy
# ---- HOPPING TERMS AND POSITIONS ----
self._init_hop_pos(
on_site=on_site,
hop=hop,
pos=pos,
contains_cc=contains_cc,
cc_check_tolerance=cc_check_tolerance,
)
# ---- CONSISTENCY CHECK FOR SIZE ----
self._check_size_hop()
# ---- CONSISTENCY CHECK FOR DIM ----
self._check_dim()
# ---- OCCUPATION NR ----
self.occ = None if (occ is None) else int(occ)
# ---------------- INIT HELPER FUNCTIONS --------------------------------#
def _init_size(self, size, on_site, hop, pos):
"""
Sets the size of the system (number of orbitals).
"""
if size is not None:
self.size = size
elif on_site is not None:
self.size = len(on_site)
elif pos is not None:
self.size = len(pos)
elif hop:
self.size = next(iter(hop.values())).shape[0]
else:
raise ValueError(
"Empty hoppings dictionary supplied and no size, on-site energies or positions given. Cannot determine the size of the system."
)
def _init_dim(self, dim, hop, pos, uc):
r"""
Sets the system's dimensionality.
"""
if dim is not None:
self.dim = dim
elif pos is not None:
self.dim = len(pos[0])
elif hop:
self.dim = len(next(iter(hop.keys())))
elif uc is not None:
self.dim = len(uc[0])
else:
raise ValueError(
"No dimension specified and no positions, hoppings, or unit cell are given. The dimensionality of the system cannot be determined."
)
self._zero_vec = tuple([0] * self.dim)
def _init_hop_pos(self, on_site, hop, pos, contains_cc, cc_check_tolerance):
"""
Sets the hopping terms and positions, mapping the positions to the UC (and changing the hoppings accordingly) if necessary.
"""
# The double-constructor is needed to avoid a double-constructor in the sparse to-array
# but still allow for the dtype argument.
hop = {
tuple(key): self._matrix_type(self._matrix_type(value), dtype=complex)
for key, value in hop.items()
}
# positions
if pos is None:
self.pos = np.zeros((self.size, self.dim))
elif len(pos) == self.size and all(len(p) == self.dim for p in pos):
pos, hop = self._map_to_uc(pos, hop)
self.pos = np.array(pos) # implicit copy
else:
if len(pos) != self.size:
raise ValueError(
"Invalid argument for 'pos': The number of positions must be the same as the size (number of orbitals) of the system."
)
raise ValueError(
"Invalid argument for 'pos': The length of each position must be the same as the dimensionality of the system."
)
if contains_cc:
hop = self._reduce_hop(hop, cc_check_tolerance=cc_check_tolerance)
else:
hop = self._map_hop_positive_R(hop)
# use partial instead of lambda to allow for pickling
self.hop = co.defaultdict(self._empty_matrix)
for R, h_mat in hop.items():
if not np.any(h_mat):
continue
self.hop[R] = self._matrix_type(h_mat)
# add on-site terms
if on_site is not None:
if len(on_site) != self.size:
raise ValueError(
"The number of on-site energies {} does not match the size of the system {}".format(
len(on_site), self.size
)
)
self.hop[self._zero_vec] += 0.5 * self._matrix_type(np.diag(on_site))
# helpers for _init_hop_pos
def _map_to_uc(self, pos, hop):
"""
hoppings in csr format
"""
uc_offsets = [np.array(np.floor(p), dtype=int) for p in pos]
# ---- common case: already mapped into the UC ----
if all([all(o == 0 for o in offset) for offset in uc_offsets]):
return pos, hop
# ---- uncommon case: handle mapping ----
new_pos = [np.array(p) % 1 for p in pos]
new_hop = co.defaultdict(
lambda: np.zeros((self.size, self.size), dtype=complex)
)
for R, hop_mat in hop.items():
hop_mat = np.array(hop_mat)
for i0, row in enumerate(hop_mat):
for i1, t in enumerate(row):
if t != 0:
R_new = tuple(
np.array(R, dtype=int) + uc_offsets[i1] - uc_offsets[i0]
)
new_hop[R_new][i0][i1] += t
new_hop = {key: self._matrix_type(value) for key, value in new_hop.items()}
return new_pos, new_hop
@staticmethod
def _reduce_hop(hop, cc_check_tolerance):
"""
Reduce the full hoppings representation (with cc) to the reduced one (without cc, zero-terms halved).
"""
# Consistency checks
failed_R = []
res = dict()
for R, mat in hop.items():
equiv_mat = hop.get(tuple(-x for x in R), np.zeros(mat.shape)).T.conjugate()
diff_norm = la.norm(mat - equiv_mat)
if diff_norm > cc_check_tolerance:
failed_R.append((R, diff_norm))
avg_mat = (mat + equiv_mat) / 2
try:
if R[np.nonzero(R)[0][0]] > 0:
res[R] = avg_mat
# Case R = 0
except IndexError:
res[R] = avg_mat / 2
if failed_R:
raise ValueError(
"The provided hoppings do not correspond to a hermitian Hamiltonian. hoppings[-R] = hoppings[R].H is not fulfilled for the following values:\n"
+ "\n".join(
f"R={R}, delta_norm={diff_norm}"
for R, diff_norm in sorted(failed_R, key=lambda val: -val[1])
)
)
return res
def _map_hop_positive_R(self, hop: HoppingType) -> HoppingType:
"""
Maps hoppings with a negative first non-zero index in R to their positive counterpart.
"""
new_hop: HoppingType = co.defaultdict(self._empty_matrix)
for R, mat in hop.items():
try:
if R[np.nonzero(R)[0][0]] > 0:
new_hop[R] += mat
else:
minus_R = tuple(-x for x in R)
new_hop[minus_R] += mat.transpose().conjugate()
except IndexError:
# make sure the zero term is also hermitian
# This only really needed s.t. the representation is unique.
# The Hamiltonian is anyway made hermitian later.
new_hop[R] += 0.5 * mat + 0.5 * mat.conjugate().transpose()
return new_hop
# end helpers for _init_hop_pos
def _check_size_hop(self):
"""
Consistency check for the size of the hopping matrices.
"""
for h_mat in self.hop.values():
if not h_mat.shape == (self.size, self.size):
raise ValueError(
"Hopping matrix of shape {0} found, should be ({1},{1}).".format(
h_mat.shape, self.size
)
)
def _check_dim(self):
"""Consistency check for the dimension of the hoppings and unit cell. The position is checked in _init_hop_pos"""
for key in self.hop.keys():
if len(key) != self.dim:
raise ValueError(
"The length of R = {} does not match the dimensionality of the system ({})".format(
key, self.dim
)
)
if self.uc is not None:
if self.uc.shape != (self.dim, self.dim):
raise ValueError(
"Inconsistend dimension of the unit cell: {}, does not match the dimensionality of the system ({})".format(
self.uc.shape, self.dim
)
)
# ---------------- CONSTRUCTORS / (DE)SERIALIZATION ----------------#
@classmethod
def from_hop_list(
cls,
*,
hop_list: ty.Iterable[ty.Tuple[complex, int, int, ty.Tuple[int, ...]]] = (),
size: ty.Optional[int] = None,
**kwargs,
) -> Model:
"""
Create a :class:`.Model` from a list of hopping terms.
Parameters
----------
hop_list :
List of hopping terms. Each hopping term has the form
[t, orbital_1, orbital_2, R], where
* ``t``: strength of the hopping
* ``orbital_1``: index of the first involved orbital
* ``orbital_2``: index of the second involved orbital
* ``R``: lattice vector of the unit cell containing the second orbital.
size :
Number of states. Defaults to the length of the on-site energies given, if such are given.
kwargs :
Any :class:`.Model` keyword arguments.
"""
if size is None:
try:
size = len(kwargs["on_site"])
except KeyError as exc:
raise ValueError(
"No on-site energies and no size given. The size of the system cannot be determined."
) from exc
class _hop:
"""
POD for hoppings
"""
def __init__(self):
self.data = []
self.row_idx = []
self.col_idx = []
def append(self, data, row_idx, col_idx):
self.data.append(data)
self.row_idx.append(row_idx)
self.col_idx.append(col_idx)
# create data, row_idx, col_idx for setting up the CSR matrices
hop_list_dict: ty.Mapping[ty.Tuple[int, ...], _hop] = co.defaultdict(_hop)
R: ty.Tuple[int, ...]
for t, i, j, R in hop_list:
R_vec = tuple(R)
hop_list_dict[R_vec].append(t, i, j)
# creating CSR matrices
hop_dict = dict()
for key, val in hop_list_dict.items():
hop_dict[key] = sp.csr(
(val.data, (val.row_idx, val.col_idx)),
dtype=complex,
shape=(size, size),
)
return cls(size=size, hop=hop_dict, **kwargs)
@staticmethod
def _read_hr(iterator, ignore_orbital_order=False):
r"""
read the number of wannier functions and the hopping entries
from *hr.dat and converts them into the right format
"""
next(iterator) # skip first line
num_wann = int(next(iterator))
nrpts = int(next(iterator))
# get degeneracy points
deg_pts = []
# order in zip important because else the next data element is consumed
for _, line in zip(range(int(np.ceil(nrpts / 15))), iterator):
deg_pts.extend(int(x) for x in line.split())
assert len(deg_pts) == nrpts
num_wann_square = num_wann ** 2
def to_entry(line, i):
"""Turns a line (string) into a hop_list entry"""
entry = line.split()
orbital_a = int(entry[3]) - 1
orbital_b = int(entry[4]) - 1
# test consistency of orbital numbers
if not ignore_orbital_order:
if not (orbital_a == i % num_wann) and (
orbital_b == (i % num_wann_square) // num_wann
):
raise ValueError(f"Inconsistent orbital numbers in line '{line}'")
return [
(float(entry[5]) + 1j * float(entry[6]))
/ (deg_pts[i // num_wann_square]),
orbital_a,
orbital_b,
[int(x) for x in entry[:3]],
]
# skip random empty lines
lines_nonempty = (l for l in iterator if l.strip())
hop_list = (to_entry(line, i) for i, line in enumerate(lines_nonempty))
return num_wann, hop_list
def to_hr_file(self, hr_file: str) -> None:
"""
Writes to a file, using Wannier90's ``*_hr.dat`` format.
Parameters
----------
hr_file :
Path of the output file
.. note :: The ``*_hr.dat`` format does not contain information
about the position of the atoms or the shape of the unit
cell. Consequently, this information is lost when saving the
model in this format.
.. warning :: The ``*_hr.dat`` format does not preserve the full
precision of the hopping strengths. This could lead to
numerical errors.
"""
with open(hr_file, "w") as f:
f.write(self.to_hr())
def to_hr(self) -> str:
"""
Returns a string containing the model in Wannier90's
``*_hr.dat`` format.
.. note :: The ``*_hr.dat`` format does not contain information about the position of the atoms or the shape of the unit cell. Consequently, this information is lost when saving the model in this format.
.. warning :: The ``*_hr.dat`` format does not preserve the full precision of the hopping strengths. This could lead to numerical errors.
"""
lines = []
tagline = " created by the TBmodels package " + time.strftime(
"%a, %d %b %Y %H:%M:%S %Z"
)
lines.append(tagline)
lines.append(f"{self.size:>12}")
num_g = len(self.hop.keys()) * 2 - 1
if num_g <= 0:
raise ValueError("Cannot print empty model to hr format.")
lines.append(f"{num_g:>12}")
tmp = ""
for i in range(num_g):
if tmp != "" and i % 15 == 0:
lines.append(tmp)
tmp = ""
tmp += " 1"
lines.append(tmp)
# negative
for R in reversed(sorted(self.hop.keys())):
if R != self._zero_vec:
minus_R = tuple(-x for x in R)
lines.extend(
self._mat_to_hr(minus_R, self.hop[R].conjugate().transpose())
)
# zero
if self._zero_vec in self.hop.keys():
lines.extend(
self._mat_to_hr(
self._zero_vec,
self.hop[self._zero_vec]
+ self.hop[self._zero_vec].conjugate().transpose(),
)
)
# positive
for R in sorted(self.hop.keys()):
if R != self._zero_vec:
lines.extend(self._mat_to_hr(R, self.hop[R]))
return "\n".join(lines)
@staticmethod
def _mat_to_hr(R, mat):
"""
Creates the ``*_hr.dat`` string for a single hopping matrix.
"""
lines = []
mat = np.array(mat).T # to be consistent with W90's ordering
for j, column in enumerate(mat):
for i, t in enumerate(column):
lines.append(
"{0[0]:>5}{0[1]:>5}{0[2]:>5}{1:>5}{2:>5}{3.real:>22.14f}{3.imag:>22.14f}".format(
R, i + 1, j + 1, t
)
)
return lines
@classmethod
def from_wannier_folder(
cls, folder: str = ".", prefix: str = "wannier", **kwargs
) -> Model:
"""
Create a :class:`.Model` instance from Wannier90 output files,
given the folder containing the files and file prefix.
Parameters
----------
folder :
Directory containing the Wannier90 output files.
prefix :
Prefix of the Wannier90 output files.
kwargs :
Keyword arguments passed to :meth:`.from_wannier_files`. If
input files are explicitly given, they take precedence over
those found in the ``folder``.
"""
common_path = os.path.join(folder, prefix)
input_files = dict()
input_files["hr_file"] = common_path + "_hr.dat"
for key, suffix in [
("win_file", ".win"),
("wsvec_file", "_wsvec.dat"),
("xyz_file", "_centres.xyz"),
]:
filename = common_path + suffix
if os.path.isfile(filename):
input_files[key] = filename
return cls.from_wannier_files(**co.ChainMap(kwargs, input_files))
@classmethod # noqa: MC0001
def from_wannier_files( # pylint: disable=too-many-locals
cls,
*,
hr_file: str,
wsvec_file: ty.Optional[str] = None,
xyz_file: ty.Optional[str] = None,
win_file: ty.Optional[str] = None,
h_cutoff: float = 0.0,
ignore_orbital_order: bool = False,
pos_kind: str = "wannier",
distance_ratio_threshold: float = 3.0,
**kwargs,
) -> Model:
"""
Create a :class:`.Model` instance from Wannier90 output files.
Parameters
----------
hr_file :
Path of the ``*_hr.dat`` file. Together with the
``*_wsvec.dat`` file, this determines the hopping terms.
wsvec_file :
Path of the ``*_wsvec.dat`` file. This file determines the
remapping of hopping terms when ``use_ws_distance`` is used
in the Wannier90 calculation.
xyz_file :
Path of the ``*_centres.xyz`` file. This file is used to
determine the positions of the orbitals, from the Wannier
centers given by Wannier90.
win_file :
Path of the ``*.win`` file. This file is used to determine
the unit cell.
h_cutoff :
Cutoff value for the hopping strength. Hoppings with a
smaller absolute value are ignored.
ignore_orbital_order :
Do not throw an error when the order of orbitals does not
match what is expected from the Wannier90 output.
pos_kind :
Determines how positions are assinged to orbitals. Valid
options are `wannier` (use Wannier centres) or
`nearest_atom` (map to nearest atomic position).
distance_ratio_threshold :
[Applies only for pos_kind='nearest_atom']
The minimum ratio between the second-nearest and nearest
atom below which an error will be raised.
kwargs :
:class:`.Model` keyword arguments.
"""
if win_file is not None:
if "uc" in kwargs:
raise ValueError(
"Ambiguous unit cell: It can be given either via 'uc' or the 'win_file' keywords, but not both."
)
with open(win_file) as f:
kwargs["uc"] = cls._read_win(f)["unit_cell_cart"]
if xyz_file is not None:
if "pos" in kwargs:
raise ValueError(
"Ambiguous orbital positions: The positions can be given either via the 'pos' or the 'xyz_file' keywords, but not both."
)
if "uc" not in kwargs:
raise ValueError(
"Positions cannot be read from .xyz file without unit cell given: Transformation from cartesian to reduced coordinates not possible. Specify the unit cell using one of the keywords 'uc' or 'win_file'."
)
with open(xyz_file) as f:
wannier_pos_list_cartesian, atom_list_cartesian = cls._read_xyz(f)
wannier_pos_cartesian = np.array(wannier_pos_list_cartesian)
atom_pos_cartesian = np.array([a.pos for a in atom_list_cartesian])
if pos_kind == "wannier":
pos_cartesian: ty.Union[
ty.List[np.ndarray], np.ndarray
] = wannier_pos_cartesian
elif pos_kind == "nearest_atom":
if distance_ratio_threshold < 1:
raise ValueError(
"Invalid value for 'distance_ratio_threshold': must be >= 1."
)
pos_cartesian = ty.cast(ty.List[np.ndarray], [])
for p in wannier_pos_cartesian:
p_reduced = la.solve(kwargs["uc"].T, np.array(p).T).T
T_base = np.floor(p_reduced)
all_atom_pos = np.array(
[
kwargs["uc"].T @ (T_base + T_shift) + atom_pos
for atom_pos in atom_pos_cartesian
for T_shift in itertools.product([-1, 0, 1], repeat=3)
]
)
distances = la.norm(p - all_atom_pos, axis=-1)
idx = np.argpartition(distances, 2)[:2]
nearest, second_nearest = distances[idx]
if second_nearest / nearest < distance_ratio_threshold:
raise TbmodelsException(
f"The ratio ({second_nearest / nearest:.3f}) between "
f"the nearest ({nearest:.3f}) and second-nearest "
f"({second_nearest:.3f}) atomic position is less than "
f"'distance_ratio_threshold' ({distance_ratio_threshold}).",
exception_marker=ParseExceptionMarker.AMBIGUOUS_NEAREST_ATOM_POSITIONS,
)
pos_cartesian.append(all_atom_pos[idx[0]])
else:
raise ValueError(
"Invalid value '{}' for 'pos_kind', must be 'wannier' or 'nearest_atom'".format(
pos_kind
)
)
kwargs["pos"] = la.solve(kwargs["uc"].T, np.array(pos_cartesian).T).T
with open(hr_file) as f:
num_wann, hop_entries = cls._read_hr(
f, ignore_orbital_order=ignore_orbital_order
)
hop_entries = (hop for hop in hop_entries if abs(hop[0]) > h_cutoff)
if wsvec_file is not None:
with open(wsvec_file) as f:
wsvec_generator = cls._async_parse(
cls._read_wsvec(f), chunksize=num_wann
)
def remap_hoppings(hop_entries):
for t, orbital_1, orbital_2, R in hop_entries:
# Step _async_parse to where it accepts
# a new key.
# The _async_parse does not raise StopIteration
next( # pylint: disable=stop-iteration-return
wsvec_generator
)
T_list = wsvec_generator.send(
(orbital_1, orbital_2, tuple(R))
)
N = len(T_list)
for T in T_list:
# not using numpy here increases performance
yield (
t / N,
orbital_1,
orbital_2,
tuple(r + t for r, t in zip(R, T)),
)
hop_entries = remap_hoppings(hop_entries)
return cls.from_hop_list(
size=num_wann, hop_list=hop_entries, **kwargs
)
return cls.from_hop_list(size=num_wann, hop_list=hop_entries, **kwargs)
@staticmethod
def _async_parse(iterator, chunksize=1):
"""
Helper function to get values from a (key, value) iterator
out of order without having to exhaust the iterator from the start.
The desired key needs to be sent to this generator, and it
will go through the `iterator` until that key is found. Pairs
for which the key has not yet been requested are stored in a
temporary dictionary.
Note that this generator never raises StopIteration, it can
only exit with KeyError.
"""
mapping = dict()
stopped = False
while True:
# get the desired key
key = yield
while True:
try:
# key found
yield mapping.pop(key)
break
except KeyError as e:
if stopped:
# avoid infinte loop in true KeyError
raise e
for _ in range(chunksize):
try:
# parse new data
newkey, newval = next(iterator)
mapping[newkey] = newval
except StopIteration:
stopped = True
break
@staticmethod
def _read_wsvec(iterator):
"""
Generator that parses the content of the *_wsvec.dat file.
"""
# skip comment line
try:
next(iterator)
except StopIteration as exc:
raise TbmodelsException(
"The 'wsvec' iterator is empty.",
exception_marker=ParseExceptionMarker.INCOMPLETE_WSVEC_FILE,
) from exc
for first_line in iterator:
*R, o1, o2 = (int(x) for x in first_line.split())
# in our convention, orbital indices start at 0.
key = (o1 - 1, o2 - 1, tuple(R))
try:
N = int(next(iterator))
val = [tuple(int(x) for x in next(iterator).split()) for _ in range(N)]
except StopIteration as exc:
raise TbmodelsException(
"Incomplete wsvec iterator.",
exception_marker=ParseExceptionMarker.INCOMPLETE_WSVEC_FILE,
) from exc
yield key, val
@staticmethod
def _read_xyz(iterator):
"""Reads the content of a .xyz file"""
# This functionality exists within pymatgen, so it might make sense
# to use that if we anyway want pymatgen as a dependency.
N = int(next(iterator))
next(iterator) # skip comment line
wannier_centres = []
atom_positions = []
AtomPosition = co.namedtuple("AtomPosition", ["kind", "pos"])
for l in iterator:
kind, *pos = l.split()
pos = tuple(float(x) for x in pos)
if kind == "X":
wannier_centres.append(pos)
else:
atom_positions.append(AtomPosition(kind=kind, pos=pos))
assert len(wannier_centres) + len(atom_positions) == N
return wannier_centres, atom_positions
@staticmethod
def _read_win(iterator):
"""
Takes an iterator representing the Wannier90 .win file lines,
and returns a mapping of its content.
"""
lines = (l.split("!")[0] for l in iterator)
lines = (l.strip() for l in lines)
lines = (l for l in lines if l)
lines = (l.lower() for l in lines)
split_token = re.compile("[\t :=]+")
mapping = {}
for line in lines:
if line.startswith("begin"):
key = split_token.split(line[5:].strip(" :="), 1)[0]
val = []
while True:
line = next(lines)
if line.startswith("end"):
end_key = split_token.split(line[3:].strip(" :="), 1)[0]
assert end_key == key
break
val.append(line)
mapping[key] = val
else:
key, val = split_token.split(line, 1)
mapping[key] = val
# here we can continue parsing the individual keys as needed
if "length_unit" in mapping:
length_unit = mapping["length_unit"].strip().lower()
else:
length_unit = "ang"
mapping["length_unit"] = length_unit
if "unit_cell_cart" in mapping:
uc_input = mapping["unit_cell_cart"]
# handle the case when the unit is explicitly given
if len(uc_input) == 4:
unit, *uc_input = uc_input
# unit = unit[0]
else:
unit = length_unit
val = [[float(x) for x in split_token.split(line)] for line in uc_input]
val = np.array(val).reshape(3, 3)
if unit == "bohr":
val *= 0.52917721092
mapping["unit_cell_cart"] = val
return mapping
def to_kwant_lattice(self):
"""
Returns a kwant lattice corresponding to the current model. Orbitals with the same position are grouped into the same Monoatomic sublattice.
.. note :: The TBmodels - Kwant interface is experimental. Use it with caution.
"""
import kwant # pylint: disable=import-outside-toplevel
sublattices = self._get_sublattices()
uc = self.uc if self.uc is not None else np.eye(self.dim)
# get sublattice positions in cartesian coordinates
pos_abs = np.dot(np.array([sl.pos for sl in sublattices]), uc)
return kwant.lattice.general(prim_vecs=uc, basis=pos_abs)
def add_hoppings_kwant(self, kwant_sys, kwant_sublattices=None):
"""
Sets the on-site energies and hopping terms for an existing kwant system to those of the :class:`.Model`.
.. note :: The TBmodels - Kwant interface is experimental. Use it with caution.
"""
import kwant # pylint: disable=import-outside-toplevel
sublattices = self._get_sublattices()
if kwant_sublattices is None:
kwant_sublattices = self.to_kwant_lattice().sublattices
# handle R = 0 case (on-site)
on_site_mat = copy.deepcopy(self._array_cast(self.hop[self._zero_vec]))
on_site_mat += on_site_mat.conjugate().transpose()
# R = 0 terms within a sublattice (on-site)
for site in kwant_sys.sites():
for i, latt in enumerate(kwant_sublattices):
if site.family == latt:
indices = sublattices[i].indices
kwant_sys[site] = on_site_mat[np.ix_(indices, indices)]
break
# site doesn't belong to any sublattice
else:
# TODO: check if there is a legitimate use case which triggers this
raise ValueError(f"Site {site} did not match any sublattice.")
# R = 0 terms between different sublattices
for i, s1 in enumerate(sublattices):
for j, s2 in enumerate(sublattices[i + 1 :], start=i + 1):
kwant_sys[
kwant.builder.HoppingKind(
self._zero_vec,
kwant_sublattices[i],
kwant_sublattices[j],
)
] = on_site_mat[np.ix_(s1.indices, s2.indices)]
# R != 0 terms
for R, mat in self.hop.items():
mat = self._array_cast(mat)
# special case R = 0 handled already
if R == self._zero_vec:
continue
minus_R = tuple(-np.array(R))
for i, s1 in enumerate(sublattices):
for j, s2 in enumerate(sublattices):
sub_matrix = mat[np.ix_(s1.indices, s2.indices)]
# TODO: check "signs"
kwant_sys[
kwant.builder.HoppingKind(
minus_R, kwant_sublattices[i], kwant_sublattices[j]
)
] = sub_matrix
return kwant_sys
def _get_sublattices(self):
"""
Helper function to group indices of orbitals which have the same
position into sublattices.
"""
Sublattice = co.namedtuple("Sublattice", ["pos", "indices"])
sublattices = []
for i, p_orb in enumerate(self.pos):
# try to match an existing sublattice
for sub_pos, sub_indices in sublattices:
if np.isclose(p_orb, sub_pos, rtol=0).all():
sub_indices.append(i)
break
# create new sublattice
else:
sublattices.append(Sublattice(pos=p_orb, indices=[i]))
return sublattices
def construct_kdotp(self, k: ty.Sequence[float], order: int):
"""
Construct a k.p model around a given k-point. This is done by explicitly
evaluating the derivatives which make up the Taylor expansion of the k.p
models.
This method can currently only construct models using
`convention 2 <http://www.physics.rutgers.edu/pythtb/_downloads/pythtb-formalism.pdf>`_
for the Hamiltonian.
Parameters
----------
k :
The k-point around which the k.p model is constructed.
order :
The order (sum of powers) to which the Taylor expansion is
performed.
"""
taylor_coefficients = dict()
if order < 0:
raise ValueError("The order for the k.p model must be positive.")
k_powers: ty.Tuple[int, ...]
for k_powers in itertools.product(range(order + 1), repeat=self.dim):
curr_order = sum(k_powers)
if curr_order > order:
continue
taylor_coefficients[k_powers] = (
(2j * np.pi) ** curr_order / np.prod(factorial(k_powers, exact=True))
) * sum(
(
np.prod(np.array(R) ** np.array(k_powers))
* np.exp(2j * np.pi * np.dot(k, R))
* self._array_cast(mat)
+ np.prod((-np.array(R)) ** np.array(k_powers))
* np.exp(-2j * np.pi * np.dot(k, R))
* self._array_cast(mat).T.conj()
for R, mat in self.hop.items()
),
np.zeros((self.size, self.size), dtype=complex),
)
return KdotpModel(taylor_coefficients=taylor_coefficients)
@classmethod
def from_hdf5_file( # pylint: disable=arguments-differ
cls, hdf5_file: str, **kwargs
) -> Model:
"""
Returns a :class:`.Model` instance read from a file in HDF5
format.
Parameters
----------
hdf5_file :
Path of the input file.
kwargs :
:class:`.Model` keyword arguments. Explicitly specified
keywords take precedence over those given in the HDF5 file.
"""