Reference¶
Contents
Model Class¶

class
tbmodels.
Model
(*, on_site: Optional[Sequence[float]] = None, hop: Optional[Dict[Tuple[int, …], Any]] = None, size: Optional[int] = None, dim: Optional[int] = None, occ: Optional[int] = None, pos: Optional[Sequence[Sequence[float]]] = None, uc: Optional[numpy.ndarray] = None, contains_cc: bool = True, cc_check_tolerance: float = 1e12, sparse: bool = False)[source]¶ A class describing a tightbinding model. It contains methods for modifying the model, evaluating the Hamiltonian or eigenvalues at specific kpoints, and writing to and from different file formats.
 Parameters
on_site – Onsite 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 tightbinding 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
xdim
arraycontains_cc – Specifies whether the hopping matrices and onsite energies are given fully (
contains_cc=True
), or the complex conjugate should be added for each term to obtain the full model. Theon_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.

__add__
(model: tbmodels._tb_model.Model) → tbmodels._tb_model.Model[source]¶ Adds two models together by adding their hopping terms.

__sub__
(model: tbmodels._tb_model.Model) → tbmodels._tb_model.Model[source]¶ Substracts one model from another by substracting all hopping terms.

add_hop
(overlap: complex, orbital_1: int, orbital_2: int, R: Sequence[int])[source]¶ Adds a hopping term with a given overlap (hopping strength) from
orbital_2
(\(o_2\)), which lies in the unit cell pointed to byR
, toorbital_1
(\(o_1\)) which is in the home unit cell. In other words,overlap
is the matrix element \(\mathcal{H}_{o_1,o_2}(\mathbf{R}) = \langle o_1, \mathbf{0}  \mathcal{H}  o_2, \mathbf{R} \rangle\).The complex conjugate of the hopping is added automatically. That is, the matrix element \(\langle o_2, \mathbf{R}  \mathcal{H}  o_1, \mathbf{0} \rangle\) does not have to be added manually.
Note
This means that adding a hopping of overlap \(\epsilon\) between an orbital and itself in the home unit cell increases the orbitals onsite energy by \(2 \epsilon\).
 Parameters
overlap – Strength of the hopping term (in energy units).
orbital_1 – Index of the first orbital.
orbital_2 – Index of the second orbital.
R – Lattice vector pointing to the unit cell where
orbital_2
lies.
Warning
The positions given in the constructor of
Model
are automatically mapped into the home unit cell. This has to be taken into account when determiningR
.

add_hoppings_kwant
(kwant_sys)[source]¶ Sets the onsite energies and hopping terms for an existing kwant system to those of the
Model
.Note
The TBmodels  Kwant interface is experimental. Use it with caution.

add_on_site
(on_site: Sequence[float])[source]¶ Adds onsite energy to the orbitals. This adds to the existing onsite energy, and does not erase it.
 Parameters
on_site – Onsite energies. This must be a sequence of real numbers, of the same length as the number of orbitals

change_unit_cell
(*, uc: Optional[Sequence[Sequence[float]]] = None, offset: Sequence[float] = (0, 0, 0), cartesian: bool = False) → tbmodels._tb_model.Model[source]¶ Return a model with a different unit cell of the same volume.
Creates a model with a changed unit cell  with a different shape and / or origin. The new unit cell must be compatible with the current lattice, and have the same volume.
 Parameters
uc – The new unit cell shape. Lattice vectors are given as rows in a (dim x dim) matrix. If no unit cell is given, the current unit cell shape is kept.
offset – The position of the new unit cell origin, relative to the old one.
cartesian – Specifies if the offset and unit cell are in cartesian or reduced coordinates. Reduced coordinates are with respect to the old unit cell.

construct_kdotp
(k: Sequence[float], order: int)[source]¶ Construct a k.p model around a given kpoint. 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 for the Hamiltonian.
 Parameters
k – The kpoint around which the k.p model is constructed.
order – The order (sum of powers) to which the Taylor expansion is performed.

eigenval
(k: Union[Sequence[float], Sequence[Sequence[float]]]) → Union[numpy.ndarray, List[numpy.ndarray]][source]¶ Returns the eigenvalues at a given k point, or list of kpoints.
 Parameters
k – The kpoint at which the Hamiltonian is evaluated. If a list of kpoints is given, a corresponding list of eigenvalue arrays is returned.

