### Setup Graphene Sample for TBPM Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/tbpm.md Initializes a graphene sample and rescales the Hamiltonian for TBPM calculations. The Hamiltonian must be rescaled so its eigenvalues fall within the range [-1, 1]. ```python import matplotlib.pyplot as plt import tbplas as tb prim_cell = tb.make_graphene_diamond() super_cell = tb.SuperCell(prim_cell, dim=(480, 480, 1), pbc=(True, True, False)) sample = tb.Sample(super_cell) sample.rescale_ham(9.0) ``` -------------------------------- ### MPI and OpenMP Parallel Band Structure Calculation Source: https://context7.com/deepmodeling/tbplas/llms.txt This example shows how to perform a parallel band structure calculation using MPI. Ensure `enable_mpi=True` is passed to relevant functions. Master-process guards are needed for I/O. ```python #! /usr/bin/env python # Run with: mpirun -np 4 ./script.py import numpy as np import tbplas as tb timer = tb.Timer() vis = tb.Visualizer(enable_mpi=True) cell = tb.make_graphene_diamond() sample = tb.Sample(tb.SuperCell(cell, dim=(12,12,1), pbc=(True,True,False))) # Parallel band structure k_path, k_idx = tb.gen_kpath( np.array([[0,0,0],[2/3,1/3,0],[1/2,0,0],[0,0,0]]), [40,40,40]) timer.tic("band") k_len, bands = sample.calc_bands(k_path, enable_mpi=True) timer.toc("band") vis.plot_bands(k_len, bands, k_idx, ["G","M","K","G"]) if vis.is_master: timer.report_total_time() ``` -------------------------------- ### Fortran Object Library Setup Source: https://github.com/deepmodeling/tbplas/blob/master/CMakeLists.txt Builds the 'fortranobject' library, which is essential for interfacing Fortran code with Python via f2py. It includes f2py include directories and links against NumPy. ```cmake # Define the fortranobject execute_process( COMMAND "${PYTHON_EXECUTABLE}" -c "import numpy.f2py; print(numpy.f2py.get_include())" OUTPUT_VARIABLE F2PY_INCLUDE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE) add_library(fortranobject OBJECT "${F2PY_INCLUDE_DIR}/fortranobject.c") target_link_libraries(fortranobject PUBLIC Python::NumPy) target_include_directories(fortranobject PUBLIC "${F2PY_INCLUDE_DIR}") set_property(TARGET fortranobject PROPERTY POSITION_INDEPENDENT_CODE ON) if(USE_MKL) target_link_libraries(fortranobject PUBLIC mkl_rt iomp5 pthread m dl) target_include_directories(fortranobject PUBLIC "$ENV{MKLROOT}/include") #target_link_directories(fortranobject PUBLIC "$ENV{MKLROOT}/lib") endif() ``` -------------------------------- ### Hamiltonian convention 1 output Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/analy_ham.md Example output of the analytical Hamiltonian for convention 1, showing the formula for matrix elements. ```text ham[0, 0] = (0.0) ham[1, 1] = (0.0) ham[0, 1] = ((-2.7+0j) * exp_i(0.3333333333333333 * ka + 0.3333333333333333 * kb) + (-2.7-0j) * exp_i(-0.6666666666666667 * ka + 0.3333333333333333 * kb) + (-2.7-0j) * exp_i(0.3333333333333333 * ka - 0.6666666666666667 * kb)) ham[1, 0] = ham[0, 1].conjugate() with exp_i(x) := cos(2 * pi * x) + 1j * sin(2 * pi * x) ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md Install mandatory and optional Python packages using pip or conda. For users without root privileges, consider using virtual environments, the --user option, or the --prefix option. ```bash pip install numpy conda install numpy ``` ```bash pip install --user numpy ``` ```bash pip install --prefix=DEST numpy ``` -------------------------------- ### Setup Primitive Cell for Graphene Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/lindhard.md Initializes a primitive cell for graphene, defining lattice vectors, orbitals, and hopping parameters. This setup is required before creating a `Lindhard` object. ```python import numpy as np import matplotlib.pyplot as plt import tbplas as tb # Make graphene primitive cell t = 3.0 vectors = tb.gen_lattice_vectors(a=0.246, b=0.246, c=1.0, gamma=60) cell = tb.PrimitiveCell(vectors, unit=tb.NM) cell.add_orbital([0.0, 0.0], label="C_pz") cell.add_orbital([1 / 3., 1 / 3.], label="C_pz") cell.add_hopping([0, 0], 0, 1, t) cell.add_hopping([1, 0], 1, 0, t) cell.add_hopping([0, 1], 1, 0, t) ``` -------------------------------- ### Install TBPLaS with pip Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md The standard command to build and install TBPLaS after configuring pyproject.toml. If you lack root privileges, refer to the dependencies section for alternative solutions. ```bash pip install . ``` -------------------------------- ### Install TBPLaS and optional dependencies Source: https://context7.com/deepmodeling/tbplas/llms.txt Install TBPLaS using pip. Optional dependencies like mpi4py for MPI parallelization and ase for the LAMMPS interface can also be installed. ```bash # Configure pyproject.toml for your compiler, then: pip install . # Optional dependencies pip install mpi4py # for MPI parallelization pip install ase # for LAMMPS interface ``` -------------------------------- ### Hamiltonian convention 2 output Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/analy_ham.md Example output of the analytical Hamiltonian for convention 2, illustrating the formula for matrix elements. ```text ham[0, 0] = (0.0) ham[1, 1] = (0.0) ham[0, 1] = ((-2.7+0j) * 1 + (-2.7-0j) * exp_i(-ka) + (-2.7-0j) * exp_i(-kb)) ham[1, 0] = ham[0, 1].conjugate() with exp_i(x) := cos(2 * pi * x) + 1j * sin(2 * pi * x) ``` -------------------------------- ### Verify TBPLaS Installation Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md After installation, navigate to a different directory and invoke Python to import TBPLaS. A successful import without errors confirms the installation. ```python import tbplas ``` -------------------------------- ### Initialize FakePC, DiagSolver, and Visualizer Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/analy_ham.md Sets up a fake primitive cell with 2 orbitals, a `DiagSolver` using the fake cell, and a `Visualizer` for plotting. ```python # Create fake primitive cell, solver and visualizer vectors = tb.gen_lattice_vectors(a=0.246, b=0.246, c=1.0, gamma=60) cell = FakePC(num_orb=2, lat_vec=vectors, unit=tb.NM) solver = tb.DiagSolver(cell) vis = tb.Visualizer() ``` -------------------------------- ### Create Graphene Sample Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Import and create a graphene sample for calculations. This sets up the material and supercell. ```python cell = tb.make_graphene_diamond() sample = tb.Sample(tb.SuperCell(cell, dim=(12, 12, 1), pbc=(True, True, False))) ``` -------------------------------- ### Set up Graphene Nano-Ribbon Samples Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/bands.md Initializes `Sample` objects for armchair-edged and zigzag-edged graphene nano-ribbons. These samples are created from `SuperCell` objects derived from a rectangular graphene lattice. ```python import numpy as np import tbplas as tb rect_cell = tb.make_graphene_rect() sc_am = tb.SuperCell(rect_cell, dim=(3, 3, 1), pbc=(False, True, False)) gnr_am = tb.Sample(sc_am) sc_zz = tb.SuperCell(rect_cell, dim=(3, 3, 1), pbc=(True, False, False)) gnr_zz = tb.Sample(sc_zz) ``` -------------------------------- ### Initialize Visualizer for MPI Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Set up the visualizer to enable MPI-based parallelization. This is a prerequisite for parallel calculations. ```python #! /usr/bin/env python import numpy as np import tbplas as tb timer = tb.Timer() vis = tb.Visualizer(enable_mpi=True) ``` -------------------------------- ### Main function to set up and visualize exact eigenstates Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/quasi_eigen.md Sets up a graphene sample with a vacancy and calls wfc_diag to calculate and visualize its exact eigenstates. This function serves as the entry point for the exact diagonalization part of the tutorial. ```python def main(): # Build a graphene sample with a single vacancy prim_cell = tb.make_graphene_diamond() super_cell = tb.SuperCell(prim_cell, dim=(17, 17, 1), pbc=(True, True, False)) super_cell.add_vacancies([(8, 8, 0, 0)]) sample = tb.Sample(super_cell) # Calcuate and Visualize the eigenstate wfc_diag(sample) if __name__ == "__main__": main() ``` -------------------------------- ### Instantiate TBPM Solver and Analyzer Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/tbpm.md Creates instances of the Solver and Analyzer classes using the prepared sample and configuration objects. ```python solver = tb.Solver(sample, config) analyzer = tb.Analyzer(sample, config) ``` -------------------------------- ### Define Graphene Sample and Propagation Parameters Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/strain_fields.md Sets up a rectangular graphene sample with specified dimensions and boundary conditions, and defines parameters for wave function propagation. ```python prim_cell = tb.make_graphene_rect() dim = (50, 20, 1) pbc = (True, True, False) x_max = prim_cell.lat_vec[0, 0] * dim[0] y_max = prim_cell.lat_vec[1, 1] * dim[1] wfc_center = (x_max * 0.5, y_max * 0.5) deform_center = (x_max * 0.75, y_max * 0.5) ``` -------------------------------- ### Propagate Wave Function in Pristine Sample Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/strain_fields.md Prepares a sample and an initial Gaussian wave function, then propagates the wave function over time using a tbplas solver. Requires sample rescaling and solver configuration. ```python # Prepare the sample and inital wave function sample = tb.Sample(tb.SuperCell(prim_cell, dim, pbc)) psi0 = init_wfc_gaussian(sample, center=wfc_center, extent=(1.0, 0.0)) # Propagate the wave function config = tb.Config() config.generic["nr_time_steps"] = 128 time_log = np.array([0, 16, 32, 64, 128]) sample.rescale_ham() solver = tb.Solver(sample, config) psi_t = solver.calc_psi_t(psi0, time_log) ``` -------------------------------- ### Run TBPLaS Tests Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md Execute testing scripts located in the `tests` directory to verify your TBPLaS compilation and installation. Successful tests will print output to the screen, save figures, and conclude with a success notice. ```bash python test_base.py ``` -------------------------------- ### Cython Extension Generation and Module Definition Source: https://github.com/deepmodeling/tbplas/blob/master/CMakeLists.txt Iterates through a list of Cython prefixes to generate C files from .pyx files using Cython and then defines them as Python modules. Each module is installed to the appropriate directory. ```cmake #------------------------------ Cython extension ------------------------------# set(CYX_PREFIX primitive super sample lindhard atom) foreach(PREF IN LISTS CYX_PREFIX) # Generate the interface add_custom_command( OUTPUT ${PREF}.c DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tbplas/cython/${PREF}.pyx" VERBATIM COMMAND "${CYTHON}" "${CMAKE_CURRENT_SOURCE_DIR}/tbplas/cython/${PREF}.pyx" --output-file "${CMAKE_CURRENT_BINARY_DIR}/${PREF}.c") # Define the python module python_add_library(${PREF} MODULE "${CMAKE_CURRENT_BINARY_DIR}/${PREF}.c" WITH_SOABI) install(TARGETS ${PREF} DESTINATION ./tbplas/cython) endforeach() ``` -------------------------------- ### Print Model Details Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model.md Visualize the created model by printing lattice vectors, orbitals, and hopping terms using the `print` method. ```text Lattice vectors (nm): 0.24600 0.00000 0.00000 0.12300 0.21304 0.00000 0.00000 0.00000 1.00000 Orbitals: 0.00000 0.00000 0.00000 0.0 0.33333 0.33333 0.00000 0.0 Hopping terms: (0, 0, 0) (0, 1) -2.7 (1, 0, 0) (1, 0) -2.7 (0, 1, 0) (1, 0) -2.7 ``` -------------------------------- ### Initialize Z2 Topological Invariant Calculator for Parallel Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Enable MPI parallelization when creating the `Z2` instance for calculating topological invariants. ```python z2 = tb.Z2(cell, num_occ=10, enable_mpi=True) ``` -------------------------------- ### Troubleshoot TBPLaS ImportError Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md This traceback illustrates a common `ImportError` that occurs when Python is invoked from within the TBPLaS source code directory due to relative import issues. Always invoke Python from a different directory after installation. ```python Traceback (most recent call last): File "", line 1, in File "/home/yhli/proj/tbplas/tbplas/__init__.py", line 2, in from .adapter import * File "/home/yhli/proj/tbplas/tbplas/adapter/__init__.py", line 2, in from .wannier90 import * File "/home/yhli/proj/tbplas/tbplas/adapter/wannier90.py", line 11, in from ..builder import PrimitiveCell, PCHopDiagonalError File "/home/yhli/proj/tbplas/tbplas/builder/__init__.py", line 2, in from .advanced import * File "/home/yhli/proj/tbplas/tbplas/builder/advanced.py", line 17, in from .primitive import PrimitiveCell, PCInterHopping File "/home/yhli/proj/tbplas/tbplas/builder/primitive.py", line 12, in from ..cython import primitive as core ImportError: cannot import name 'primitive' from 'tbplas.cython' (/home/yhli/proj/tbplas/tbplas/cython/__init__.py) ``` -------------------------------- ### Import tbplas Package Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/spin_texture.md Begin by importing the necessary tbplas package for calculations. ```python import tbplas as tb ``` -------------------------------- ### Timer and Visualizer Utility Usage Source: https://context7.com/deepmodeling/tbplas/llms.txt Demonstrates the basic usage of `tbplas.Timer` for profiling code sections and `tbplas.Visualizer` for plotting band structures, DOS, scalar fields, vector fields, and topological phases. ```python import tbplas as tb timer = tb.Timer() vis = tb.Visualizer() # or tb.Visualizer(enable_mpi=True) timer.tic("diag") cell = tb.make_graphene_diamond() k_path, k_idx = tb.gen_kpath(..., [40,40,40]) k_len, bands = cell.calc_bands(k_path) timer.toc("diag") timer.report_total_time() # Output: diag : 0.12s vis.plot_bands(k_len, bands, k_idx, ["G","M","K","G"]) vis.plot_dos(energies, dos) vis.plot_scalar(x, y, z, num_grid=(480,480), cmap="jet") # spin texture σ_z vis.plot_vector(x, y, u, v, cmap="jet") # spin texture σ_x,σ_y vis.plot_phases(kb_array, phases) # Z2 topological phases ``` -------------------------------- ### Scale Band Structure Calculation with Processes Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Observe the performance improvement by running the band structure calculation with an increasing number of MPI processes. ```bash $ mpirun -np 2 ./test_mpi.py band : 5.71s $ mpirun -np 4 ./test_mpi.py band : 2.93s ``` -------------------------------- ### Main function for Fractal Generation Demonstration Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/fractal.md Demonstrates the usage of both top-down and bottom-up fractal generation approaches. It initializes a square lattice, adds orbitals and hoppings, generates fractals, and plots them. ```python def main(): # Create a square lattice lattice = np.eye(3, dtype=np.float64) prim_cell = tb.PrimitiveCell(lattice) prim_cell.add_orbital((0, 0)) prim_cell.add_hopping((1, 0), 0, 0, 1.0) prim_cell.add_hopping((0, 1), 0, 0, 1.0) prim_cell.add_hopping((1, 1), 0, 0, 1.0) prim_cell.add_hopping((1, -1), 0, 0, 1.0) # Create fractal using top-down approach fractal = top_down(prim_cell, 2, 3, 3) fractal.plot(with_cells=False, with_orbitals=False, hop_as_arrows=False) # Create fractal using bottom-up approach fractal = bottom_up(prim_cell, 2, 3, 3) fractal.plot(with_cells=False, with_orbitals=False, hop_as_arrows=False) if __name__ == "__main__": main() ``` -------------------------------- ### Project and Package Configuration Source: https://github.com/deepmodeling/tbplas/blob/master/CMakeLists.txt Sets the minimum CMake version, project name, and languages. It also finds required Python components and the Cython executable. ```cmake cmake_minimum_required(VERSION 3.17...3.26) project(${SKBUILD_PROJECT_NAME} LANGUAGES C Fortran) # Search for packages and commands find_package( Python COMPONENTS Interpreter Development.Module NumPy REQUIRED) find_program(CYTHON "cython") ``` -------------------------------- ### Add orbitals using fractional coordinates (z=0.5) Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model.md Add two pz orbitals to the cell at fractional coordinates (1/3, 1/3, 0.5) and (2/3, 2/3, 0.5) with default energy. ```python cell.add_orbital([1./3, 1./3, 0.5], energy=0.0, label="pz") cell.add_orbital([2./3, 2./3, 0.5], energy=0.0, label="pz") ``` -------------------------------- ### Create a graphene model without vacancies Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/model.md Generates a standard graphene primitive cell, creates a supercell, and then initializes a Sample object for visualization. ```python prim_cell = tb.make_graphene_diamond() sc = tb.SuperCell(prim_cell, dim=(3, 3, 1), pbc=(True, True, False)) sample = tb.Sample(sc) sample.plot() ``` -------------------------------- ### Generate and Plot Band Structure Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/sk.md Define k-points and labels, generate a k-path, calculate band structure, and visualize the results. Ensure tbplas and numpy are imported. ```python k_points = np.array([ [0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 0.0] ]) k_label = ["G", "X", "S", "Y", "G"] k_path, k_idx = tb.gen_kpath(k_points, [40, 40, 40, 40]) k_len, bands = cell.calc_bands(k_path) tb.Visualizer().plot_bands(k_len, bands, k_idx, k_label) ``` -------------------------------- ### Import Necessary Packages Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/param_fit.md Import numpy for numerical operations, matplotlib for plotting, and tbplas for the simulation. ```python import numpy as np import matplotlib.pyplot as plt import tbplas as tb ``` -------------------------------- ### Configure TBPM Calculation Parameters Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/tbpm.md Sets up the configuration for TBPM calculations, specifying the number of random samples and time steps for wave function propagation. ```python config = tb.Config() config.generic['nr_random_samples'] = 4 config.generic['nr_time_steps'] = 256 ``` -------------------------------- ### Define Quasi-crystal Parameters Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/quasi_crystal.md Import necessary libraries and define geometric parameters for constructing the quasi-crystal, including twisting angle, center, radius, interlayer shift, and supercell dimensions. ```python import math import numpy as np from numpy.linalg import norm import tbplas as tb angle = 30 / 180 * math.pi center = (2./3, 2./3, 0) radius = 3.0 shift = 0.3349 dim = (33, 33, 1) ``` -------------------------------- ### Calculate Dynamic Polarization (Regular q-points) Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/lindhard.md Calculates the dynamic polarization for q-points on the defined k-grid using `calc_dyn_pol_regular`. Includes timing and plotting of the imaginary part. ```python # Create a timer timer = tb.Timer() # Calculate dynamic polarization with calc_dyn_pol_regular q_grid = np.array([[20, 20, 0]]) timer.tic("regular") omegas, dp_reg = lind.calc_dyn_pol_regular(q_grid) timer.toc("regular") plt.plot(omegas, dp_reg[0].imag, color="red", label="Regular") plt.legend() plt.show() plt.close() ``` -------------------------------- ### Build Heterostructure Model in Python Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/hetero_model.md This function demonstrates the complete process of building a heterostructure, from calculating twist angles to visualizing the Moiré pattern. It requires tbplas library and helper functions like calc_twist_angle and calc_hetero_lattice. ```python def main(): # Evaluate twisting angle i = 5 angle = calc_twist_angle(i) # Prepare primitive cells of fixed and twisted layer prim_cell_fixed = tb.make_graphene_diamond() prim_cell_twisted = tb.make_graphene_diamond() # Shift and rotate the twisted layer tb.spiral_prim_cell(prim_cell_twisted, angle=angle, shift=0.3349) # Reshape primitive cells to the lattice vectors of hetero-structure hetero_lattice = calc_hetero_lattice(i, prim_cell_fixed) layer_fixed = tb.make_hetero_layer(prim_cell_fixed, hetero_lattice) layer_twisted = tb.make_hetero_layer(prim_cell_twisted, hetero_lattice) # Merge layers merged_cell = tb.merge_prim_cell(layer_fixed, layer_twisted) # Extend hopping terms extend_hop(merged_cell, max_distance=0.75) # Visualize Moire pattern sample = tb.Sample(tb.SuperCell(merged_cell, dim=(4, 4, 1), pbc=(True, True, False))) sample.plot(with_orbitals=False, hop_as_arrows=False, hop_eng_cutoff=0.3) if __name__ == "__main__": main() ``` -------------------------------- ### Calculate Z2 Topological Phases in Parallel Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Compute Z2 topological phases in parallel. The `enable_mpi=True` flag during `Z2` initialization handles parallelization. ```python timer.tic("z2") kb_array, phases = z2.calc_phases(ka_array, kb_array, kc) timer.toc("z2") vis.plot_phases(kb_array, phases / pi) if vis.is_master: timer.report_total_time() ``` -------------------------------- ### Calculate and Plot DOS using Visualizer Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/bands.md Calculates the density of states (DOS) using the generated k-mesh and visualizes it with the `Visualizer` class's `plot_dos` method. ```python energies, dos = cell.calc_dos(k_mesh) vis.plot_dos(energies, dos) ``` -------------------------------- ### Calculate and Visualize Band Structure (Armchair GNR) Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/bands.md Computes and visualizes the band structure for an armchair-edged graphene nano-ribbon along a specified k-path. Requires `numpy` for k-point definition and `tbplas` for calculations and visualization. ```python k_points = np.array([ [0.0, -0.5, 0.0], [0.0, 0.0, 0.0], [0.0, 0.5, 0.0], ]) k_label = ["X", "G", "X"] k_path, k_idx = tb.gen_kpath(k_points, [40, 40]) k_len, bands = gnr_am.calc_bands(k_path) vis = tb.Visualizer() vis.plot_bands(k_len, bands, k_idx, k_label) ``` -------------------------------- ### Calculate and Visualize DOS for Graphene Sample Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/bands.md Calculates and visualizes the density of states (DOS) for a graphene sample. This involves generating a k-mesh and using the `calc_dos` method, suitable for large supercells. ```python import numpy as np import tbplas as tb prim_cell = tb.make_graphene_diamond() sc = tb.SuperCell(prim_cell, dim=(20, 20, 1), pbc=(True, True, False)) sample = tb.Sample(sc) k_mesh = tb.gen_kmesh((6, 6, 1)) energies, dos = sample.calc_dos(k_mesh) vis = tb.Visualizer() vis.plot_dos(energies, dos) ``` -------------------------------- ### Construct armchair graphene nano-ribbon Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/model.md Creates a supercell with specified dimensions and periodic boundary conditions to form an armchair graphene nano-ribbon, then visualizes it. ```python sc_am = tb.SuperCell(rect_cell, dim=(3, 3, 1), pbc=(False, True, False)) gnr_am = tb.Sample(sc_am) gnr_am.plot() ``` -------------------------------- ### Fit Primitive Cell Parameters Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/param_fit.md Use the MyFit class to fit Slater-Koster parameters for a primitive cell. Initialize MyFit with k-points and weights, provide initial parameters, and call the fit function. This snippet also includes plotting the fitted band structure against a reference. ```python def main(): # Fit the sk parameters # Reference: # https://journals.aps.org/prb/abstract/10.1103/PhysRevB.82.245412 k_points = tb.gen_kmesh((120, 120, 1)) weights = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) fit = MyFit(k_points, weights) sk0 = np.array([-8.370, 0.0, -5.729, 5.618, 6.050, -3.070, 0.102, -0.171, -0.377, 0.070]) sk1 = fit.fit(sk0) print("SK parameters after fitting:") print(sk1[:2]) print(sk1[2:6]) print(sk1[6:10]) # Plot fitted band structure k_points = np.array([ [0.0, 0.0, 0.0], [1./3, 1./3, 0.0], [1./2, 0.0, 0.0], [0.0, 0.0, 0.0], ]) k_path, k_idx = tb.gen_kpath(k_points, [40, 40, 40]) cell_ref = tb.wan2pc("graphene") cell_fit = make_cell(sk1) k_len, bands_ref = cell_ref.calc_bands(k_path) k_len, bands_fit = cell_fit.calc_bands(k_path) num_bands = bands_ref.shape[1] for i in range(num_bands): plt.plot(k_len, bands_ref[:, i], color="red", linewidth=1.0) plt.plot(k_len, bands_fit[:, i], color="blue", linewidth=1.0) plt.show() if __name__ == "__main__": main() ``` -------------------------------- ### Construct zigzag graphene nano-ribbon Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/sample/model.md Creates a supercell with specified dimensions and periodic boundary conditions to form a zigzag graphene nano-ribbon, then visualizes it. ```python sc_zz = tb.SuperCell(rect_cell, dim=(3, 3, 1), pbc=(True, False, False)) gnr_zz = tb.Sample(sc_zz) gnr_zz.plot() ``` -------------------------------- ### Add orbitals using fractional coordinates (z=0) Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model.md Add two pz orbitals to the cell at fractional coordinates (1/3, 1/3) and (2/3, 2/3) with default energy. ```python cell.add_orbital([1./3, 1./3], energy=0.0, label="pz") cell.add_orbital([2./3, 2./3], energy=0.0, label="pz") ``` -------------------------------- ### Create Rectangular Primitive Cell from Scratch Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model_complex.md Constructs a rectangular primitive cell for graphene nano-ribbons by defining lattice vectors, adding orbitals, and specifying hopping terms. Use this method when building a cell from fundamental parameters. ```python import math import tbplas as tb # Generate lattice vectors sqrt3 = math.sqrt(3) a = 2.46 cc_bond = sqrt3 / 3 * a vectors = tb.gen_lattice_vectors(sqrt3 * cc_bond, 3 * cc_bond) # Create cell and add orbitals rect_cell = tb.PrimitiveCell(vectors) rect_cell.add_orbital((0, 0)) rect_cell.add_orbital((0, 2 / 3.)) rect_cell.add_orbital((1 / 2., 1 / 6.)) rect_cell.add_orbital((1 / 2., 1 / 2.)) # Add hopping terms rect_cell.add_hopping([0, 0], 0, 2, -2.7) rect_cell.add_hopping([0, 0], 2, 3, -2.7) rect_cell.add_hopping([0, 0], 3, 1, -2.7) rect_cell.add_hopping([0, 1], 1, 0, -2.7) rect_cell.add_hopping([1, 0], 3, 1, -2.7) rect_cell.add_hopping([1, 0], 2, 0, -2.7) # Plot the cell rect_cell.plot() ``` -------------------------------- ### Initialize Lindhard Object Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/lindhard.md Creates a `Lindhard` object for response function calculations. Configure parameters like energy range, k-mesh, chemical potential, temperature, and dimensionality. ```python # Create a Lindhard object lind = tb.Lindhard(cell=cell, energy_max=10, energy_step=1000, kmesh_size=(600, 600, 1), mu=0.0, temperature=300, g_s=2, back_epsilon=1.0, dimension=2) ``` -------------------------------- ### Initialize Lindhard Calculator for Parallel Response Properties Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Enable MPI parallelization when initializing the `Lindhard` calculator for response property calculations. ```python lind = tb.Lindhard(cell=cell, energy_max=10.0, energy_step=2048, kmesh_size=(600, 600, 1), mu=0.0, temperature=300.0, g_s=2, back_epsilon=1.0, dimension=2, enable_mpi=True) ``` -------------------------------- ### Import necessary packages Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model.md Import the required libraries for the TBPLaS calculations. ```python import math import numpy as np import tbplas as tb ``` -------------------------------- ### Initialize and Extend Graphene Cell Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model_complex.md Create a graphene diamond primitive cell and extend it along specified dimensions using `tbplas` functions. ```python import tbplas as tb cell = tb.make_graphene_diamond() cell = tb.extend_prim_cell(cell, dim=(3, 3, 1)) cell.plot(with_conj=False) ``` -------------------------------- ### Enable 64-bit Array Indexing in TBPLaS Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/install.md Use this script to pre-process FORTRAN source files for the 64-bit array index version. This is necessary for very large models that might cause segmentation faults with the default 32-bit index. Note that MKL is not compatible with the 64-bit index. ```bash cd tbplas/fortran ../../scripts/set_int.py 64 ``` -------------------------------- ### Import necessary packages Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/quasi_eigen.md Imports the required libraries, numpy for numerical operations and tbplas for electronic structure calculations. ```python import numpy as np import tbplas as tb ``` -------------------------------- ### Visualize Wave Function Propagation Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/strain_fields.md Use the Visualizer class to plot the time-dependent wave function. This is useful for observing how the wave packet diffuses, interacts with boundaries, and forms interference patterns. ```python vis = tb.Visualizer() for i in range(len(time_log)): vis.plot_wfc(sample, np.abs(psi_t[i])**2, cmap="hot", scatter=False) ``` -------------------------------- ### Calculate Optical Conductivity in Parallel Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/advanced/parallel.md Evaluate the optical conductivity using the parallelized `Lindhard` calculator. Subsequent calls do not require special MPI treatment. ```python timer.tic("ac_cond") omegas, ac_cond = lind.calc_ac_cond(component="xx") timer.toc("ac_cond") vis.plot_xy(omegas, ac_cond) if vis.is_master: timer.report_total_time() ``` -------------------------------- ### Calculate and Visualize Band Structure Source: https://github.com/deepmodeling/tbplas/blob/master/doc/source/tutorial/prim_cell/model_complex.md Calculate the band structure for a given k-path and visualize it using `tbplas`. Ensure the k-points are defined appropriately for the desired ribbon edges (armchair or zigzag). ```python k_points = np.array([ [0.0, -0.5, 0.0], [0.0, 0.0, 0.0], [0.0, 0.5, 0.0], ]) k_label = ["X", "G", "X"] k_path, k_idx = tb.gen_kpath(k_points, [40, 40]) k_len, bands = gnr.calc_bands(k_path) vis = tb.Visualizer() vis.plot_bands(k_len, bands, k_idx, k_label) ``` ```python k_points = np.array([ [-0.5, 0.0, 0.0], [0.0, 0.0, 0.0], [0.5, 0.0, 0.0], ]) ``` -------------------------------- ### Create Supercell and Sample for Graphene Source: https://context7.com/deepmodeling/tbplas/llms.txt Generates a supercell from a primitive cell with specified dimensions and periodic boundary conditions. Vacancies can be introduced. Requires `tbplas`. ```python import tbplas as tb prim_cell = tb.make_graphene_diamond() # 3×3×1 supercell with periodic BC in a,b but open in c (2D) sc = tb.SuperCell(prim_cell, dim=(3, 3, 1), pbc=(True, True, False)) # Introduce vacancies (cell_a, cell_b, cell_c, orbital_index) sc.unlock() sc.set_vacancies(vacancies=[(1, 1, 0, 0), (2, 1, 0, 0)]) sc.trim() # remove dangling orbitals sample = tb.Sample(sc) sample.plot() ``` -------------------------------- ### Generate and Plot Graphene Band Structure Source: https://context7.com/deepmodeling/tbplas/llms.txt This snippet demonstrates how to generate a k-path for graphene and calculate its band structure using tbplas. It then visualizes the results. ```python cell = tb.wan2pc("graphene") k_path, k_idx = tb.gen_kpath( np.array([[0,0,0],[1/3,1/3,0],[1/2,0,0],[0,0,0]]), [40,40,40]) k_len, bands = cell.calc_bands(k_path) tb.Visualizer().plot_bands(k_len, bands, k_idx, ["G","K","M","G"]) ```