### Import necessary libraries Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Imports TBmodels, Kwant, and other libraries for numerical operations and plotting. Ensure these libraries are installed. ```python import kwant import tbmodels import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' ``` -------------------------------- ### Load Initial Model in TBmodels Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/symmetrize.md Loads the initial tight-binding model using TBmodels. Ensure the path points to your examples directory. ```python from TBmodels import Model model = Model.from_file("nonsymmorphic_Si.model") ``` -------------------------------- ### ParseExceptionMarker Example Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Exception markers for parsing errors in tight-binding models. These indicate issues like ambiguous nearest atom positions or incomplete WSVEC files. ```python class tbmodels.exceptions.ParseExceptionMarker(value) ``` -------------------------------- ### SymmetrizeExceptionMarker Example Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Exception markers for errors during the symmetrization of tight-binding models. These include invalid symmetry types or non-symmetric model positions. ```python class tbmodels.exceptions.SymmetrizeExceptionMarker(value) ``` -------------------------------- ### Get hr.dat Content as String Source: https://context7.com/z2packdev/tbmodels/llms.txt Retrieves the content of the Wannier90 hr.dat file as a string. Only the first 200 characters are printed. ```python # Get hr.dat content as string hr_string = model.to_hr() print(hr_string[:200]) ``` -------------------------------- ### Model Initialization from Wannier90 Files Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Methods to create a Model instance from Wannier90 output files. ```APIDOC ## ClassMethod from_wannier_files ### Description Create a `Model` instance from Wannier90 output files. ### Method `classmethod` ### Endpoint `Model.from_wannier_files()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **hr_file** (str) - Required - Path of the `*_hr.dat` file. Together with the `*_wsvec.dat` file, this determines the hopping terms. * **wsvec_file** (str | None) - Optional - 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** (str | None) - Optional - 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** (str | None) - Optional - Path of the `*.win` file. This file is used to determine the unit cell. * **h_cutoff** (float) - Optional - Cutoff value for the hopping strength. Hoppings with a smaller absolute value are ignored. Defaults to 0.0. * **ignore_orbital_order** (bool) - Optional - Do not throw an error when the order of orbitals does not match what is expected from the Wannier90 output. Defaults to False. * **pos_kind** (str) - Optional - Determines how positions are assigned to orbitals. Valid options are wannier (use Wannier centres) or nearest_atom (map to nearest atomic position). Defaults to 'wannier'. * **distance_ratio_threshold** (float) - Optional - [Applies only for pos_kind=’nearest_atom’] The minimum ratio between the second-nearest and nearest atom below which an error will be raised. Defaults to 3.0. * **kwargs** - Optional - [`Model`](#tbmodels.Model) keyword arguments. ### Request Example ```json { "hr_file": "path/to/_hr.dat", "wsvec_file": "path/to/_wsvec.dat", "xyz_file": "path/to/_centres.xyz", "win_file": "path/to/.win" } ``` ### Response #### Success Response (200) - **Model** (Model) - A Model instance. #### Response Example ```json { "model_instance": "" } ``` ## ClassMethod from_wannier_folder ### Description Create a `Model` instance from Wannier90 output files, given the folder containing the files and file prefix. ### Method `classmethod` ### Endpoint `Model.from_wannier_folder()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **folder** (str) - Optional - Directory containing the Wannier90 output files. Defaults to '.' * **prefix** (str) - Optional - Prefix of the Wannier90 output files. Defaults to 'wannier' * **kwargs** - Optional - Keyword arguments passed to [`from_wannier_files()`](#tbmodels.Model.from_wannier_files). If input files are explicitly given, they take precedence over those found in the `folder`. ### Request Example ```json { "folder": "/path/to/wannier_files", "prefix": "my_calc" } ``` ### Response #### Success Response (200) - **Model** (Model) - A Model instance. #### Response Example ```json { "model_instance": "" } ``` ``` -------------------------------- ### Initialize a tight-binding Model Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Instantiate the Model class to describe a tight-binding system. Parameters like on-site energies, hopping matrices, and unit cell can be provided during initialization. ```python Model(on_site=None, hop=None, size=None, dim=None, occ=None, pos=None, uc=None, contains_cc=True, cc_check_tolerance=1e-12, sparse=False) ``` -------------------------------- ### Initialize Kwant Builder for Finite Wire Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Creates a bare Kwant Builder for a finite wire system, as it lacks translational symmetry. ```python wire = kwant.Builder() ``` -------------------------------- ### Define Shape for Finite Wire Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Defines a function that specifies the spatial boundaries of the finite wire. This example uses a square cross-section. ```python def shape(p): x, y, z = p return -20 < x < 20 and -5 < y < 5 and -5 < z < 5 ``` -------------------------------- ### Create and Manipulate TBmodels Source: https://context7.com/z2packdev/tbmodels/llms.txt Demonstrates basic model creation, arithmetic operations, scaling, slicing orbitals, creating supercells, joining models, changing unit cells, and removing hoppings. ```python model1 = tbmodels.Model(on_site=[1.0, -1.0], dim=3, pos=[[0, 0, 0], [0.5, 0.5, 0]]) model2 = tbmodels.Model(on_site=[0.5, -0.5], dim=3, pos=[[0, 0, 0], [0.5, 0.5, 0]]) ``` ```python model_sum = model1 + model2 model_diff = model1 - model2 ``` ```python model_scaled = 2.0 * model1 model_half = model1 / 2.0 ``` ```python model_sliced = model1.slice_orbitals(slice_idx=[1, 0]) # Swap orbital order model_single = model1.slice_orbitals(slice_idx=[0]) # Keep only first orbital ``` ```python model_2x2x1 = model1.supercell(size=[2, 2, 1]) print(f"Original size: {model1.size}, Supercell size: {model_2x2x1.size}") ``` ```python model_joined = tbmodels.Model.join_models(model1, model2) print(f"Joined model size: {model_joined.size}") ``` ```python model_shifted = model1.change_unit_cell( offset=[0.25, 0.25, 0.0], # Shift origin (reduced coordinates) cartesian=False ) ``` ```python model1.remove_small_hop(cutoff=1e-8) ``` ```python model1.remove_long_range_hop(cutoff_distance_cartesian=5.0) ``` -------------------------------- ### KdotpModel Class Initialization Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Initializes a k.p model using Taylor coefficients. The keys represent the powers of k-vector components, and values are the corresponding matrices. ```python class tbmodels.kdotp.KdotpModel(taylor_coefficients: Mapping[Tuple[int, ...], Any]) ``` -------------------------------- ### Finalize Bulk System with Wraparound Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Applies wraparound to the Kwant system to create a finalized bulk model. This is used for band structure calculations. ```python kwant_model = kwant.wraparound.wraparound(kwant_sys).finalized() ``` -------------------------------- ### Create and Save TB Model to HDF5 Source: https://context7.com/z2packdev/tbmodels/llms.txt Demonstrates creating a tight-binding model and saving it to an HDF5 file, which preserves full precision and metadata. Loading from HDF5 is also shown. ```python import tbmodels # Create a model model = tbmodels.Model( on_site=[1.0, -1.0], dim=3, pos=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.0]], uc=[[3.0, 0, 0], [0, 3.0, 0], [0, 0, 3.0]] ) # Save to HDF5 (recommended - preserves full precision and all metadata) model.to_hdf5_file('model.hdf5') # Load from HDF5 loaded_model = tbmodels.Model.from_hdf5_file('model.hdf5') ``` -------------------------------- ### Initialize Kwant Builder with Symmetry Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Creates a Kwant Builder instance and applies the defined translational symmetry. This builder will represent the bulk system. ```python kwant_sys = kwant.Builder(sym) ``` -------------------------------- ### Create Model from Wannier90 Files Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/tutorial.md Instantiate a TBmodels.Model from Wannier90 output files. Ensure `use_ws_distance = .true.` in Wannier90 for correct results. The `hr_file` is mandatory, while `wsvec_file`, `xyz_file`, and `win_file` are optional but recommended. ```python import tbmodels # use only *_hr.dat model = tbmodels.Model.from_wannier_files(hr_file='path_to_directory/wannier90_hr.dat') # use all files model = tbmodels.Model.from_wannier_files( hr_file='path_to_directory/wannier90_hr.dat', wsvec_file='path_to_directory/wannier90_wsvec.dat', xyz_file='path_to_directory/wannier90_centres.xyz', win_file='path_to_directory/wannier90.win' ) ``` -------------------------------- ### Construct k.p Model from Tight-Binding Model Source: https://context7.com/z2packdev/tbmodels/llms.txt Derives a k.p (effective mass) model by performing a Taylor expansion of the tight-binding model around a specified k-point. The `order` parameter controls the expansion order. ```python import tbmodels import numpy as np import matplotlib.pyplot as plt # Load a tight-binding model model_tb = tbmodels.io.load('tb_model.hdf5') # Construct k.p model around a specific k-point k_star = np.array([0.1, 0.2, 0.3]) # Expansion point model_kp = model_tb.construct_kdotp( k=k_star, order=2 # Taylor expansion order (sum of k-powers) ) # The k.p model has similar interface to the TB model # but k is relative to k_star H_kp = model_kp.hamilton(k=[0.0, 0.0, 0.0]) # At k_star eigenvalues_kp = model_kp.eigenval(k=[0.01, 0.0, 0.0]) # Access Taylor coefficients directly # Keys are tuples (power_kx, power_ky, power_kz) for k_powers, matrix in model_kp.taylor_coefficients.items(): if np.any(matrix): print(f"k^{k_powers} coefficient:") print(matrix) # Compare TB and k.p bands along a direction k_dir = np.array([0.3, -0.1, 0.1]) k_values = np.linspace(-0.5, 0.5, 100) bands_tb = np.array([model_tb.eigenval(k_star + x * k_dir) for x in k_values]) bands_kp = np.array([model_kp.eigenval(x * k_dir) for x in k_values]) # Plot comparison plt.plot(k_values, bands_tb, 'b-', label='Tight-binding') plt.plot(k_values, bands_kp, 'r--', label='k.p (order 2)') plt.xlabel('k along direction') plt.ylabel('Energy') plt.legend() plt.show() ``` -------------------------------- ### TBmodels Command-Line Interface Source: https://context7.com/z2packdev/tbmodels/llms.txt Utilize TBmodels via the command line for parsing Wannier90 output, symmetrizing models, slicing orbitals, calculating eigenvalues, and specifying output sparsity. ```bash # Show available commands tbmodels --help ``` ```bash # Parse Wannier90 output to HDF5 tbmodels parse --folder ./wannier_output --prefix silicon --output model.hdf5 tbmodels parse -f ./wannier_output -p silicon -o model.hdf5 --pos-kind nearest_atom ``` ```bash # Symmetrize a model tbmodels symmetrize --input model.hdf5 --symmetries symmetries.hdf5 --output model_sym.hdf5 tbmodels symmetrize -i model.hdf5 -s symmetries.hdf5 -o model_sym.hdf5 --full-group ``` ```bash # Slice specific orbitals from a model tbmodels slice --input model.hdf5 --output model_sliced.hdf5 0 1 2 3 ``` ```bash # Calculate eigenvalues at k-points tbmodels eigenvals --input model.hdf5 --kpoints kpoints.hdf5 --output eigenvals.hdf5 tbmodels eigenvals -i model.hdf5 -k kpoints.hdf5 -o eigenvals.hdf5 -v ``` ```bash # Specify output sparsity tbmodels parse -f ./wannier -p silicon -o model.hdf5 --sparsity sparse tbmodels parse -f ./wannier -p silicon -o model.hdf5 --sparsity dense ``` -------------------------------- ### TBmodels Slice Command Options Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Documentation for options related to slicing models in the tbmodels CLI. ```APIDOC ## tbmodels slice options ### Description Options for controlling the output and sparsity of sliced models. ### Method Not applicable (CLI command) ### Endpoint Not applicable (CLI command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options - **-o, --output ** (string) - Required - Output file for the sliced model. - **--sparsity ** (string) - Optional - Write the model in sparse format. By default, the format of the input model is used. Options: sparse | dense | as_input - **-v, --verbose** (boolean) - Optional - Enable verbose output. ### Arguments - **SLICE_IDX** (integer) - Optional - Index for slicing. ### Request Example ```shell tbmodels slice --output sliced_model.h5 --sparsity sparse 0 ``` ### Response #### Success Response (200) Not applicable (CLI command, output is to file) #### Response Example None ``` -------------------------------- ### construct_kdotp Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Constructs a k.p model around a specified k-point by evaluating Taylor expansion derivatives. ```APIDOC ## construct_kdotp ### Description Constructs a k.p model around a given k-point by explicitly evaluating the derivatives that form the Taylor expansion. ### Method Not specified (likely a method of a Model object) ### Endpoint Not applicable (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **k** (Sequence[float]) - Required - The k-point around which the k.p model is constructed. * **order** (int) - Required - The order (sum of powers) to which the Taylor expansion is performed. ``` -------------------------------- ### Create TB Model Manually Source: https://context7.com/z2packdev/tbmodels/llms.txt Constructs a tight-binding model by defining on-site energies, orbital positions, unit cell, and hopping terms. Hoppings can be added individually using `add_hop()` or in bulk using `from_hop_list()`. This method is useful for custom models or when Wannier90 output is not available. ```python import tbmodels import numpy as np import itertools # Create a 3D model with two orbitals model = tbmodels.Model( on_site=[1.0, -1.0], # On-site energies dim=3, # Dimensionality occ=1, # Number of occupied states pos=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.0]], # Orbital positions (reduced coordinates) uc=[[1, 0, 0], [0, 1, 0], [0, 0, 1]] # Unit cell vectors (optional) ) # Add hopping terms: t1 for nearest-neighbor, t2 for next-nearest-neighbor t1, t2 = 0.1, 0.2 # Add nearest-neighbor hoppings between orbitals 0 and 1 for phase, R in zip([1, -1j, 1j, -1], itertools.product([0, -1], [0, -1], [0])): model.add_hop( overlap=t1 * phase, # Hopping strength orbital_1=0, # First orbital index orbital_2=1, # Second orbital index R=R # Lattice vector to unit cell containing orbital_2 ) # Add next-nearest-neighbor hoppings (same orbital, different unit cells) for R in ((r[0], r[1], 0) for r in itertools.permutations([0, 1])): model.add_hop(t2, 0, 0, R) model.add_hop(-t2, 1, 1, R) # Alternative: create model from a list of hoppings hop_list = [ (0.1, 0, 1, (1, 0, 0)), # t, orbital_1, orbital_2, R (0.1, 0, 1, (0, 1, 0)), (0.05, 0, 0, (1, 0, 0)), ] model2 = tbmodels.Model.from_hop_list( hop_list=hop_list, on_site=[1.0, -1.0], pos=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.0]] ) ``` -------------------------------- ### Manually Construct a Model Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/tutorial.md Create a TBmodels.Model instance directly using the constructor. Define on-site energies, dimensionality, occupancy, and orbital positions. Use `add_hop()` to add hopping terms between orbitals and across unit cells. ```python # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch import tbmodels import itertools model = tbmodels.Model( on_site=[1, -1], dim=3, occ=1, pos=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.0]] ) t1, t2 = (0.1, 0.2) for phase, R in zip([1, -1j, 1j, -1], itertools.product([0, -1], [0, -1], [0])): model.add_hop(t1 * phase, 0, 1, R) for R in ((r[0], r[1], 0) for r in itertools.permutations([0, 1])): model.add_hop(t2, 0, 0, R) model.add_hop(-t2, 1, 1, R) ``` -------------------------------- ### Save Model to HDF5 File Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/tutorial.md Use `to_hdf5_file()` to save the model exactly as it is. Load it later with `from_hdf5_file()` to create an exact copy. ```python model.to_hdf5_file('model.hdf5') model2 = tbmodels.Model.from_hdf5_file('model.hdf5') # model2 is an exact copy of model ``` -------------------------------- ### Hamiltonian Calculation with Conventions Source: https://context7.com/z2packdev/tbmodels/llms.txt Calculate the Hamiltonian at a specific k-point using different convention settings. Convention 2 is the default. ```python H_conv1 = model.hamilton(k=[0.5, 0.0, 0.0], convention=1) H_conv2 = model.hamilton(k=[0.5, 0.0, 0.0], convention=2) # default ``` -------------------------------- ### Load TBmodels Hamiltonian Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Loads the tight-binding model from Wannier90 output files. This is the initial step for interfacing with Kwant. ```python model = tbmodels.Model.from_wannier_files(hr_file='data/wannier90_hr.dat') ``` -------------------------------- ### Plot Finite Wire System Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Visualizes the finite wire system using Kwant's plotting function. This helps verify the system geometry. ```python kwant.plot(wire); ``` -------------------------------- ### Create TB Model from Wannier90 Output Source: https://context7.com/z2packdev/tbmodels/llms.txt Parses Wannier90 output files to create a tight-binding model. Requires at least the `hr_file`. Other files like `wsvec_file`, `xyz_file`, and `win_file` provide additional details. `h_cutoff` can be used to ignore small hoppings, and `pos_kind` specifies how to determine orbital positions. ```python import tbmodels # Basic usage with only the hopping file model = tbmodels.Model.from_wannier_files( hr_file='wannier90_hr.dat' ) # Full usage with all Wannier90 output files model = tbmodels.Model.from_wannier_files( hr_file='wannier90_hr.dat', wsvec_file='wannier90_wsvec.dat', # Correction terms for lattice vectors xyz_file='wannier90_centres.xyz', # Wannier centers for orbital positions win_file='wannier90.win', # Unit cell dimensions h_cutoff=1e-6, # Ignore hoppings smaller than this pos_kind='wannier' # Use Wannier centers ('wannier') or nearest atoms ('nearest_atom') ) # Convenience method using folder and prefix model = tbmodels.Model.from_wannier_folder( folder='./wannier_output', prefix='silicon' # Will look for silicon_hr.dat, silicon_wsvec.dat, etc. ) # Print eigenvalues at Gamma point print(model.eigenval([0, 0, 0])) ``` -------------------------------- ### Symmetrize TB Model CLI Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Command-line interface for symmetrizing tight-binding models. Requires input model, output file, and symmetry definitions. ```shell tbmodels symmetrize [OPTIONS] ``` -------------------------------- ### TBmodels CLI: Version Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Displays the version of the TBmodels package. ```shell tbmodels --version ``` -------------------------------- ### KdotpModel Class Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Documentation for the KdotpModel class, used to represent k.p models. ```APIDOC ## class tbmodels.kdotp.KdotpModel ### Description A class describing a k.p model. ### Method __init__ ### Endpoint Not applicable (Python class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **taylor_coefficients** (Mapping[Tuple[int, ...], Any]) - Required - A mapping containing the taylor coefficients of the k.p model. The keys are tuples which describe the power of the k-vector components, and the values are the corresponding matrices. Example: : (1, 0, 2): [[1, 0], [0, -1]] describes k_x * k_z**2 * sigma_z ### Request Example ```python from typing import Mapping, Tuple, Any taylor_coeffs: Mapping[Tuple[int, ...], Any] = { (1, 0, 2): [[1, 0], [0, -1]] } model = KdotpModel(taylor_coefficients=taylor_coeffs) ``` ### Response #### Success Response (200) Not applicable (Python class instantiation) #### Response Example None ``` -------------------------------- ### Add hopping terms from a Kwant system Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md The add_hoppings_kwant method allows setting the on-site energies and hopping terms of an existing Kwant system based on a tbmodels Model. This interface is experimental and should be used with caution. ```python add_hoppings_kwant(kwant_sys, kwant_sublattices=None) ``` -------------------------------- ### Load TB Model from hr.dat File Source: https://context7.com/z2packdev/tbmodels/llms.txt Loads a tight-binding model from a Wannier90 hr.dat file. Note that this method does not preserve the original position and unit cell information. ```python # Load from hr.dat file (note: positions and unit cell not preserved) model_from_hr = tbmodels.Model.from_wannier_files(hr_file='model_hr.dat') ``` -------------------------------- ### Calculate and Compare Eigenvalues Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Calculates eigenvalues for both TBmodels and Kwant Hamiltonians along the defined k-list. Requires scaling k-vectors for Kwant. ```python eigs_tbmodels = [model.eigenval(k) for k in k_list] eigs_kwant = [la.eigvalsh( kwant_model.hamiltonian_submatrix( params={key: val for key, val in zip(['k_x', 'k_y', 'k_z'], 2 * np.pi * np.array(k))} ) ) for k in k_list] ``` -------------------------------- ### Model Creation from Hopping List Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Method for creating a Model object from a list of hopping terms. ```APIDOC ## classmethod from_hop_list(*, hop_list: Iterable[Tuple[complex, int, int, Tuple[int, ...]]] = (), size: int | None = None, **kwargs) -> Model ### Description Create a [`Model`](#tbmodels.Model) from a list of hopping terms. ### Method classmethod ### Endpoint N/A (Class method) ### Parameters #### Request Body - **hop_list** (Iterable[Tuple[complex, int, int, Tuple[int, ...]]]) - 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** (int | None) - Number of states. Defaults to the length of the on-site energies given, if such are given. - **kwargs** (dict) - Any [`Model`](#tbmodels.Model) keyword arguments. ``` -------------------------------- ### Populate Finite Wire Lattice and Hoppings Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Adds lattice sites within the defined shape to the wire builder and then adds the hoppings from the TBmodels object. ```python wire[lattice.shape(shape, (0, 0, 0))] = 0 model.add_hoppings_kwant(wire) ``` -------------------------------- ### Write Model to Wannier90 HR File Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Writes the model to a file in Wannier90's \*_hr.dat format. Information about atom positions and unit cell shape is not preserved, and hopping strength precision may be reduced. ```python to_hr_file(hr_file: str) → None ``` -------------------------------- ### Create Kwant lattice from TBmodels Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Converts the TBmodels lattice structure into a Kwant lattice object. This is essential for building Kwant systems. ```python lattice = model.to_kwant_lattice() ``` -------------------------------- ### CLI: tbmodels parse Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Parses Wannier90 output files to create an HDF5 tight-binding model. ```APIDOC ## tbmodels parse ### Description Parse Wannier90 output files and create an HDF5 file containing the tight-binding model. ### Usage ```shell tbmodels parse [OPTIONS] ``` ### Options - **-f, --folder** - Directory containing the Wannier90 output files. - **-p, --prefix** - Common prefix of the Wannier90 output files. - **--pos-kind** - Which position to use for the orbitals. Options: wannier | nearest_atom. - **--distance-ratio-threshold** - Threshold for distance ratio. - **--sparsity** - Write the model in sparse format. Options: sparse | dense | as_input. By default, the format of the input model is used. - **-v, --verbose** - Enable verbose output. - **-o, --output** - Path of the output file. ``` -------------------------------- ### Plot Bands for Comparison Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Plots the band structures calculated from both TBmodels (black) and Kwant (blue) for visual comparison. ```python fig, ax = plt.subplots() for band in np.array(eigs_tbmodels).T: ax.plot(x, band, 'k') for band in np.array(eigs_kwant).T: ax.plot(x, band, 'b') ``` -------------------------------- ### Save and Load TB Model using IO Module Source: https://context7.com/z2packdev/tbmodels/llms.txt An alternative method for saving and loading TB models using the tbmodels.io module, compatible with fsc.hdf5_io. ```python import tbmodels # Alternative using io module (compatible with fsc.hdf5_io) tbmodels.io.save(model, 'model_v2.hdf5') loaded_model2 = tbmodels.io.load('model_v2.hdf5') ``` -------------------------------- ### Convert Model to Wannier90 HR Format Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Returns a string containing the model in Wannier90's \*_hr.dat format. Note that atom positions and unit cell shape information are lost, and precision of hopping strengths may be reduced. ```python to_hr() → str ``` -------------------------------- ### Hamiltonian Calculation Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Calculate the Hamilton matrix for a given k-point or list of k-points. ```APIDOC ## hamilton ### Description Calculates the Hamilton matrix for a given k-point or list of k-points. ### Method Instance Method ### Endpoint `model.hamilton(k, convention=2)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **k** (Sequence[float] | Sequence[Sequence[float]]) - Required - The k-point at which the Hamiltonian is evaluated. If a list of k-points is given, the result will be the corresponding list of Hamiltonians. * **convention** (int) - Optional - Choice of convention to calculate the Hamilton matrix. See explanation in [the PythTB documentation](http://www.physics.rutgers.edu/pythtb/_downloads/pythtb-formalism.pdf). Valid choices are 1 or 2. Defaults to 2. ### Request Example ```json { "k": [0.1, 0.2, 0.3], "convention": 1 } ``` ### Response #### Success Response (200) - **ndarray[Any, dtype[complex128]]** - The Hamilton matrix for the given k-point(s). #### Response Example ```json { "hamiltonian_matrix": "" } ``` ``` -------------------------------- ### Calculate Eigenvalues at Multiple k-points Source: https://context7.com/z2packdev/tbmodels/llms.txt Efficiently calculate eigenvalues for a list of k-points. This method is more performant than iterating through individual k-points. ```python k_points = [ [0.0, 0.0, 0.0], # Gamma [0.5, 0.0, 0.0], # X [0.5, 0.5, 0.0], # M [0.5, 0.5, 0.5], # R ] all_eigenvalues = model.eigenval(k_points) for k, eig in zip(k_points, all_eigenvalues): print(f"k={k}: E={eig}") ``` -------------------------------- ### Convert Model to Kwant Lattice Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md 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. ```python to_kwant_lattice() ``` -------------------------------- ### Sparse Matrix Support in TBmodels Source: https://context7.com/z2packdev/tbmodels/llms.txt Manage sparse and dense matrix representations for memory efficiency. Supports creating sparse models, converting existing models, and checking sparsity status. ```python import tbmodels # Create model with sparse matrices model_sparse = tbmodels.Model( on_site=[1.0, -1.0, 0.5, -0.5], dim=3, pos=[[0, 0, 0], [0.25, 0.25, 0], [0.5, 0.5, 0], [0.75, 0.75, 0]], sparse=True # Use sparse matrices ) ``` ```python model = tbmodels.Model(on_site=[1.0, -1.0], dim=3) model.set_sparse(True) ``` ```python model.set_sparse(False) ``` ```python print(f"Model is sparse: {model._sparse}") ``` ```python # Sparse models work the same way for calculations eigenvalues = model.eigenval([0, 0, 0]) hamiltonian = model.hamilton([0.5, 0.5, 0.5]) ``` -------------------------------- ### Define k-vector list for band plotting Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Creates a list of k-vectors along the kx-axis for plotting the band structure. Note the scaling difference between TBmodels and Kwant. ```python k_list = [(kx, 0, 0) for kx in np.linspace(0, 1, 100)] x = range(100) ``` -------------------------------- ### Save Model to Wannier90 hr.dat File Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/tutorial.md Use `to_hr_file()` for compatibility with Wannier90's `*hr.dat` format. This method preserves only hopping terms and truncates precision. ```python model.to_hr_file('model_hr.dat') model3 = tbmodels.Model.from_hr_file('model_hr.dat') # model3 might differ from model ``` -------------------------------- ### Define Infinite System Shape Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Sets an 'infinite' shape for the Kwant system before adding hoppings. This ensures all lattice sites are included. ```python kwant_sys[lattice.shape(lambda p: True, (0, 0, 0))] = 0 ``` -------------------------------- ### TBmodels CLI: Calculate Eigenvalues Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Calculates energy eigenvalues for a given set of k-points. Input and output are handled via HDF5 files. Use the -v flag for verbose output. ```shell tbmodels eigenvals [OPTIONS] ``` ```shell -i, --input File containing the input model (in HDF5 format). ``` ```shell -k, --kpoints File containing the k-points for which the eigenvalues are evaluated. ``` ```shell -o, --output Output file for the energy eigenvalues. ``` ```shell -v, --verbose ``` -------------------------------- ### Evaluate Hamiltonian and Eigenvalues Source: https://context7.com/z2packdev/tbmodels/llms.txt Calculates the Hamiltonian matrix and energy eigenvalues at specified k-points. Supports evaluation for single k-points or lists of k-points for batch processing. This is crucial for band structure calculations and understanding electronic properties. ```python import tbmodels import numpy as np # Load or create a model model = tbmodels.Model( on_site=[1.0, -1.0], dim=3, pos=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.0]] ) # Calculate Hamiltonian at a single k-point H = model.hamilton(k=[0.0, 0.0, 0.0]) print("Hamiltonian at Gamma:") print(H) # Output: 2x2 complex matrix # Calculate eigenvalues at a single k-point eigenvalues = model.eigenval(k=[0.0, 0.0, 0.0]) print("Eigenvalues at Gamma:", eigenvalues) # Output: array([...]) ``` -------------------------------- ### Model Class Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md The `Model` class represents a tight-binding model. It allows for modification of the model, evaluation of Hamiltonians and eigenvalues, and saving/loading to various file formats. ```APIDOC ## Class tbmodels.Model ### Description 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 #### Initialization Parameters - **on_site** (Sequence[float] | None) - On-site energy of the states. The length of the list must be the same as the number of states. - **hop** (Dict[Tuple[int, ...], Any] | None) - Hopping matrices, as a dict containing the corresponding lattice vector R as a key. - **size** (int | None) - Number of states. Defaults to the size of the hopping matrices, if such are given. - **dim** (int | None) - Dimension of the tight-binding model. By default, the dimension is guessed from the other parameters if possible. - **occ** (int | None) - Number of occupied states. - **pos** (Sequence[Sequence[float]] | None) - 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** (_SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | str | bytes] | None) - Unit cell of the system. The unit cell vectors are given as rows in a `dim` x `dim` array. - **contains_cc** (bool) - 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. Defaults to True. - **cc_check_tolerance** (float) - Tolerance when checking if the complex conjugate values (if given) match. Defaults to 1e-12. - **sparse** (bool) - Specifies whether the hopping matrices should be saved in sparse format. Defaults to False. ### Methods #### Arithmetic Operations - **__add__(model: [Model](#tbmodels.Model)) → [Model](#tbmodels.Model)**: Adds two models together by adding their hopping terms. - **__mul__(x: float) → [Model](#tbmodels.Model)**: Multiplies hopping terms by x. - **__neg__() → [Model](#tbmodels.Model)**: Changes the sign of all hopping terms. - **__rmul__(x: float) → [Model](#tbmodels.Model)**: Multiplies hopping terms by x. - **__sub__(model: [Model](#tbmodels.Model)) → [Model](#tbmodels.Model)**: Substracts one model from another by substracting all hopping terms. - **__truediv__(x: float) → [Model](#tbmodels.Model)**: Divides hopping terms by x. #### Hopping Manipulation - **add_hop(overlap: complex, orbital_1: int, orbital_2: int, R: Sequence[int])**: Adds a hopping term with a given overlap (hopping strength) from `orbital_2` ($o_2$), which lies in the unit cell pointed to by `R`, to `orbital_1` ($o_1$) which is in the home unit cell. The complex conjugate of the hopping is added automatically. * **Parameters**: * **overlap** (complex) - Strength of the hopping term (in energy units). * **orbital_1** (int) - Index of the first orbital. * **orbital_2** (int) - Index of the second orbital. * **R** (Sequence[int]) - Lattice vector pointing to the unit cell where `orbital_2` lies. - **add_hoppings_kwant(kwant_sys, kwant_sublattices=None)**: Sets the on-site energies and hopping terms for an existing kwant system to those of the [`Model`](#tbmodels.Model). Note: The TBmodels - Kwant interface is experimental. Use it with caution. ``` -------------------------------- ### Define Lead Shape and Populate Source: https://github.com/z2packdev/tbmodels/blob/trunk/examples/kwant_interface/kwant_interface_demo.ipynb Defines the shape of the lead and populates it with lattice sites and hoppings. The lead must be long enough to contain the longest hopping. ```python lead = kwant.Builder(sym_lead) def lead_shape(p): x, y, z = p return -5 <= x <= 0 and -5 < y < 5 and -5 < z < 5 lead[lattice.shape(lead_shape, (0, 0, 0))] = 0 model.add_hoppings_kwant(lead) ``` -------------------------------- ### Model Manipulation and Utility Methods Source: https://github.com/z2packdev/tbmodels/blob/trunk/doc/source/reference.md Methods for joining models, modifying hoppings, and creating supercells. ```APIDOC ## ClassMethod join_models ### Description Creates a tight-binding model which contains all orbitals of the given input models. The orbitals are ordered by model, such that the resulting Hamiltonian is block-diagonal. ### Method `classmethod` ### Endpoint `Model.join_models(*models)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **models** ([Model](#tbmodels.Model)) - Required - Models which should be joined together. ### Request Example ```json { "models": [ "", "" ] } ``` ### Response #### Success Response (200) - **Model** (Model) - A new Model instance containing all orbitals from the input models. #### Response Example ```json { "joined_model": "" } ``` ## property reciprocal_lattice ### Description An array containing the reciprocal lattice vectors as rows. ### Method `property` ### Endpoint `model.reciprocal_lattice` ### Parameters None ### Response #### Success Response (200) - **ndarray** - The reciprocal lattice vectors. #### Response Example ```json { "reciprocal_lattice": "" } ``` ## remove_long_range_hop ### Description Remove hoppings whose range is longer than the given cutoff. ### Method Instance Method ### Endpoint `model.remove_long_range_hop(cutoff_distance_cartesian)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cutoff_distance_cartesian** (float) - Required - Cartesian distance between the two orbitals above which the hoppings are removed. ### Request Example ```json { "cutoff_distance_cartesian": 5.0 } ``` ### Response #### Success Response (200) - **None** - This method modifies the model in-place and returns None. #### Response Example ```json { "status": "success" } ``` ## remove_small_hop ### Description Remove hoppings which are smaller than the given cutoff value. ### Method Instance Method ### Endpoint `model.remove_small_hop(cutoff)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cutoff** (float) - Required - Cutoff value below which a hopping is removed. ### Request Example ```json { "cutoff": 1e-5 } ``` ### Response #### Success Response (200) - **None** - This method modifies the model in-place and returns None. #### Response Example ```json { "status": "success" } ``` ## set_sparse ### Description Defines whether sparse or dense matrices should be used to represent the system, and changes the system accordingly if needed. ### Method Instance Method ### Endpoint `model.set_sparse(sparse=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **sparse** (bool) - Optional - Flag to determine whether the system is set to be sparse (`True`) or dense (`False`). Defaults to True. ### Request Example ```json { "sparse": false } ``` ### Response #### Success Response (200) - **None** - This method modifies the model in-place and returns None. #### Response Example ```json { "status": "success" } ``` ## slice_orbitals ### Description Returns a new model with only the orbitals as given in the `slice_idx`. This can also be used to re-order the orbitals. ### Method Instance Method ### Endpoint `model.slice_orbitals(slice_idx)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **slice_idx** (List[int]) - Required - Orbital indices that will be in the resulting model. ### Request Example ```json { "slice_idx": [0, 2, 3] } ``` ### Response #### Success Response (200) - **Model** (Model) - A new Model instance with the selected orbitals. #### Response Example ```json { "sliced_model": "" } ``` ## supercell ### Description Generate a model for a supercell of the current unit cell. ### Method Instance Method ### Endpoint `model.supercell(size)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **size** (Sequence[int]) - Required - The size of the supercell, given as integer multiples of the current lattice vectors. ### Request Example ```json { "size": [2, 2, 1] } ``` ### Response #### Success Response (200) - **Model** (Model) - A Model instance representing the supercell. #### Response Example ```json { "supercell_model": "" } ``` ```