fold_model
(*, new_unit_cell: ty.Sequence[ty.Sequence[float]], unit_cell_offset: ty.Sequence[float] = (0, 0, 0), position_tolerance: float = 0.001, unmatched_position_threshold: float = inf, orbital_labels: ty.Sequence[ty.Hashable], target_indices: ty.Optional[ty.Sequence[int]] = None, check_cc: bool = True, check_uc_volume: bool = True, uc_volume_tolerance: float = 1e06, check_orbital_ratio: bool = True, order_by: Literal[‘label’, ‘index’] = 'label') → Model[source]¶ Returns a model with a smaller unit cell. Orbitals which are related by a lattice vector of the new unit cell are “folded” into a single orbital. This is the inverse operation of the supercell construction.
Note
This function is currently experimental, and its interface may still change without warning.
 Parameters
new_unit_cell – The unit cell of the new model. Note that this unit cell must lie completely within the old unit cell.
unit_cell_offset – Position (in cartesian coordinates) at which the new unit cell is based.
position_tolerance – Tolerance used when determining if a position mapped into the new unit cell is the same as an existing orbital position.
unmatched_position_threshold – Threshold above which orbital positions that do not have a matching position in the new model are ignored. The threshold is defined as cartesian distance from the new unit cell origin.
orbital_labels – A list of labels for the orbitals of the current model. This is needed to distinguish between orbitals of the same position when mapping them to the new orbitals.
target_indices – Optional list of indices (in the current model) of the orbitals which lie within the new unit cell. This can be used as a check that the new orbitals are the expected ones.
check_cc – Flag to determine whether the hoppings should be checked for being perfect complex conjugates. This check can fail if the model does not have exact translation symmetry w.r.t. the new unit cell. If set to false, hoppings are averaged to be complex conjugates.
check_uc_volume – Flag to determine if the unit cell volume should decrease by the same factor as the number of orbitals.
uc_volume_tolerance – Absolute tolerance when checking if the unit cell volume change is consistent with the change in number of orbitals.
check_orbital_ratio – Flag to determine if the ratio of individual orbital labels should be checked to be the same as the initial ratio. If this is set to False, the resulting model will always have
occ=None
.order_by – Determines how the orbitals in the new model are ordered. For
order_by="index"
, the orbitals are ordered exactly the same as in the original model. Note that this order will depend on which orbitals end up inside the unit cell. Fororder_by="label"
, the orbitals are ordered according to the occurrence (not the value) of the labels in theorbital_labels
input. Orbitals with the same label are again ordered by index.

classmethod
from_hdf5
(hdf5_handle, **kwargs) → tbmodels._tb_model.Model[source]¶ Deserializes the object stored in HDF5 format.

classmethod
from_hdf5_file
(hdf5_file: str, **kwargs) → tbmodels._tb_model.Model[source]¶ Returns a
Model
instance read from a file in HDF5 format. Parameters
hdf5_file – Path of the input file.
kwargs –
Model
keyword arguments. Explicitly specified keywords take precedence over those given in the HDF5 file.

classmethod
from_hop_list
(*, hop_list: Iterable[Tuple[complex, int, int, Tuple[int, …]]] = (), size: Optional[int] = None, **kwargs) → tbmodels._tb_model.Model[source]¶ Create a
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 hoppingorbital_1
: index of the first involved orbitalorbital_2
: index of the second involved orbitalR
: lattice vector of the unit cell containing the second orbital.
size – Number of states. Defaults to the length of the onsite energies given, if such are given.
kwargs – Any
Model
keyword arguments.

classmethod
from_wannier_files
(*, hr_file: str, wsvec_file: Optional[str] = None, xyz_file: Optional[str] = None, win_file: Optional[str] = None, h_cutoff: float = 0.0, ignore_orbital_order: bool = False, pos_kind: str = 'wannier', distance_ratio_threshold: float = 3.0, **kwargs) → tbmodels._tb_model.Model[source]¶ Create a
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 whenuse_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 secondnearest and nearest atom below which an error will be raised.
kwargs –
Model
keyword arguments.

classmethod
from_wannier_folder
(folder: str = '.', prefix: str = 'wannier', **kwargs) → tbmodels._tb_model.Model[source]¶ Create a
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
from_wannier_files()
. If input files are explicitly given, they take precedence over those found in thefolder
.

hamilton
(k: Union[Sequence[float], Sequence[Sequence[float]]], convention: int = 2) → numpy.ndarray[source]¶ Calculates the Hamilton matrix for a given kpoint or list of kpoints.
 Parameters
k – The kpoint at which the Hamiltonian is evaluated. If a list of kpoints is given, the result will be the corresponding list of Hamiltonians.
convention – Choice of convention to calculate the Hamilton matrix. See explanation in the PythTB documentation . Valid choices are 1 or 2.

classmethod
join_models
(*models: tbmodels._tb_model.Model) → tbmodels._tb_model.Model[source]¶ Creates a tightbinding model which contains all orbitals of the given input models. The orbitals are ordered by model, such that the resulting Hamiltonian is blockdiagonal.
 Parameters
models – Models which should be joined together.

property
reciprocal_lattice
¶ An array containing the reciprocal lattice vectors as rows.

remove_long_range_hop
(*, cutoff_distance_cartesian: float) → None[source]¶ Remove hoppings whose range is longer than the given cutoff.
 Parameters
cutoff_distance_cartesian – Cartesian distance between the two orbitals above which the hoppings are removed.

remove_small_hop
(cutoff: float) → None[source]¶ Remove hoppings which are smaller than the given cutoff value.
 Parameters
cutoff – Cutoff value below which a hopping is removed.

set_sparse
(sparse: bool = True)[source]¶ Defines whether sparse or dense matrices should be used to represent the system, and changes the system accordingly if needed.
 Parameters
sparse – Flag to determine whether the system is set to be sparse (
True
) or dense (False
).

slice_orbitals
(slice_idx: List[int]) → tbmodels._tb_model.Model[source]¶ Returns a new model with only the orbitals as given in the
slice_idx
. This can also be used to reorder the orbitals. Parameters
slice_idx – Orbital indices that will be in the resulting model.

supercell
(size: Sequence[int]) → tbmodels._tb_model.Model[source]¶ Generate a model for a supercell of the current unit cell.
 Parameters
size – The size of the supercell, given as integer multiples of the current lattice vectors

symmetrize
(symmetries: ty.Sequence[symmetry_representation.SymmetryOperation], full_group: bool = False, position_tolerance: float = 1e05) → Model[source]¶ Returns a model which is symmetrized w.r.t. the given symmetries. This is done by performing a group average over the symmetry group.
 Parameters
symmetries – Symmetries which the symmetrized model should respect.
full_group – Specifies whether the given symmetries represent the full symmetry group, or only a subset from which the full symmetry group is generated.
position_tolerance – Absolute tolerance (in reduced coordinates) when matching positions after a symmetry has been applied to existing positions.

to_hdf5
(hdf5_handle)[source]¶ Serializes the object to HDF5 format, attaching it to the given HDF5 handle (might be a HDF5 File or Dataset).

to_hdf5_file
(hdf5_file)¶ Saves the object to a file, in HDF5 format.
 Parameters
hdf5_file (str) – Path of the file.

to_hr
() → str[source]¶ 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.

to_hr_file
(hr_file: str) → None[source]¶ 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.
Helper functions¶
This module contains a helper function to create a list of hoppings from a given matrix (matrix_to_hop()
).

tbmodels.helpers.
matrix_to_hop
(mat: Sequence[Sequence[complex]], orbitals: Optional[Sequence[int]] = None, R: Sequence[int] = (0, 0, 0), multiplier: float = 1.0) → List[Tuple[complex, int, int, numpy.ndarray]][source]¶ Turns a square matrix into a series of hopping terms.
 Parameters
mat – The matrix to be converted.
orbitals – Indices of the orbitals that make up the basis w.r.t. which the matrix is defined. By default (
orbitals=None
), the firstlen(mat)
orbitals are used.R – Lattice vector for all the hopping terms.
multiplier – Multiplicative constant for the hopping strength.
Saving and loading (HDF5)¶
Defines functions for saving and loading in HDF5 format.

tbmodels.io.
load
(file_path)[source]¶ Load TBmodels objects from an HDF5 file. Compatible with all types registered through
fsc.hdf5_io
.

tbmodels.io.
save
(obj, hdf5_file)¶ Save TBmodels objects to a HDF5 file. Compatible with all types registered through
fsc.hdf5_io
.
Command line interface¶
tbmodels¶
tbmodels [OPTIONS] COMMAND [ARGS]...
Options

version
¶
Show the version and exit.
eigenvals¶
Calculate the energy eigenvalues for a given set of kpoints (in reduced coordinates). The input and output is given in an HDF5 file.
tbmodels eigenvals [OPTIONS]
Options

i
,
input
<input>
¶ File containing the input model (in HDF5 format).

k
,
kpoints
<kpoints>
¶ File containing the kpoints for which the eigenvalues are evaluated.

o
,
output
<output>
¶ Output file for the energy eigenvalues.

v
,
verbose
¶
parse¶
Parse Wannier90 output files and create an HDF5 file containing the tightbinding model.
tbmodels parse [OPTIONS]
Options

f
,
folder
<folder>
¶ Directory containing the Wannier90 output files.

p
,
prefix
<prefix>
¶ Common prefix of the Wannier90 output files.

poskind
<pos_kind>
¶ Which position to use for the orbitals.
 Options
wannier  nearest_atom

distanceratiothreshold
<distance_ratio_threshold>
¶

sparsity
<sparsity>
¶ Write the model in sparse format. By default, the format of the input model is used.
 Options
sparse  dense  as_input

v
,
verbose
¶

o
,
output
<output>
¶ Path of the output file.
slice¶
Create a model containing only the orbitals given in the SLICE_IDX.
tbmodels slice [OPTIONS] [SLICE_IDX]...
Options

i
,
input
<input>
¶ File containing the input model (in HDF5 format).

o
,
output
<output>
¶ Output file for the sliced model.

sparsity
<sparsity>
¶ Write the model in sparse format. By default, the format of the input model is used.
 Options
sparse  dense  as_input

v
,
verbose
¶
Arguments

SLICE_IDX
¶
Optional argument(s)
symmetrize¶
Symmetrize tightbinding model with given symmetry group(s).
tbmodels symmetrize [OPTIONS]
Options

i
,
input
<input>
¶ File containing the input model (in HDF5 format).

o
,
output
<output>
¶ Output file for the symmetrized model.

s
,
symmetries
<symmetries>
¶ File containing symmetry_representation.SymmetryGroup objects (in HDF5 form).

f
,
fullgroup
,
nofullgroup
¶
Full group: The full symmetry group is given in the symmetries. No full group: The symmetries only contain a generating subset of the full group. Overrides the option given in the symmetries file (if any).

sparsity
<sparsity>
¶ Write the model in sparse format. By default, the format of the input model is used.
 Options
sparse  dense  as_input

v
,
verbose
¶
k.p Model class¶

class
tbmodels.kdotp.
KdotpModel
(taylor_coefficients: Mapping[Tuple[int, …], Any])[source]¶ A class describing a k.p model.
 Parameters
taylor_coefficients –
A mapping containing the taylor coefficients of the k.p model. The keys are tuples which describe the power of the kvector components, and the values are the corresponding matrices.
 Example:
(1, 0, 2): [[1, 0], [0, 1]] describes k_x * k_z**2 * sigma_z
Exceptions¶
Defines custom exceptions to be used in TBmodels. The main purpose of these custom exceptions is their use in the CLI. Custom exceptions are formatted in the CLI in a way that makes error parsing simple.

class
tbmodels.exceptions.
ExceptionMarker
(value)[source]¶ Base class for markers to be used with
TbmodelsException
exceptions.Note
The exception marker names are considered a public interface and will not be changed in a minor release (although new ones can be added). The values of the exception markers however are informational only, and should not be relied upon.

class
tbmodels.exceptions.
ParseExceptionMarker
(value)[source]¶ Exception markers for errors which can occur while parsing a tightbinding model.

AMBIGUOUS_NEAREST_ATOM_POSITIONS
= 'The nearest atom to use for position parsing is ambiguous.'¶

INCOMPLETE_WSVEC_FILE
= 'The seedname_wsvec.dat file is empty or incomplete.'¶


class
tbmodels.exceptions.
SymmetrizeExceptionMarker
(value)[source]¶ Exception markers for errors which can occur while symmetrizing a tightbinding model.

INVALID_SYMMETRY_TYPE
= 'The type of the given symmetries object is incorrect.'¶

POSITIONS_NOT_SYMMETRIC
= 'The model positions do not respect the given symmetry.'¶


exception
tbmodels.exceptions.
TbmodelsException
(message: str, exception_marker: tbmodels.exceptions.ExceptionMarker)[source]¶ Custom exception class for TBmodels errors. This class should be used only for exception with a wellknown cause, not for unexpected “crashes”. For example, it can be used for malformed or incompatible inputs, truncated or missing input files, and similar errors.
Errors which use this exception class will be formatted in the CLI as:
Error: [<exception marker name>] <error message>

exit_code
= 3¶ The exit code for this exception
