Basis
Hamster.AdaptiveInterpolator — Type
AdaptiveInterpolator(xmin::Float64, xmax::Float64, Ninit::Int64, Nmax::Int64, tol::Float64)A struct that defines the settings for adaptive interpolation.
Fields
xmin::Float64: The minimum value ofxin the interpolation range.xmax::Float64: The maximum value ofxin the interpolation range.Ninit::Int64: The initial number of sample points for the interpolation.Nmax::Int64: The maximum number of sample points allowed during the interpolation process.tol::Float64: The convergence tolerance. If the interpolation error falls below this value, the algorithm is considered to have converged.
Hamster.get_new_point! — Method
get_new_point(f, xmax, ymax, Nmax; max_iter=10000)Generate a new point xnew for function sampling based on the gradient and curvature of the function f. This function prioritizes areas of the function with high curvature or gradient, to improve sampling in regions with rapid changes.
Arguments
f: The function to sample from. Assumed to have fieldsxscontaining previous sample points.xmax: The maximum possible value forx.ymax: The maximum possible value of the functionfover the sampled points.Nmax: The maximum number of points that can be generated.max_iter: Maximum number of iterations to attempt generating a new point (default is10000).
Returns
xnew: A new sampled pointxnewthat is in a region with either high gradient or high curvature, and sufficiently far from existing points inf.xs.
Hamster.insertxy! — Method
insertxy!(xs, ys, xnew, ynew)Insert a new point (xnew, ynew) into two vectors xs and ys, which are assumed to be paired coordinates, while maintaining the sorted order of xs.
Arguments
xs: A vector ofxvalues (assumed to be sorted in ascending order).ys: A vector ofyvalues corresponding toxs.xnew: The newxvalue to insert intoxs.ynew: The newyvalue to insert intoys, corresponding toxnew.
Hamster.interpolate_f — Method
interpolate_f(itper::AdaptiveInterpolator, f::Function)Adaptive interpolation of a given function f using an AdaptiveInterpolator. The function is sampled at adaptive points and interpolated using cubic splines until convergence is reached or the maximum number of samples (Nmax) is exceeded.
Arguments
itper::AdaptiveInterpolator: An instance of theAdaptiveInterpolatorstruct that defines the interpolation settings, such as the initial number of points, the maximum allowed number of points (Nmax), and the convergence tolerance.f::Function: The function to interpolate.
Returns
xs: A vector ofxvalues where the function has been evaluated.ys: A vector ofyvalues (f(xs)) corresponding to thexvalues.
Hamster.Basis — Type
Basis(strc::Structure, conf=get_empty_config()) -> BasisConstruct a Basis object from a given Structure and configuration.
Arguments
strc::Structure: TheStructureobject representing the atomic or molecular structure for which the basis is being constructed.conf: (Optional) The configuration object that holds parameters to control the basis construction. Defaults toget_empty_config().
Returns
Basis: ABasisobject.
Hamster.Basis — Type
struct Basis{Orb, Ov, P, R}A data structure that represents the basis of a system, containing information about orbitals, overlap integrals, parameters, and precomputed radial functions (RLLM).
Fields
orbitals::Orb: A collection of orbitals for each ion in the system. This typically contains the orbital functions and axes associated with each ion.overlaps::Ov: A collection of overlap integrals between orbitals. These overlap integrals define how the orbitals interact with each other spatially.parameters::P: Parameters used for computing the matrix elements between orbitals. These can include interaction strengths, angular momentum values, and other system-specific constants.rllm::R: Precomputed radial functions (RLLM), typically stored as spline objects for efficient interpolation. These functions depend on the distance between ions and are used in overlap integrals.
Base.length — Method
length(basis::Basis) -> IntCompute the total number of orbitals in the basis.
Arguments
basis::Basis: TheBasisobject containing orbitals for each ion in the system.
Returns
Int: The total number of orbitals, calculated by summing the lengths of the orbital sets for all ions in thebasis.
Hamster.get_bonds — Function
get_bonds(strc, basis, conf=get_empty_config();
rcut=get_rcut(conf),
rcut_tol=get_rcut_tol(conf),
npar=get_nthreads_bands(conf))Construct bond vectors between basis orbitals for all lattice translations.
This function computes inter-ionic bond displacement vectors within a cutoff radius and assembles them into sparse matrices indexed by basis orbitals. For each lattice translation R, a sparse matrix of size Nε × Nε is returned, where Nε = length(basis) and each nonzero entry stores the Cartesian bond vector connecting a pair of orbitals.
Arguments
strc: Structure object containing ion positions, lattice vectors, and lattice translations.basis: Orbital basis associated with the ions instrc.conf: Configuration object.
Keyword Arguments
rcut: Real-space cutoff radius for bond construction.rcut_tol: Tolerance applied to the cutoff condition.npar: Number of parallel chunks used for bond generation.
Returns
bonds::Vector{SparseMatrixCSC{SVector{3,Float64},Int64}}: A vector of sparse matrices, one for each lattice translationR, whose nonzero entries store Cartesian bond vectors asSVector{3,Float64}.
Hamster.get_geometry_tensor — Function
get_geometry_tensor(strc, basis, conf=get_empty_config(); tmethod=get_tmethod(conf), rcut=get_rcut(conf))Constructs the geometry tensor based on the structure of the system, the orbital basis, and configuration settings.
Arguments
strc: The structure object, containing information about ions, lattice, and geometry of the system.basis: The basis object, containing the orbital information and overlap parameters.conf: Configuration object, defaults to an empty configuration if not provided.tmethod: Transformation method used for coordinate system alignment (default is obtained from the configuration).rcut: Cutoff distance for nearest neighbor interactions (default is obtained from the configuration).
Keyword Arguments
tmethod: The transformation method for aligning coordinate systems.rcut: The distance cutoff for nearest neighbor interactions.
Returns
- The reshaped geometry tensor, represented as a matrix of sparse matrices, which encodes the overlap contributions for the system's orbital interactions for each parameter.
Hamster.get_oc_and_mode_dicts — Method
get_oc_and_mode_dicts(overlaps, ions)Generate dictionaries that map ion pairs to their respective orbital configuration (oc) and mode types for each overlap configuration.
Arguments
overlaps::Vector: A collection of overlap configurations, where each element represents a different overlap calculation.ions::Vector: A vector of ion types, where each ion has atypefield that identifies the specific ion type.
Returns
oc_dicts::Vector{Dict{IonLabel, Union{SymOrb, DefOrb, MirrOrb}}}: A vector of dictionaries, each corresponding to one overlap configuration, mapping ion pairs (represented byIonLabel) to their respective orbital configuration (SymOrb,DefOrb, orMirrOrb).mode_dicts::Vector{Dict{IonLabel, Union{NormalMode, ConjugateMode}}}: A vector of dictionaries, each corresponding to one overlap configuration, mapping ion pairs (represented byIonLabel) to their respective mode type (NormalModeorConjugateMode).
Hamster.get_param_index — Method
get_param_index(overlap, nnlabel, parameters, orb1, orb2, i, j) :: Int64Retrieve the index of a parameter that matches a given nearest neighbor label, overlap label, orbital types, and ion labels.
Arguments
overlap: An object representing the overlap between two orbitals or ions.nnlabel::Int: The nearest neighbor (NN) label, identifying if this is a nearest neighbor interaction.parameters::Vector: A vector of parameter objects, each of which contains attributes such asnnlabel,overlap_label, andion_label.orb1: The first orbital involved in the overlap.orb2: The second orbital involved in the overlap.i::Int: The index of the first orbital.j::Int: The index of the second orbital.
Returns
Int64: The indexvof the parameter in theparametersvector that matches the conditions. If no match is found, the function returns0.
Hamster.nparams — Method
nparams(basis::Basis) -> IntReturn the number of TB overlap parameters defined in basis.
Arguments
basis::Basis: TheBasisobject containing orbitals for each ion in the system.
Returns
Int: The total number of parameters.
Hamster.overlap_contributes_to_matrix_element — Method
overlap_contributes_to_matrix_element(overlap, orb1, orb2, ion_label)Return true if overlap contributes to the matrix element between the orbitals orb1 and orb2 for ion_label.
Arguments
overlap: The overlap object, which contains information about the types of orbitals involved and the ion label.orb1: The first orbital.orb2: The second orbital.ion_label: The ion label to check if the overlap corresponds to the same type of ions as the orbitals.
Returns
Bool: Returnstrueif the overlap contributes to the matrix element, i.e., if the orbital types oforb1andorb2match the types in the overlap, and theion_labelmatches.
Hamster.reshape_geometry_tensor — Method
reshape_geometry_tensor(h_dict, NV, NR, Nε)Reshapes the geometry tensor from a dictionary h_dict into a matrix of sparse matrices.
Arguments
h_dict::Dict: A dictionary where keys are tuples of the form(v, i, j, R)representing the tensor indices, and values are the corresponding tensor entries.NV::Int: Number of rows (vectors) in the reshaped matrix.NR::Int: Number of columns (points) in the reshaped matrix.Nε::Int: Not used explicitly in this function but typically represents the number of strain components.
Returns
- A
NV x NRmatrixh_outwhere each element is a sparse matrix (SparseMatrixCSC{Float64, Int64}) formed by the corresponding indices and values from the input dictionaryh_dict.
Hamster.get_index_to_ion_orb_map — Method
get_index_to_ion_orb_map(Norb) -> Vector{Tuple{Int64, Int64}}Generate a mapping from basis state indices to corresponding ion and orbital indices.
Arguments:
Norb: A vector where each element represents the number of orbitals associated with each ion.
Returns:
index_map: A vector of tuples where each tuple(iion, iorb)represents the ion and orbital index corresponding toi.
Hamster.get_ion_and_orbital_indices — Method
get_ion_and_orbital_indices(Norb, index) -> Tuple{Int64, Int64}Return the ion index iion and the orbital index jorb corresponding to the basis-state index index in the Hamiltonian matrix.
Arguments:
Norb: A vector where each element represents the number of orbitals for each ion.index: The basis-state index for which the corresponding ion and orbital indices are sought.
Returns:
iion: The index of the ion corresponding to the givenindex.jorb: The index of the orbital for the ioniioncorresponding toindex.- If
indexis out of bounds, returns(0, 0)as a fallback.
Hamster.get_ion_orb_to_index_map — Method
get_ion_orb_to_index_map(Norb) -> Dict{Tuple{Int64, Int64}, Int64}Generate a mapping from ion and orbital indices to a basis state index.
Arguments:
Norb: A vector where each element represents the number of orbitals associated with each ion.
Returns:
ij_map: A dictionary where each key is a tuple(i_ion, i_orb)representing the ion indexi_ionand the orbital indexi_orb. The value corresponding to each key is the basis state indexi.
Hamster.IonLabel — Type
IonLabel(types::SVector{2, UInt8})A structure representing a label for overlaps between two ions, characterized by a 2-element static vector of integers that indicate the ion species.
Fields
types::SVector{2, UInt8}: A static vector containing twoInt64values representing the types or identifiers associated with the ion. The use ofSVector{2, Int64}ensures that the two types are stored efficiently as a fixed-size array.
Constructors
IonLabel(type1::Int64, type2::Int64; sorted=true): Creates anIonLabelfrom two integer types. Ifsorted=true, the types will be sorted before creating the label, ensuring consistent ordering.IonLabel(type1::String, type2::String; sorted=true): Creates anIonLabelfrom two element symbols (asStrings). Converts the symbols to atomic numbers and optionally sorts them ifsorted=true.
Base.isequal — Method
Base.isequal(ion_label1::IonLabel, ion_label2::IonLabel; sorted=false) -> BoolCompares two IonLabel objects for equality.
Arguments
ion_label1::IonLabel: The firstIonLabelinstance to compare.ion_label2::IonLabel: The secondIonLabelinstance to compare.sorted::Bool=false: Whether to sort thetypesfields of bothIonLabelinstances before comparing them. Defaults tofalse.
Returns
Bool: Returnstrueif theIonLabelinstances are considered equal based on theirtypesfields (with or without sorting), andfalseotherwise.
Base.string — Method
string(ion_label::IonLabel) -> StringConverts an IonLabel object into a human-readable string representation, where the types are converted into their corresponding element symbols.
Arguments
ion_label::IonLabel: TheIonLabelinstance containing two atomic types represented as atomic numbers.
Returns
String: A string representation of theIonLabel, where the two element numbers are converted to their respective element symbols and concatenated with a+sign.
Hamster.aresameions — Method
sameions(ion_label::IonLabel) -> BoolChecks if both ions in the given IonLabel are of the same type.
Arguments
ion_label::IonLabel: TheIonLabelobject that contains two ion types represented as atomic numbers.
Returns
Bool: Returnstrueif both ions in theIonLabelhave the same atomic number, meaning they are the same type of ion; otherwise, returnsfalse.
Hamster.areswapped — Method
areswapped(type1, type2) -> BoolDetermines whether the two ion types type1 and type2 are swapped when creating an IonLabel. This function returns true if the unsorted IonLabel(type1, type2, sorted=false) differs from the sorted IonLabel(type1, type2), indicating that the order of type1 and type2 was altered during sorting. Otherwise, it returns false.
Arguments
type1: The first ion type.type2: The second ion type.
Returns
Bool:trueif the order oftype1andtype2is swapped in the sortedIonLabel,falseotherwise.
Hamster.get_nn_label — Function
get_nn_label(r, r_thresh, onsite, sepNN) :: Int64Returns the nearest neighbor (NN) label (0, 1, 2) for a matrix element based on the interatomic distance r, a nearest neighbor threshold r_thresh, and flags for onsite and sepNN (separated nearest neighbors).
Arguments
r::Float64: The interatomic distance between two atoms.r_thresh::Float64: The threshold distance for determining nearest neighbors.onsite::Bool: A flag indicating if onsite interactions (i.e., whenr ≈ 0) should be considered separately.sepNN::Bool: A flag indicating if nearest neighbors should be separated into multiple groups based on distance.
Returns
- An integer label (
Int64) representing the type of interaction.
Hamster.string_to_overlap_label — Method
string_to_overlap_label(overlap_string::String) -> SVector{3, Int64}Converts an overlap_string into an overlap label, represented as a 3-element static vector of integers. The overlap label consists of two angular momentum indices (l1, l2) and a magnetic quantum number (m).
Arguments
overlap_string::String: A string representing the overlap label. This string can indicate diagonal or off-diagonal onsite interactions or hybridized orbitals.
String Parsing
- If the string contains
"diag", it represents a diagonal or off-diagonal onsite interaction.- If it's diagonal,
l1andl2will be the same value. - If it's off-diagonal, the string may represent hybrid orbitals or a combination of atomic and hybrid orbitals.
- Based on the length of
ll_string,l1andl2are parsed:- Length 2: Represents two atomic orbitals (e.g.,
"diag12"). - Length 3: Combination of hybrid and atomic orbitals (e.g.,
"diag-12"). - Length 4: Only hybrid orbitals (e.g.,
"diag-1213").
- Length 2: Represents two atomic orbitals (e.g.,
mis set to0for diagonal and1for off-diagonal onsite interactions to differentiate between them.
- If it's diagonal,
- If the string does not contain
"diag", it represents an offsite overlap, andl1,l2, andmare determined using lookup tables (ldict_invandmdict_inv).
Returns
SVector{3, Int64}: A static vector where:l1: First angular momentum index.l2: Second angular momentum index.m: Magnetic quantum number (or other integer differentiating diagonal and off-diagonal cases).
Hamster.DefOrb — Type
DefOrb()No symmetry in orbitals: orbital type in label has to be used in the same order as given.
Hamster.MirrOrb — Type
MirrOrb()No symmetry in orbitals: orbital type in label has to be used in reverse order as given.
Hamster.OrbitalConfiguration — Type
OrbitalConfigurationAbstract type for defining the configuration of orbitals w.r.t. to the overlap label for a specific TB overlap.
Subtypes:
SymOrb: Symmetry in orbitals allows for interchangeable orbital types in labels.DefOrb: No symmetry; the order of orbital types in labels must be preserved exactly.MirrOrb: Symmetry requires orbital types to be used in reverse order.
Hamster.OrbitalConfiguration — Method
OrbitalConfiguration(Y1, Y2, Ys1, Ys2; sameions=true, ionswap=false) -> OrbitalConfigurationDetermine the OrbitalConfiguration type based on the symmetry and relationship between two orbitals, Y1 and Y2, and their corresponding sets Ys1 and Ys2. This function decides the appropriate orbital symmetry configuration based on the angular momentum and ion types involved.
Arguments
Y1: The first orbital (expected to have anlproperty for angular momentum).Y2: The second orbital (expected to have anlproperty for angular momentum).Ys1: Set of orbitals corresponding to the first ion.Ys2: Set of orbitals corresponding to the second ion.sameions(optional, default=true): A boolean indicating whether both orbitals belong to the same ion type.ionswap(optional, default=false): A boolean indicating whether the ion types are swapped in the configuration.
Returns:
- Either
SymOrb,DefOrborMirrOrb.
Hamster.SymOrb — Type
SymOrb()Symmetry in orbitals: orbital type in label can be interchanged.
Example
<Ga_pσ|As_pσ>
In this case, both orbitals are equal and the label ppσ is symmetric.Hamster.get_mode — Method
get_mode(mode_dicts, kparam, ion_label, iorb, jorb)Retrieve the mode (mode) for a given ion label and orbital indices.
Arguments
mode_dicts: A vector of dictionaries where each dictionary mapsIonLabels to their respective mode (e.g.,NormalMode,ConjugateMode). Each entry corresponds to a different k-point parameter (kparam).kparam: The k-point parameter index indicating which dictionary inmode_dictsto use.ion_label: The label identifying the ion pair for which the mode is needed.iorb: The index of the first orbital in the pair.jorb: The index of the second orbital in the pair.
Returns
mode: The mode corresponding to the givenion_label, after potentially checking for a conjugate mode usingcheck_for_conjugate_mode.
Hamster.get_orbconfig — Method
get_orbconfig(oc_dicts, kparam, ion_label, iorb, jorb)Retrieve the orbital configuration (orbconfig) for a given ion label and orbital indices.
Arguments
oc_dicts: A vector of dictionaries where each dictionary mapsIonLabels to their respective orbital configurations (orbconfig). Each entry in the dictionary corresponds to a different k-point parameter (kparam).kparam: The k-point parameter index indicating which dictionary inoc_dictsto use.ion_label: The label identifying the ion pair for which the orbital configuration is needed.iorb: The index of the first orbital in the pair.jorb: The index of the second orbital in the pair.
Returns
orbconfig: The orbital configuration (orbconfig) after potentially checking for a conjugate configuration usingcheck_for_conjugate_orbconfig.
Hamster.Orbital — Type
Orbital{O<:Angular}(ion_type::Int64, type::O, axis::SVector{3, Float64})Defines an orbital associated with an ion, characterized by its type, angular momentum properties, and orientation.
Type Parameters
O<:Angular: Specifies the angular momentum type, such as s, p, or d orbitals.
Fields
ion_type::UInt8: An integer representing the type or species of the ion this orbital is associated with.type::O: The angular momentum type of the orbital, parameterized byO, which defines the orbital's angular properties (e.g., s, p, d orbitals).axis::SVector{3, Float64}: A 3D unit vector representing the orientation or axis of the orbital in Cartesian coordinates.
Hamster.get_axes — Function
get_axes(iion::Int64, strc::Structure, orbital_list::Vector{Angular}, conf=get_empty_config(); NNaxes=get_nnaxes(conf, type))Compute the axes (or orientations) for a set of orbitals associated with a specific ion in a structure.
Arguments
iion::Int64: The index of the ion for which to compute the axes.strc::Structure: AStructureobject representing the lattice and ion configuration.orbital_list::Vector{Angular}: A vector containing angular orbital types (e.g.,s,p,sp3) for which axes need to be computed.conf: Configuration object (optional) that contains settings for computing axes. Default isget_empty_config().NNaxes: A Boolean flag that determines whether to compute nearest-neighbor axes (true) or directly use predefined orbital axes (false).
Hamster.get_axes_from_orbitals — Method
get_axes_from_orbitals(orbitals::Vector{Vector{Orbitals}}]) -> Vector{Matrix{3, Norb}}Reads the orbital axes from a nested Vector of Orbital and returns them as a Vector of matrices.
Arguments
orbitals::Vector{Vector{Orbital}}: A vector where each element is a vector ofOrbital.
Hamster.get_axis — Method
get_axis(h::HybridOrbital) -> Vector{SVector{3, Float64}}
get_axis(o::AngularOrbital) -> SVector{3, Float64}Returns the unit vector(s) representing the axis (or axes) of the given orbital type.
Orbital Types and Axes
h::sp3: Returns four unit vectors corresponding to the axes ofsp3(orsp3dr2) hybrid orbitals:[1, 1, 1],[1, -1, -1],[-1, 1, -1],[-1, -1, 1].o::s: Returns the axis[0, 0, 1]for ansorbital.o::px: Returns the axis[1, 0, 0]for apxorbital.o::py: Returns the axis[0, 1, 0]for apyorbital.o::pz: Returns the axis[0, 0, 1]for apzorbital.o::pxdx2: Returns the axis[1, 0, 0]for a combinedpx/dx²orbital.o::pydy2: Returns the axis[0, 1, 0]for a combinedpy/dy²orbital.o::pzdz2: Returns the axis[0, 0, 1]for a combinedpz/dz²orbital.
Hamster.get_orbitals — Function
get_orbitals(strc::Structure, conf=get_empty_config())Generate a list of orbitals for the ions in a given Structure object, using a configuration for the orbital types and axes.
Arguments
strc::Structure: The structure containing ions and their corresponding positions and types.conf: Configuration object that defines how to retrieve orbital information for the given ions. Defaults toget_empty_config()if no configuration is provided.
Returns
orbitals::Vector{Orbital}: A vector ofOrbitalobjects, where each orbital corresponds to a specific ion in the structure.
Details
- The function loops over all ions in the given structure (
strc), retrieves the orbital types for each ion based on the ion's type, and generates corresponding axes. - For each ion, it constructs the associated orbitals, considering the ion's type, angular properties, and orientation (axes).
- It then stores the orbitals as
Orbitalobjects in a vector.
Hamster.TBOverlap — Type
TBOverlap{T<:MatrixElement, OC<:OrbitalConfiguration}Represents a tight-binding (TB) overlap used in calculations, characterized by its type, orbital configuration, and ion label. This represents one interaction term.
Fields
type::T: Specifies the type of the TB overlap parameter, whereTis a subtype ofMatrixElement. This field indicates the specific kind of matrix element or overlap parameter.orbconfig::OC: Represents theOrbitalConfigurationassociated with the TB overlap parameter.ion_label::IonLabel: Labels the ions that are involved in the interaction term.
Hamster.Vddδ — Type
VddδOverlap parameter for overlaps between two d-orbitals with |m|=2.
Hamster.Vddπ — Type
VddπOverlap parameter for overlaps between two d-orbitals with |m|=1.
Hamster.Vddσ — Type
VddσOverlap parameter for overlaps between an s- and a d-orbital with |m|=0.
Hamster.Vpdπ — Type
VpdπHamster.Vpdσ — Type
VpdσHamster.Vppπ — Type
VppπHamster.Vppσ — Type
VppσHamster.Vsdσ — Type
VsdσHamster.Vspσ — Type
VspσHamster.Vssσ — Type
VssσBase.isequal — Method
Base.isequal(ov1::TBOverlap, ov2::TBOverlap)Compare two TBOverlap objects, ov1 and ov2, for equality.
Arguments
ov1::TBOverlap: The firstTBOverlapinstance.ov2::TBOverlap: The secondTBOverlapinstance.
Returns
Bool:trueif the twoTBOverlapinstances are considered equal,falseotherwise.
Base.string — Method
Base.string(p::TBOverlap; apply_oc=false)::StringConverts a TBOverlap instance into a string, e.g., "Ga+As_ssσ". Ifapply_oc=true, theOrbitalConfigurationis taken into account. This is only relevant fororbconfig<:MirrOrb, where the order of orbitals in the label is inverted, e.g., the overlapspσ`withorbconfig<:MirrOrbwould becomepsσ`.
Arguments
p::TBOverlap: TheTBOverlapinstance to be converted into a string.apply_oc::Bool: A flag indicating whether to apply orbital configuration-specific formatting.
Hamster.NConst — Method
NConst(baseorb, l₁, l₂)Determine the normalization constant for the matrix element between orbitals in baseorb with respective components l₁ and l₂.
Hamster.decide_orbconfig — Method
decide_orbconfig(Vllm, ion_label)Conjugate the orbital configuration if the sorted ion overlap label of the TB parameter Vllm is the conjugate of the actual ion overlap label ion_label of the respective Hamiltonian matrix element.
Hamster.get_baseorb_ls — Method
get_baseorb_ls(overlap::TBOverlap) -> Tuple{Int, Int}Extract the orbital angular momentum quantum numbers l for the two orbitals in the baseorb field of the given TBOverlap object.
Arguments
overlap::TBOverlap: ATBOverlapobject representing the overlap between two orbitals in a tight-binding model. Thebaseorbfield contains information about the two orbitals.
Returns
- A tuple
(l1, l2)wherel1is the angular momentum quantum number of the first orbital andl2is that of the second orbital.
Hamster.get_overlaps — Function
get_overlaps(ions, orbitals, conf=get_empty_config())Compute all tight-binding (TB) overlaps between pairs of orbitals for a given list of ions.
Arguments
ions: A vector of ions from which overlaps are to be computed.orbitals: A vector of orbitals corresponding to each ion inions.conf: Optional configuration parameter (default:get_empty_config()).
Returns
Vector{TBOverlap}: A vector containing all computedTBOverlapinstances for the ion and orbital pairs.
Hamster.get_overlaps_for_orbitals — Method
get_overlaps_for_orbitals(orbitals_1, orbitals_2, ion_label, ionswap)Compute the list of tight-binding (TB) overlaps for pairs of orbitals from two ions (orbitals_1 and orbitals_2) based on the given ion_label and whether the ions are swapped (ionswap).
Arguments
orbitals_1: A collection of orbitals from the first ion.orbitals_2: A collection of orbitals from the second ion.ion_label: AnIonLabelinstance representing the ion types involved in the interaction.ionswap: A boolean flag indicating if the ions are swapped in the interaction.
Returns
Vector{TBOverlap}: A unique list ofTBOverlapinstances describing the possible overlaps between the orbitals of the two ions, taking into account symmetry and ion swaps.
Hamster.me_to_overlap_label — Method
me_to_overlap_label(me::MatrixElement) -> SVector{3, Int64}Converts the matrix element me to an overlap label with l, l', m as a static array.
Hamster.same_ion_label — Method
same_ion_label(Vllm, ion_label)Return true if the TB overlap Vllm has the ion overlap ion label ion_label independently if either is sorted.
Hamster.ParameterLabel — Type
ParameterLabel(nnlabel::Int64, ion_label::IonLabel, overlap_label::SVector{3, Int64})Represents a tight-binding (TB) parameter label by uniquely identifying it based on its nearest neighbor (NN) label, ion label, and overlap label.
Fields
nnlabel::Int64: An integer representing the nearest neighbor (NN) label, which identifies a specific neighbor interaction.ion_label::IonLabel: AnIonLabelobject representing the two ion types involved in the TB parameter.overlap_label::SVector{3, Int64}: A 3D static vector representing the overlap label in terms ofll'm.
Base.string — Method
string(param_label::ParameterLabel) -> StringReturns a string representation of the ParameterLabel object by concatenating its nearest neighbor label (nnlabel), ion label (ion_label), and overlap label (overlap_label).
Arguments
param_label::ParameterLabel: TheParameterLabelobject containing information about nearest neighbors, ions, and overlap.
String Formatting
- Nearest neighbor (
nnlabel) is prefixed with"NN"(e.g.,"NN1"). - Ion label is converted to string using
string(param_label.ion_label). - The overlap string is constructed based on the
nnlabelvalue:- For
nnlabel ≠ 0: The overlap string is constructed fromldictandmdictdictionaries using the first two elements ofoverlap_label. - For
nnlabel == 0:- If
overlap_label[3] == 0: The overlap string is"diag"followed by the angular momentum indexl. - Otherwise, the overlap string is
"offdiag"followed by two angular momentum indicesl1andl2.
- If
- For
Returns
- A concatenated string in the form, e.g.,
NN1_Ga+As_ssσ.
Hamster.check_consistency — Method
check_consistency(conf_values, conf::Config) -> BoolChecks the consistency of configuration values from a file with the given Config object.
Arguments
conf_values::Dict{String, String}: A dictionary of configuration values read from the file (e.g.,rcut,onsite,sepNN,_n, and_alphavalues).conf::Config: AConfigobject containing the expected values for comparison.
Returns
Bool: Returnstrueif all values inconf_valuesare consistent with the values inconf, otherwise returnsfalse.
Hamster.get_ion_types_from_parameters — Method
get_ion_types_from_parameters(parameters) -> Vector{String}Extract and return a unique list of ion types from a given list of parameters.
Each parameter contains an ion_label that consists of two ion types concatenated by a "+" sign. This function splits the ion labels, and collects the unique ion types into a single vector.
Arguments
parameters::Vector: A vector of parameter objects where each parameter has anion_label.
Returns
- A vector of unique ion types (as strings) extracted from the
ion_labelfield of the parameters.
Hamster.get_onsite_parameters! — Method
get_onsite_parameters!(parameters::Vector{ParameterLabel}, overlaps::Vector{TBOverlap})Populate the parameters vector with onsite tight-binding parameters based on the given overlaps between orbitals.
This function identifies onsite interaction terms (where both orbitals belong to the same ion) and adds corresponding ParameterLabel objects to the parameters vector. These labels represent the interaction of orbitals of the same type (onsite) and account for angular momentum quantum numbers (l₁, l₂).
Arguments
parameters::Vector{ParameterLabel}: A vector of tight-binding parameter labels, which will be populated with new onsite parameters.overlaps::Vector{TBOverlap}: A vector ofTBOverlapobjects representing the overlap between orbitals. The function filters those with the same ion type for onsite interactions.
Hamster.get_parameter_for_nn_label! — Method
get_parameter_for_nn_label!(parameters::Vector{ParameterLabel}, overlaps::Vector{TBOverlap}, nn_label::Int)Populate the parameters vector with tight-binding parameters for a given nearest-neighbor (NN) interaction label (nn_label), based on the provided orbital overlaps.
This function takes a list of orbital overlaps and assigns them a specified nearest-neighbor label (nn_label), creating a ParameterLabel for each overlap. These labels capture the interaction between orbitals at different distances (nearest-neighbor interactions).
Arguments
parameters::Vector{ParameterLabel}: A vector of tight-binding parameter labels to be populated with new nearest-neighbor parameters.overlaps::Vector{TBOverlap}: A vector ofTBOverlapobjects representing the overlaps between orbitals.nn_label::Int: The nearest-neighbor label that defines the type of interaction (e.g., first-nearest-neighbor, second-nearest-neighbor).
Hamster.get_parameters_from_overlaps — Function
get_parameters_from_overlaps(overlaps::Vector{TBOverlap}, conf::Config=get_empty_config(); sepNN::Bool=get_sepNN(conf), onsite::Bool=get_onsite(conf)) -> Vector{ParameterLabel}Generate tight-binding parameters (ParameterLabel) from orbital overlaps, including onsite and nearest-neighbor interactions.
This function computes a list of ParameterLabel objects based on the given orbital overlaps. It determines whether to include onsite parameters, first-nearest-neighbor (NN) parameters, and optionally second-nearest-neighbor (NN) parameters, depending on the configuration.
Arguments
overlaps::Vector{TBOverlap}: A vector of orbital overlap objects representing the interactions between orbitals.conf::Config: A configuration object that specifies how parameters should be generated (default is an empty config).sepNN::Bool: A keyword argument (default fromconf) indicating whether second-nearest-neighbor interactions should be included (trueif included,falseotherwise).onsite::Bool: A keyword argument (default fromconf) indicating whether onsite parameters should be included (trueif included,falseotherwise).
Returns
- A
Vector{ParameterLabel}containing the tight-binding parameters based on the overlaps, including:- Onsite parameters (if
onsite=true). - First-nearest-neighbor parameters (always included).
- Second-nearest-neighbor parameters (if
sepNN=true).
- Onsite parameters (if
Hamster.read_params — Function
read_params(filename="params.dat")Reads and parses a parameter file generated by write_params into tight-binding (TB) parameters, parameter values, ion types, SOC parameters, and system configuration.
Arguments
filename::String="params.dat": The name of the file to read (default is"params.dat").
Returns
parameters::Vector{ParameterLabel}: A vector of TB parameter labels.parameter_values::Vector{Float64}: A vector of corresponding TB parameter values.ion_types::Vector{String}: A vector of ion types for which SOC parameters are defined (if any).soc_parameters::Vector{Float64}: A vector of SOC parameters corresponding to theion_types(if any).conf_values::Dict{String, String}: A dictionary containing the configuration values from the header section (if present), such as system type,rcut,onsite, etc.
Hamster.same_param_label — Method
same_param_label(nnlabel::Int64, ion_label::IonLabel, overlap_label::SVector{3, Int64}, param_label::ParameterLabel) -> BoolCheck if the given nearest-neighbor label (nnlabel), ion label (ion_label), and overlap label (overlap_label) are the same as those in the param_label.
Arguments
nnlabel::Int64: The nearest-neighbor label to compare with thennlabelinparam_label.ion_label::IonLabel: The ion label to compare with theion_labelinparam_label.overlap_label::SVector{3, Int64}: The overlap label to compare with theoverlap_labelinparam_label.param_label::ParameterLabel: The parameter label to compare against.
Returns
Bool: Returnstrueif all components (nnlabel,ion_label,overlap_label) match those of the givenparam_label, otherwise returnsfalse.
Hamster.string_to_param_label — Method
string_to_param_label(string_label)Convert a string parameter label string_label to a ParameterLabel.
Hamster.write_params — Function
write_params(parameters::Vector, parameter_values::Vector, ion_types::Vector=[], soc_parameters::Vector=[], conf::Config=get_empty_config(); filename="params")
write_params(parameters, parameter_values, conf::Config; filename="params")Writes the tight-binding (TB) parameters, system configuration, and optional spin-orbit coupling (SOC) parameters to a .dat file.
Arguments
parameters::Vector: A vector of TB parameter labels (ParameterLabel) that describe the system.parameter_values::Vector: A vector of parameter values corresponding to theparameters.ion_types::Vector=[]: A vector of ion types for which SOC parameters are defined (optional).soc_parameters::Vector=[]: A vector of SOC parameters corresponding to the ion types (optional).conf::Config: A configuration object that holds various settings for the system (e.g., system type,rcut,onsite, etc.).filename::String="params": The base filename (without extension) for the output file (optional, default is"params").
Keyword Arguments
filename: The name of the file (excluding the extension) to which the data will be written (default:"params").
File Format
The file written contains the following:
- System configuration block: Includes details like
rcut,onsite,sepNN, and alpha/n values for each unique ion type. - Tight-binding parameters: Parameters and corresponding values, formatted to align in a readable manner.
- SOC parameters (optional): SOC values for each ion type, if provided.
Hamster.distance_dependence — Method
distance_dependence(ME::MatrixElement, orbconfig::OrbitalConfiguration, r, ns, αs)Computes the distance-dependent interaction between two orbitals, based on their matrix element ME and orbital configuration orbconfig.
Arguments
ME::MatrixElement: The matrix element representing the interaction type.orbconfig::OrbitalConfiguration: The configuration of the orbitals involved in the interaction, which determines the orbital angular momenta.r: The distance between the two orbitals in the interaction.ns: A vector containing the quantum numbersnfor the two orbitals.αs: A vector containing the exponential decay factorsαfor the two orbitals.
Returns
- The integral
Iof the overlap function between the two orbitals over the given distancer, modified by a sign factor if necessary.
Hamster.fcut — Method
fcut(r, rcut)Cut-off function whose value smoothly transitions to zero as r approaches rcut. Ensures continuity by using a cosine-based smoothing function.
Arguments
r: The input distance.rcut: The cutoff radius beyond which the function returns zero.rcut_tol: A tolerance applied to the cut-off radius, can be positive or negative.
Returns
- A smoothly varying value between 1 and 0, with
fcut(r, rcut) = 0forr > rcut.
Hamster.get_rllm_from_file — Function
get_rllm(overlaps, conf=get_empty_config(); load_rllm=get_load_rllm(conf), rllm_file=get_rllm_file(conf), interpolate_rllm=get_interpolate_rllm(conf))Retrieves or computes the radial orbital integral look-up table (RLLM) for a given set of overlaps, based on configuration settings.
Arguments
overlaps::Vector: A list of overlap objects for which RLLM data is required.conf::Config: Configuration object controlling the behavior of RLLM retrieval or generation. Defaults to an empty configuration.comm: (Keyword argument) MPI communicator, defaults tonothing.load_rllm::Bool: (Keyword argument) Iftrue, load the RLLM data from a file. The file location is provided byrllm_file. Defaults to the value fromconf.rllm_file::String: (Keyword argument) Filename for loading or saving the RLLM data. Defaults to the value fromconf.interpolate_rllm::Bool: (Keyword argument) Iftrue, interpolate new RLLM data based on the overlaps and save it to a file. Defaults to the value fromconf.verbosity::Int: (Keyword argument) Controls level of verbosity.
Returns
rllm_dict::Dict{String, CubicSpline}: A dictionary mapping overlap string representations to cubic spline interpolations of the radial integrals. Ifload_rllmistrue, the data is read from the file. Ifinterpolate_rllmistrue, it is interpolated and saved.
Hamster.interpolate_overlap — Method
interpolate_overlap(overlap, conf::Config)Interpolates an overlap and stores the resulting cubic spline in the overlap's rllm field.
Arguments
overlap: An overlap object that contains information about the interaction type and orbital configuration.conf::Config: A configuration object that provides values for parameters such asnandαfor each ion type involved in the overlap.
Hamster.precalc_rllm — Function
precalc_rllm(bases, conf=get_empty_config();
comm=nothing,
rank=0,
nranks=1,
rllm_file=get_rllm_file(conf),
verbosity=get_verbosity(conf))Precomputes overlap distance dependence interpolation tables for a set of basis functions. Distributes the computation across MPI ranks and saves the results to a file.
Arguments
bases: Vector ofBasisobjects for which the overlaps are computed.conf: Configuration object containing simulation and ML parameters.comm: MPI communicator for distributed computation.rank: Integer rank of the current MPI process.nranks: Total number of MPI ranks participating in the computation.rllm_file: Filename to save the RLLM interpolation data.verbosity: Integer controlling output logging.
Hamster.read_rllm — Method
read_rllm(filename="rllm.dat") -> Dict{String, Tuple{Vector{Float64}, Vector{Float64}}}Reads the rllm.dat file and returns a dictionary mapping overlap labels to tuples of vectors containing the x and y values.
Arguments
filename::String: The name of the file containing Rllm data. Defaults to"rllm.dat".
Returns
- A dictionary where each key is an overlap label, and each value a tuple of x/y value vectors.
Hamster.save_rllm — Method
save_rllm(overlaps; filename="rllm.dat")Saves overlap data, including the associated Rllm values, to a file.
Arguments
rllm_dict: A collection of overlap objects, where each overlap contains anrllmfield withxs(x values) andys(y values).comm: The MPI communicator.filename::String: The name of the file where the Rllm data will be saved. Defaults to"rllm.dat".
Hamster.fs — Method
Define rotation coefficients.Hamster.get_base_orb — Method
baseorb logicThe baseorb of px, py, pz should be the same since since one can transform one into the other by rotation.
Hamster.Angular — Type
AngularAngular parts of real atomic orbitals.
Hamster.OrbitalFunction — Type
(orb::OrbitalFunction)(r⃗)Evaluate the orbital orb at the point r⃗, which can be one- or two-dimensional or a tuple including the norm.
Hamster.Overlap — Type
Overlap(Ψ₁, r⃗₁, Ψ₂, r⃗₂)Struct to calculate the overlap integral between two wavefunctions with centers r⃗₁ and r⃗₂.
Hamster.Radial — Type
RadialRadial parts for atomic s orbitals with n=1,2,3,4,5,6.
Hamster.get_spherical — Method
get_spherical(l, m)Returns the spherical harmonic function for a given orbital angular momentum quantum number l and magnetic quantum number m.
Arguments
l::Int: The orbital angular momentum quantum number (l = 0fors,l = 1forp,l = 2ford, etc.).m::Int: The magnetic quantum number, which ranges from-ltol.
Returns
- The corresponding spherical harmonic function as a vector, based on the values of
landm.
Hamster.str_to_orb — Method
str_to_orb(str::String)Convert an orbital name given as a string to its corresponding orbital object.
Arguments
str::String: The name of the orbital as a string. Valid strings include"s","px","py","pz","dz2","dxy","dxz","dyz","dx2_y2","sp3","sp3dr2","pxdx2","pydy2", and"pzdz2".
Returns
Orbital: The corresponding orbital object based on the input string.
Structure
Hamster.PointGrid — Type
PointGrid(rs_ion, Ts, conf::TBConfig) -> PointGridConstructs a PointGrid for managing atomic positions within a 3D simulation cell.
The function takes atomic positions rs_ion, lattice translation vectors Ts, and a TBConfig configuration object as input, and returns a PointGrid object that organizes these atomic positions into a grid of cubic cells.
Arguments:
rs_ion: A collection (e.g., array) of atomic positions in real space.Ts: A collection of lattice translation vectors, typically used for defining the periodic boundaries of the simulation cell.conf::Config: A configuration object containing parameters necessary for setting up thePointGrid, such as the grid size.
Returns:
PointGrid: APointGridobject that partitions the real-space simulation cell into a grid and maps atomic positions to these grid cells.
Hamster.PointGrid — Type
PointGridA data structure for organizing and managing points in a 3D simulation cell by dividing the space into equally-sized cubic boxes.
The PointGrid structure stores grid points for atom positions, allowing for efficient spatial queries and neighbor searches.
Fields:
grid_size::Float64: The size of each cubic grid cell in real space.dict0::Dict{SVector{3, Int64}, Vector{Int64}}: A dictionary that maps grid cell indices to a vector of point indices (e.g., atoms) within that cell.dictR::Dict{SVector{3, Int64}, Vector{Tuple{Int64, Int64}}}: A dictionary that maps grid cell indices to a vector of tuples. Each tuple contains an atom index and a corresponding replica index, facilitating the handling of periodic boundary conditions.num_points::Int64: The total number of points (e.g., atoms) managed by the grid.
Hamster.get_grid_dict — Method
get_grid_dict(rs, Ts, grid_size; δrs=zeros(3, size(rs, 2)))Constructs a point grid for ion positions rs, considering all translation vectors Ts.
Arguments
rs::AbstractMatrix: A 3×N matrix where each column represents the position of an ion in 3D space.Ts::AbstractMatrix: A 3×M matrix where each column represents a translation vector.grid_size::Real: The size of the grid cells used to map the ion positions and their translations.
Returns
grid_dict::Dict{SVector{3, Int64}, Vector{Tuple{Int64, Int64}}}: A dictionary where the keys are grid points (represented as static 3D integer vectorsSVector{3, Int64}), and the values are vectors of tuples(iion, R), whereiionis the index of the ion andRis the index of the translation vector.
Hamster.get_grid_dict — Method
get_grid_dict(rs, grid_size)Constructs a spatial grid based on the ion positions rs, mapping each position to a grid point determined by grid_size.
Arguments
rs::AbstractMatrix: A 3×N matrix where each column represents the position of an ion in 3D space.grid_size::Real: The size of the grid cells used to map the ion positions.
Returns
grid_dict::Dict{SVector{3, Int64}, Vector{Int64}}: A dictionary where the keys are grid points (represented as static 3D integer vectorsSVector{3, Int64}), and the values are vectors of ion indices corresponding to the ions located at that grid point.
Hamster.get_grid_point — Method
get_grid_point(r⃗, grid_size) -> SVector{3, Int64}Calculate the grid point corresponding to a given position vector r⃗ based on a specified grid size.
Arguments
r⃗: A 3D position vector, typically represented as anSVector{3, Float64}or similar type, indicating the coordinates in space.grid_size: A scalar value representing the size of each grid cell. This is used to determine which grid point the positionr⃗belongs to.
Returns
- An
SVector{3, Int64}representing the grid point. The grid point is computed by dividing each component ofr⃗bygrid_size, flooring the result to obtain the integer grid coordinates.
Hamster.iterate_nn_grid_points — Method
iterate_nn_grid_points(grid_point, point_grid::PointGrid)Find and return all neighboring grid points of a given grid_point within the specified point grid and gather the associated ion indices and translation vectors.
Arguments
grid_point: A grid point represented as a tuple (or similar structure), indicating the current grid position for which neighboring points are being queried.point_grid::PointGrid: APointGridobject containing information about the point grid, including the ions' positions and the translation vectors.
Returns
all_inds::Vector{Tuple{Int64, Int64}}: A vector of tuples, where each tuple contains:- The index of the ion (
iion) corresponding to a nearby grid point. - The translation vector (
R) for that ion.
- The index of the ion (
Hamster.iterate_nn_grid_points — Method
iterate_nn_grid_points(point_grid::PointGrid)Iterates over nearest-neighbor (NN) grid points in a given PointGrid and collects indices of ion pairs and translation vectors.
Arguments
point_grid::PointGrid: APointGridobject containing the initial grid points and the corresponding indices of ions.
Returns
all_inds::Vector{Tuple{Int64, Int64, Int64}}: A vector of tuples where each tuple consists of:iion1::Int64: Index of the first ion in the current grid point.iion2::Int64: Index of the second ion in the neighboring grid point.R::Int64: Index of the translation vector between the current grid point and its nearest neighbor.
Hamster.nn_grid_points — Method
nn_grid_points(grid_point, grid_dict) -> Vector{SVector{3, Int64}}Returns a vector of grid points that are nearest neighbors to the given grid_point.
This function computes the nearest-neighbor grid points in a 3D grid by considering all adjacent grid cells in the 3x3x3 neighborhood centered around grid_point. It checks for the existence of each neighbor in the provided grid_dict before including it in the result.
Arguments:
grid_point: AnSVector{3, Int64}representing the coordinates of the grid point for which nearest neighbors are sought.grid_dict: A dictionary (Dict{SVector{3, Int64}, ...}) where the keys are grid points in the form ofSVector{3, Int64}. This dictionary is used to determine if a neighbor grid point exists.
Returns:
Vector{SVector{3, Int64}}: A vector containing the nearest-neighbor grid points of the specifiedgrid_pointthat are present in thegrid_dict.
Hamster.push_grid_point! — Method
push_grid_point!(grid_dict, grid_point, point_info)Add or update an entry in the grid dictionary with a specified grid point.
Arguments
grid_dict::Dict: A dictionary where keys are grid points (e.g.,SVector{3, Int64}) and values are lists of associated points or indices.grid_point: The key representing the grid point in the dictionary. Typically a static vector or tuple indicating the grid coordinates.point_info: The value to associate with thegrid_point. Often this is an index, tuple of indices, or other relevant information.
Details
If the grid_point key already exists in grid_dict, the point_info is appended to the existing list of values. If the grid_point does not exist, a new entry is created with point_info as the first element in the list.
Hamster.Ion — Type
IonA mutable structure representing an ion in a crystal lattice.
Fields
type::UInt8: The type or species of the ion, denoted by its proton number.pos::StaticArray{3, Float64}: A 3D static array representing the position of the ion in Cartesian coordinates.dist::StaticArray{3, Float64}: A 3D static array representing any distortion applied to the ion's position.
Hamster.findnext_ion_of_type — Method
findnext_ion_of_type(type, ions::Vector{Ion}) -> Int64Find the index of the next ion in the vector Ions that has the specified type.
Arguments:
type: The type of ion to search for. This could be a string, integer, or any other type that represents an ion type.Ions: A vector ofIonobjects, where eachIonhas atypefield that specifies its ion type.
Returns:
- The index
iionof the first ion inionswhosetypematches the inputtype. - If no ion with the specified
typeis found, the function returns0.
Hamster.get_ion_positions — Method
get_ion_positions(ions::Vector{Ion}) :: Vector{SVector{3, Float64}}Retrieve the positions of all ions in a given vector of Ion objects.
Arguments
ions::Vector{Ion}: A vector ofIonobjects, where eachIoncontains information about its type, position, and distortion.
Returns
Vector{SVector{3, Float64}}: A vector ofSVector{3, Float64}where each element represents the 3D Cartesian coordinates of an ion.
Hamster.get_ion_types — Method
get_ion_types(ions::Vector{Ion}; uniq=false, sorted=false)Return an array containing the types of all ions in the vector ions.
Arguments
ions::Vector{Ion}: A vector ofIoninstances, each containing information about an ion's type, position, and distortion.uniq::Bool=false: Iftrue, the returned array contains only unique ion types.sorted::Bool=false: Iftrue, the returned array is sorted in alphabetical order.
Returns
Vector{String}: An array of ion types. The array will contain all ion types present in the input vectorions. Ifuniqis set totrue, only unique types will be included. Ifsortedis set totrue, the types will be sorted alphabetically.
Hamster.get_ions — Function
get_ions(positions, types, distortions=zeros(3, size(positions, 2)))Create a vector of Ion instances from given positions, types, and distortions.
Arguments
positions::AbstractMatrix{T}: A matrix where each column represents the 3D position of an ion in Cartesian coordinates.types::AbstractVector{String}: A vector of strings representing the type or species of each ion, corresponding to the columns ofpositions.distortions::AbstractMatrix{T}: A matrix where each column represents the 3D distortion vector applied to the corresponding ion's position. Defaults to a matrix of zeros.
Returns
Vector{Ion}: A vector ofIoninstances, each containing the type, position, and distortion of an ion.
Hamster.findR0 — Method
findR0(Rs::Matrix{<:Number})Finds the index of the translation vector [0, 0, 0] in the matrix Rs.
Arguments
Rs::Matrix{<:Number}: A 3xN matrix where each column represents a translation vector.
Returns
R::Int: The index of the column inRsthat contains the vector[0, 0, 0]. If the vector[0, 0, 0]is not found, returns0.
Hamster.get_Rmax — Function
get_Rmax(lattice, conf=get_empty_config(); rcut=get_rcut(conf), Rmax=get_Rmax(conf), upperR=10)Determines the maximum radius Rmax for the given lattice and configuration parameters based on the cutoff radius rcut.
Arguments
lattice: The lattice parameters used to convert fractional to Cartesian coordinates.conf: (Optional) Configuration object. Defaults toget_empty_config().rcut: (Optional) The cutoff radius used to determine the maximum radius. Defaults toget_rcut(conf).Rmax: (Optional) Initial guess for the maximum radius. Defaults toget_Rmax(conf).upperR: (Optional) Upper limit for the search radius. Defaults to 10.
Returns
Rmax::Int: The maximum radius such that the spherical region of radiusRmaxcontains all points within the cutoff radiusrcut.
Hamster.get_translation_vectors — Function
get_translation_vectors(rs_ion, lattice, conf=get_empty_config(); Rmax=get_Rmax(lattice, conf), rcut=get_rcut(conf))Generate a set of translation vectors based on ion positions rs_ion, the lattice vectors lattice, and optional configuration settings. The function returns the translation vectors that satisfy the maximum interatomic distance rcut, which is determined from the configuration or can be manually specified.
Arguments
rs_ion::AbstractMatrix: Matrix of ion positions in fractional coordinates. Each column represents the position of an ion.lattice::AbstractMatrix: Lattice vectors of the system, where each column represents a lattice vector.conf::Config: (Optional) Configuration object containing settings likeRmaxandrcut. Defaults to an empty configuration.Rmax::Int64: (Optional) Maximum entry magnitude for the initial set of translation vectors. Defaults to the value from the configuration.rcut::Float64: (Optional) Maximum interatomic distance. If set to 0, all initial translation vectors will be returned. Defaults to the value from the configuration.
Returns
AbstractMatrix: A matrix containing the translation vectors as columns. The vectors are filtered based on thercutvalue to include only those within the specified interatomic distance.
Hamster.get_translation_vectors — Method
get_translation_vectors(M::Int64)Generate a set of translation vectors within a cubic grid defined by the maximum entry magnitude M.
Arguments
M::Int64: The maximum magnitude of the entries in the translation vectors. The resulting grid will include all integer vectors where each component is in the range-MtoM.
Returns
Rs::Matrix{Float64}: A 3xN matrix whereNis the total number of translation vectors. Each column ofRsrepresents a translation vector with components within the specified magnitude range.
Hamster.get_nearest_neighbors — Method
get_nearest_neighbors(r0, rs, Ts, point_grid::PointGrid; kNN=1, sorted=false)Find the nearest neighbors (NN) of a given point r0 within a set of points rs and translation vectors Ts.
Arguments
r0::AbstractVector{T}: The reference point in 3D space for which the nearest neighbors are to be found.rs::AbstractMatrix{T}: A 3xN matrix where each column represents a 3D point in space. These are the potential neighbors.Ts::AbstractMatrix{T}: A 3xM matrix where each column is a 3D translation vector. These vectors are applied to the points inrsto account for periodic boundary conditions.point_grid::PointGrid: APointGridstructure used for efficient neighbor searching, containing a grid size and a dictionary of grid points.kNN::Int: The number of nearest neighbors to find. Defaults to 1.
Returns
r_NN::Matrix{Float64}: A 3xkNN matrix where each column represents the 3D coordinates of one of thekNNnearest neighbors tor0.
Description
This function computes the nearest neighbors of a point r0 by:
- Locating the grid point corresponding to
r0in thepoint_grid. - Iterating over the neighboring grid points to compute distances to all potential neighbor points in
rsshifted by translation vectors inTs. - Sorting these distances to identify the
kNNclosest neighbors. - Returning the positions of these nearest neighbors in a matrix.
Hamster.get_nn_thresholds — Function
get_nn_thresholds(ions, Ts, point_grid, conf=get_empty_config(); sepNN=get_sepNN(conf))Calculate nearest-neighbor distance thresholds for pairs of ions based on their positions and types, returning a dictionary of IonLabel keys and corresponding minimum distances.
Arguments
ions: A list of ion objects. Each ion contains its position and type.Ts: A transformation matrix used for periodic boundary conditions.point_grid: A grid of points to iterate over for calculating neighbor distances.conf: A configuration object (optional). Default isget_empty_config().sepNN: A Boolean flag (optional). Iftrue, separate NN thresholds are calculated for each ion pair. Iffalse, all ion pairs are treated uniformly. Default isget_sepNN(conf).
Keyword Arguments
sepNN: Whether to compute separate NN distances for different ion pairs. Default isget_sepNN(conf).
Returns
NN_dict::Dict{IonLabel, Float64}: A dictionary where each key is anIonLabelrepresenting a pair of ion types, and the value is the minimum nearest-neighbor distance for that pair.
Hamster.get_sk_transform_matrix — Method
get_sk_transform_matrix(r⃗₁, r⃗₂, axis, tmethod)Returns a transformation matrix that aligns the z-axis along the vector connecting r⃗₁ and r⃗₂. The method of transformation depends on tmethod.
Arguments
r⃗₁::AbstractVector: The first position vector.r⃗₂::AbstractVector: The second position vector.axis::AbstractVector: A vector used to define the x-axis in case of Gram-Schmidt transformation.tmethod::String: The transformation method.
Returns
Ê::AbstractMatrix: The 3x3 transformation matrix that aligns the z-axis with the vector betweenr⃗₁andr⃗₂.
Hamster.get_transformed_system — Method
get_transformed_system(r⃗₁, r⃗₂, ω; ϵ=1e-5)
get_transformed_system(r⃗₁, r⃗₂)Construct a new orthonormal coordinate system based on two vectors r⃗₁ and r⃗₂, with the z-axis oriented along the vector connecting r⃗₁ and r⃗₂. Optionally, a third vector ω can be provided to influence the initial guess for the x-axis.
Arguments
r⃗₁::Vector: A 3D vector representing the first position.r⃗₂::Vector: A 3D vector representing the second position.ω::Vector: (Optional) A 3D vector used as the initial guess for the x-axis orientation. Ifωis omitted, the function assumes a default method for constructing the x-axis.ϵ::Float64=1e-5: (Optional) A small tolerance value to handle near-zero differences and near-parallel vectors.
Returns
- A 3x3 matrix
Êwhere the rows correspond to the new x-axis, y-axis, and z-axis of the coordinate system.
Details
- Z-axis (ez): Always aligned with the normalized vector
r⃗₂ - r⃗₁. If this vector is zero or near-zero (within toleranceϵ), the z-axis defaults to[0, 0, 1]. - X-axis (ex): If
ωis provided, the x-axis is constructed from the projection ofωorthogonal to the z-axis and is normalized. Ifωis omitted, an alternative method will define the x-axis. - Y-axis (ey): Always computed as the cross-product of the z-axis and x-axis, ensuring orthogonality and completeness of the coordinate system.
- Fallback behavior: If
ωis nearly parallel to the z-axis within toleranceϵ, the function reverts to the simpler versionget_transformed_system(r⃗₁, r⃗₂)to handle the ambiguity in the x-axis.
Hamster.rotation_matrix_around_axis — Method
rotation_matrix_around_axis(u⃗::AbstractVector{T}, θ::T) where TConstructs a 3x3 rotation matrix that rotates by an angle θ around an arbitrary axis u⃗, using Rodrigues' rotation formula.
Arguments
u⃗::AbstractVector{T}: A 3D unit vector (axis of rotation) whereTis a numeric type.θ::T: The angle of rotation (in radians) around the axisu⃗.
Returns
- A 3x3 static matrix representing the rotation around the axis
u⃗by angleθ.
Hamster.Structure — Type
Structure(conf=get_empty_config(); poscar_path=get_poscar(conf), rcut=get_rcut(conf), grid_size=get_grid_size(conf))Create a Structure instance from a POSCAR file.
Arguments
conf: AConfiginstance that contains various parameters.poscar_path: The file path to the POSCAR file.rcut: The cutoff radius for interactions to be taken into account.grid_size: The size of the grid used in thePointGridfor efficient neighbor searching.
Returns
Structure: AStructureinstance.
Hamster.Structure — Type
StructureA data structure representing a crystal structure, including its lattice vectors, atomic positions, and a point grid for efficient neighbor searching.
Fields
lattice::Matrix{Float64}: A 3x3 matrix representing the lattice vectors of the crystal. Each column corresponds to a lattice vector.Rs::Matrix{Float64}: A matrix where each column represents the position of a lattice translation vector in fractional coordinates.ions::Vector{Ion}: A vector containing the ions in the structure. EachIonincludes information like the type of ion, its position, and possibly its distortion from the equilibrium.point_grid::PointGrid: A data structure used for efficiently finding neighboring ions based on their positions.
Hamster.Structure — Method
Structure(Rs, rs_ion, δrs_ion, ion_types, lattice, conf=get_empty_config(); rcut=get_rcut(conf), grid_size=get_grid_size(conf))
Structure(Rs, rs_ion, ion_types, lattice, conf=get_empty_config(); rcut=get_rcut(conf), grid_size=get_grid_size(conf))Create a Structure instance from atomic information.
Arguments
Rs: A 3xNR matrix representing the set of lattice translation vectors.rs_ion: A 3xNion matrix representing the coordinates of the ions in the unit cell.δrs_ion: (Optional) A 3xNion matrix representing atomic displacements fromrs_ion. Defaults to a zeros.ion_types: A vector representing the types of ions in the unit cell.lattice: A 3x3 matrix representing the lattice vectors of the crystal.conf: (Optional) AConfiginstance.rcut: The cutoff radius for interactions to be taken into account.grid_size: The size of the grid used in thePointGridfor efficient neighbor searching.
Returns
Structure: AStructureinstance.
Hamster.get_config_index_sample — Function
get_config_index_sample(conf=get_empty_config(); Nconf=get_Nconf(conf), Nconf_min=get_Nconf_min(conf), Nconf_max=get_Nconf_max(conf), val_ratio=get_val_ratio(conf))Randomly selects training and validation configuration indices from a given range of configurations.
Arguments
conf: (Optional) A configuration object from which all other parameters may be derived. Defaults to an empty configuration.Nconf: (Optional) The number of configurations to sample for training. Derived fromconfif not specified.Nconf_min: (Optional) The minimum configuration index. Derived fromconfif not specified.Nconf_max: (Optional) The maximum configuration index. Derived fromconfif not specified.validate: (Optional) Boolean flag indicating whether validation should be performed. Derived fromconfif not specified.val_ratio: (Optional) Ratio of validation configurations to training configurations. Used only iftrain_mode == val_mode.train_mode: (Optional) Mode identifier for training configurations. Derived fromconf.val_mode: (Optional) Mode identifier for validation configurations. Derived fromconf.
Returns
train_config_inds: A vector of indices for training configurations.val_config_inds: A vector of indices for validation configurations.
Hamster.get_config_inds_for_systems — Function
get_config_inds_for_systems(systems, comm; rank=0) -> (train_inds, val_inds)Distribute and synchronize configuration indices for multiple systems across MPI processes, returning training and validation index sets for each system.
Arguments
systems::Vector{String}: List of system names (e.g. materials or datasets).comm: MPI communicator used to synchronize configuration indices between ranks.rank::Int(keyword, default =0): Current MPI process rank.
Returns
(train_config_inds, val_config_inds): Two dictionaries mapping each system name (String) to a vector of integer indices (Vector{Int64}) representing the selected configurations for training and validation, respectively.
Hamster.get_number_of_bands_per_structure — Method
get_number_of_bands_per_structure(bases, indices; soc=false) -> Dict{String, Int}Compute the number of electronic bands per system, given a list of Basis and a mapping from systems to configuration indices.
Arguments
bases: A vector of bases.indices: ADict{String, Vector{Int}}containing atomic configuration indices.soc(keyword, default =false): Iftrue, doubles the band count per to account for SOC.
Returns
Dict{String, Int}: A dictionary mapping each system name to its number of bands.
Hamster.get_structures — Function
get_structures(conf=get_empty_config(); index_file="config_inds.dat", xdatcar=get_xdatcar(conf), sc_poscar=get_sc_poscar(conf))Generates a list of Structure objects based on the configurations from an XDATCAR file (or an h5 file) and the initial POSCAR structure.
Arguments
conf: A configuration object. By default,get_empty_config().index_file: A string specifying the filename containing the configuration indices. If this file exists, the configuration indices are read from it. If not, they are sampled usingget_config_index_sample().xdatcar: The path to the XDATCAR file, containing configuration data for the system.sc_poscar: The path to the POSCAR file, representing the initial supercell structure.
Returns
strcs: A vector ofStructureobjects. Each structure represents the ion positions and their displacements relative to the initial configuration.
Hamster.get_systems — Method
get_systems(conf) -> Vector{String}Return the list of system names available for a given configuration conf.
Arguments
conf: A configuration object.
Returns
Vector{String}: A list of system names (HDF5 group names or a single system).
Hamster.read_structure_file — Function
read_structure_file(system, conf=get_empty_config(); mode="md", sc_poscar=get_sc_poscar(conf), xdatcar=get_xdatcar(conf))
-> (rs_atom, atom_types, lattice, configs)Read atomic structures and lattice information for a given system from POSCAR/XDATCAR or HDF5 files, depending on the selected mode.
Arguments
system::String: Name of the system (material) to load, used when reading from an HDF5 file.conf: Configuration object containing simulation paths and metadata. Defaults toget_empty_config().mode::String(keyword, default ="md"): Determines data source and type."md"→ single dataset."universal"→ read from system group in an HDF5 file.
sc_poscar: Path to the POSCAR or supercell POSCAR file.xdatcar: Path to the XDATCAR or.h5file containing configurations.
Returns
A tuple containing:
rs_atom::Matrix{Float64}— Cartesian positions of atoms in the reference structure.atom_types::Vector{String}— Atomic species labels.lattice::Matrix{Float64}— Lattice vectors (3×3 matrix).configs::Array{Float64,3}— Atomic positions for all configurations (shape:3 × N_atoms × N_configs).
Hamster.split_indices_into_chunks — Method
split_indices_into_chunks(indices, nchunks; rank=0)Splits a collection of indices into nchunks approximately equal-sized chunks and returns the chunk corresponding to the specified rank.
Arguments
indices::AbstractVector: The collection of indices to be split.nchunks::Int: The number of chunks to divide the indices into.rank::Int=0: The rank (0-based) specifying which chunk to return. Defaults to0.
Returns
AbstractVector: The chunk of indices corresponding to the specifiedrank. If therankexceeds the number of chunks, an empty array of typeInt64[]is returned.
Hamster.calc_angle — Method
calc_angle(v1, v2; ϵ=1e-5)Calculate the angle between two vectors v1 and v2 in radians.
Arguments:
v1: First vector (can be any dimensionality as long as it matchesv2).v2: Second vector (same dimensionality asv1).ϵ: Small tolerance value to ensure that the norm of the vectors is sufficiently large to avoid division by zero (default:1e-5).
Returns:
- The angle in radians between
v1andv2, calculated using the dot product. If either vector's norm is less thanϵ, the function returns0..
Hamster.get_rotated_angles — Method
get_rotated_angles(Û, r⃗)Calculate the spherical angles (θ, φ) for a vector r⃗ after it is rotated by the matrix Û.
Arguments
Û::AbstractMatrix{T}: A 3x3 rotation matrix that transforms the vectorr⃗.r⃗::AbstractVector{T}: A 3D vector to be rotated, whereTis a numeric type.
Returns
θ::T: The polar (zenith) angle, measured from the z-axis, in radians.φ::T: The azimuthal angle, measured from the x-axis in the xy-plane, in radians.
Hamster.normdiff — Method
normdiff(v⃗::AbstractVector, w⃗::AbstractVector)
normdiff(v⃗::AbstractVector, w⃗::AbstractVector, t⃗::AbstractVector)
normdiff(v⃗::AbstractVector, w⃗::AbstractVector, δv⃗::AbstractVector, δw⃗::AbstractVector, t⃗::AbstractVector)Compute the Euclidean norm (L2 distance) between two vectors v⃗ and w⃗, optionally with displacement vectors δv⃗ and δw⃗ and lattice translation vector t⃗.
Arguments
v⃗::AbstractVector: The first vector.w⃗::AbstractVector: The second vector.δv⃗::AbstractVector: The first displacement vector.δw⃗::AbstractVector: The second displacement vector.t⃗::AbstractVector: The lattice translation vector.
Returns
Float64: The Euclidean norm of the difference between vectorsvandw.
Hamster.proj — Method
proj(u⃗, v⃗)Calculate the projection of the vector v⃗ onto the vector u⃗.
Arguments
u⃗::AbstractVector: The vector onto which the projection is calculated.v⃗::AbstractVector: The vector being projected ontou⃗.
Returns
AbstractVector: The projection ofv⃗ontou⃗.
Hamster.transform_basis — Method
transform_basis(r⃗::AbstractVector, Ê::AbstractMatrix) -> AbstractVectorTransforms a vector to a new basis using a given transformation matrix.
This function takes a vector r⃗ and transforms it into a new basis by applying the transformation matrix Ê. The transformation is performed by multiplying the matrix Ê with the vector r⃗, yielding the transformed vector.
Arguments:
r⃗::AbstractVector: The vector to be transformed. This represents coordinates or a state in the original basis.Ê::AbstractMatrix: The transformation matrix that defines the new basis. This matrix should have dimensions compatible with the vectorr⃗.
Returns:
AbstractVector: The transformed vector in the new basis, obtained by multiplyingÊwithr⃗.
Hamster.transform_to_spherical — Method
transform_to_spherical(r⃗::AbstractArray{Float64, 2}; origin=[0, 0, 0]) -> AbstractMatrix{Float64}Converts a set of Cartesian coordinates to spherical coordinates relative to a specified origin.
This function takes a 3xN matrix r⃗, where each column represents a point in Cartesian coordinates (x, y, z), and transforms these points into spherical coordinates (r, θ, φ). The transformation is performed relative to a specified origin.
Arguments:
r⃗::AbstractArray{Float64, 2}: A 3xN matrix where each column represents Cartesian coordinates[x, y, z]of a point.origin::AbstractVector{Float64}: A 3-element vector specifying the origin relative to which the spherical coordinates are computed. Default is[0, 0, 0].
Returns:
AbstractMatrix{Float64}: An N×3 matrix where each row contains the spherical coordinates(r, θ, φ)for the corresponding point in the input.
Hamster.transform_to_spherical — Method
transform_to_spherical(r⃗::AbstractArray{Float64, 1}) -> Tuple{Float64, Float64, Float64}Converts Cartesian coordinates to spherical coordinates.
This function takes a 3D vector r⃗ in Cartesian coordinates (x, y, z) and transforms it into spherical coordinates (r, θ, φ). The spherical coordinates are defined as follows:
r: The radial distance from the origin.θ: The polar angle, measured from the positive z-axis.φ: The azimuthal angle, measured from the positive x-axis in the xy-plane.
Arguments:
r⃗::AbstractArray{Float64, 1}: A 3-element vector representing the Cartesian coordinates[x, y, z].
Returns:
Tuple{Float64, Float64, Float64}: A tuple containing the spherical coordinates(r, θ, φ).
TB
Hamster.copy_params! — Method
copy_params!(receiving_ham::H1, sending_ham::H2) where {H1,H2<:EffectiveHamiltonian}Copy parameters from one EffectiveHamiltonian (sending_ham) to another (receiving_ham).
Arguments
receiving_ham: The Hamiltonian object that will receive the parameters.sending_ham: The Hamiltonian object providing the parameters to be copied.
Hamster.get_hamiltonian — Method
get_hamiltonian(ham::EffectiveHamiltonian, index, ks)Construct the Hamiltonian matrix for given k-points ks from the real-space Hamiltonian and lattice vectors.
Arguments
ham::EffectiveHamiltonian: The effective Hamiltonian object.index::Int: The index of the structure for which the Hamiltonian is to be calculated.ks: The k-points for which the Hamiltonian matrix is to be calculated.comm(optional): The MPI communicator.
Returns
Hk: The Hamiltonian matrix in reciprocal space corresponding to the given k-points.
Hamster.get_hr — Method
get_hr(ham::EffectiveHamiltonian, index)Retrieve the real-space Hamiltonian (Hr) by combining contributions from individual models within the EffectiveHamiltonian.
Arguments
ham::EffectiveHamiltonian: The effective Hamiltonian object.index::Int: The index of the structure for which the Hamiltonian is to be calculated.
Returns
Hr: The combined real-space Hamiltonian matrix, obtained by summing the Hamiltonians of all the models in theham.modelstuple.
Hamster.get_sparse_iterator — Function
get_sparse_iterator(strc, basis, conf=get_empty_config(), rcut=get_rcut(conf))Constructs an iterator that generates sparse matrix indices for interactions within a specified cutoff radius.
Arguments
strc: A structure object containing information about ions, positions, lattice, and grid points.basis: A basis object, containing the orbitals associated with each ion.conf: Configuration object, which contains relevant simulation parameters.rcut: A cutoff radius, that defines the maximum distance for interactions to be included.
Returns
indices: A vector of vectors, where each sub-vector corresponds to a specific grid point (denoted byR) and contains tuples(i, j)representing the sparse matrix indices for interactions within the cutoff radius.
Hamster.update! — Method
update!(ham::EffectiveHamiltonian, opt, dL_dHr)Update the parameters of each model within the EffectiveHamiltonian object using a provided update rule.
Arguments
ham::EffectiveHamiltonian: The effective Hamiltonian object containing multiple models.opt: An optimizer object specifying the update rule (e.g., ADAM).model_grad: The gradient of the loss w.r.t. the model parameters.
Returns
- This function modifies the
hamobject in place, updating the parameters of each model it contains.
Hamster.write_params — Function
write_params(eff_ham::EffectiveHamiltonian, conf)Writes the parameters of all models contained within an EffectiveHamiltonian.
Arguments
eff_ham::EffectiveHamiltonian: An EffectiveHamiltonian model.conf::Config: A configuration object.
Behavior
- Iterates through all models within
eff_hamand callswrite_params(model)for each.
Hamster.apply_spin_basis — Method
apply_spin_basis(H::AbstractMatrix; alternating_order=false)Extends a given matrix H to a spin basis (up/down) representation by applying the tensor product with the identity matrix. The order of the tensor product application is controlled by the alternating_order flag which affects the order of spin states in the basis.
Arguments:
H::AbstractMatrix: The input matrix to be extended to the spin basis. It should be a square matrix or generally a 2D array.alternating_order::Bool=false: A boolean flag that determines the order of applying the spin basis. Iftrue, the order is, e.g., up,down,up,down. Iffalse, the order is, e.g., up,up,down,down.
Returns:
- A matrix in the spin basis in the specified order.
Hamster.diagonalize — Method
diagonalize(Hk::AbstractMatrix; Neig=size(Hk, 1), target=0, method="shift-invert")Fully diagonalizes a Hermitian Hamiltonian matrix Hk and returns the eigenvalues and eigenvectors.
Arguments:
Hk::AbstractMatrix: A Hermitian matrix (Hamiltonian) to be diagonalized. The matrix should be square and typically complex-valued.Neig::Int=size(Hk, 1): The number of eigenvalues and corresponding eigenvectors to compute. Not used.target::Real=0: The target eigenvalue around which to focus the computation. Not used.method::String: The method to be used for calculating eigenvalues of a sparse matrix.
Returns:
real_values::Vector{Float64}: A vector containing the real parts of the eigenvalues ofHk. The eigenvalues are computed using the Hermitian matrix, so they are guaranteed to be real.eigenvectors::Matrix{ComplexF64}: A matrix where each column is an eigenvector corresponding to an eigenvalue ofHk. The eigenvectors are computed in the standard basis and are complex-valued.
Hamster.diagonalize — Method
diagonalize(Hk::SparseMatrixCSC; Neig=6, target=0, method="shift-invert")Diagonalizes a sparse Hermitian matrix Hk to find a specified number of eigenvalues and eigenvectors, optionally focusing on eigenvalues near a given target.
Arguments:
Hk::SparseMatrixCSC: A sparse Hermitian matrix in compressed sparse column format to be diagonalized. The matrix should be square and Hermitian.Neig::Int=6: The number of eigenvalues and corresponding eigenvectors to compute. Defaults to6, but can be adjusted based on the required precision or size of the spectrum.target::Real=0: The target eigenvalue around which to focus the computation. This is used to prioritize finding eigenvalues closest to this value. Defaults to0.method::String: The method to be used for calculating eigenvalues of a sparse matrix.
Returns:
eigenvalues::Vector{Float64}: A vector of the real parts of the computed eigenvalues, focusing on those closest to the target. The number of eigenvalues returned is equal toNeig.eigenvectors::Matrix{ComplexF64}: A matrix where each column is an eigenvector corresponding to one of the computed eigenvalues.
Hamster.diagonalize — Method
diagonalize(Hk::Vector{<:AbstractMatrix}; Neig=size(Hk[1], 1), target=0, method="shift-invert")Diagonalizes a vector of Hamiltonian matrices Hk and returns the specified number of eigenvalues and eigenvectors for each matrix.
Arguments:
Hk::Vector{<:AbstractMatrix}: A vector of Hamiltonian matrices to be diagonalized. Each matrix typically corresponds to a different momentumkin a band structure calculation.Neig::Int=size(Hk[1], 1): The number of eigenvalues and corresponding eigenvectors to compute for each Hamiltonian matrix. Defaults to the full diagonalization (size(Hk[1], 1)).target::Real=0: The target eigenvalue when computing eigenvalues of a sparse matrix.method::String: The method to be used for calculating eigenvalues of a sparse matrix.
Returns:
Es::Matrix{Float64}: A matrix where each columnEs[:, k]contains theNeigeigenvalues of thek-th Hamiltonian matrix inHk.vs::Array{ComplexF64, 3}: A 3D array where eachvs[:, :, k]contains theNeigeigenvectors corresponding to thek-th Hamiltonian matrix inHk. The dimensions ofvsare(Nε, Neig, Nk), whereNεis the size of each Hamiltonian matrix,Neigis the number of eigenvectors, andNkis the number of Hamiltonian matrices.
Hamster.exp_2πi — Method
exp_2πi(k⃗, R⃗)Calculate the phase factor exp(2πik⃗⋅R⃗).
Hamster.get_hamiltonian — Function
get_hamiltonian(Hr::Vector{<:AbstractMatrix}, Rs, ks, mode=Dense(), weights=ones(size(Rs, 2)))Constructs a vector of Hamiltonian matrices by combining a vector of matrices Hr with phase factors determined by Rs and ks.
Arguments:
Hr::Vector{<:AbstractMatrix}: A vector of matrices where each matrix represents a component of the Hamiltonian. These matrices must be compatible in size for the operations performed.Rs: A matrix or array containing positional information used to calculate phase factors.ks: A matrix of momentum values used in conjunction withRsto compute phase factors.mode::Dense(): Indicates whether to construct a sparse or dense Hamiltonian. Defaults toDense.weights::Vector=ones(size(Rs, 2)): A vector of weights used in the summation of phase factors. The length of this vector should match the number of columns inRs. These are the degeneracies for the Wannier90 Hamiltonians.
Returns:
- A vector of Hamiltonian matrices
Hk, where each matrix is constructed by combiningHrwith phase factors and optionally transformed into a spin basis.
Hamster.get_sparsity — Method
get_sparsity(H::AbstractArray; sp_tol=1e-10)Calculates the sparsity of a matrix or array by determining the fraction of elements that are considered effectively zero based on a specified numerical tolerance.
Arguments:
H::AbstractArray: The input matrix or array for which sparsity is to be calculated. It can be a dense or sparse matrix, or any array-like structure.sp_tol::Real=1e-10: The numerical tolerance used to determine whether an element is considered zero. Elements with both real and imaginary parts less thansp_tolin magnitude are considered zero.
Returns:
sparsity::Float64: The fraction of elements inHthat are considered zero according to the specified tolerance. This value lies between0.0(no zero elements) and1.0(all elements are effectively zero).
Hamster.get_sparsity — Method
get_sparsity(H::Vector{AbstractArray}; sp_tol=1e-10)Calculates the sparsity of a vector of arrays by determining the fraction of elements across all arrays that are considered effectively zero based on a specified numerical tolerance.
Arguments:
H::Vector{AbstractArray}: A vector containing arrays (e.g., matrices) for which sparsity is to be calculated. Each element ofHshould be an array of the same size.sp_tol::Real=1e-10: The numerical tolerance used to determine whether an element is considered zero. Elements with both real and imaginary parts less thansp_tolin magnitude are considered zero.
Returns:
sparsity::Float64: The fraction of elements across all arrays inHthat are considered zero according to the specified tolerance. This value lies between0.0(no zero elements) and1.0(all elements are effectively zero).
Hamster.gradient_apply_spin_basis — Method
gradient_apply_spin_basis(dHr::AbstractMatrix; alternating_order=false)Calculate the gradient of the spin basis applied to a given matrix dHr. The output matrix is of size (Nε/2, Nε/2).
This function reshapes the input matrix dHr, which is expected to represent a gradient in a spin system, into a form suitable for applying the spin basis transformation. The transformation is performed using the Kronecker product, and the output is computed depending on the specified order of application.
Arguments
dHr::AbstractMatrix: An abstract matrix containing the gradient data to be transformed. It should have a shape that is compatible with the spin basis operations.alternating_order::Bool: A flag that determines the order of the spin basis application. Iffalse, the function applies the transformation askron(H, I_spin). Iftrue, it applies the transformation askron(I_spin, H).
Hamster.reshape_and_sparsify_eigenvectors — Method
reshape_and_sparsify_eigenvectors(vs, mode::SparsityMode; sp_tol=1e-10) -> MatrixReshapes and optionally sparsifies a 3D array of eigenvectors vs into a 2D matrix of vectors, depending on the specified SparsityMode.
The input vs is assumed to have dimensions (n, m, k), where:
nrepresents the size of each eigenvector.mandkrepresent the number of eigenvector groups along two axes.
Arguments
vs::Array: A 3D array of eigenvectors, wherevs[:, m, k]corresponds to the eigenvector at position(m, k).mode::SparsityMode: Specifies the sparsity mode. Must be either:Dense: Produces a dense matrix where each element is a dense vector.Sparse: Produces a sparse matrix where each element is a sparse vector.
sp_tol::Float64=1e-10: (Optional) The tolerance below which elements of the eigenvectors are dropped whenSparsemode is selected. Defaults to1e-10.
Returns
Matrix{Vector{ComplexF64}}ifmodeisDense: A 2D matrix of dense vectors corresponding to eigenvectors invs.Matrix{SparseVector{ComplexF64, Int64}}ifmodeisSparse: A 2D matrix of sparse vectors, where elements smaller thansp_tolare removed.
SparseArrays.droptol! — Function
droptol!(H::Vector{AbstractSparseMatrix}, tol=1e-10)Applies a tolerance to drop small elements from a vector of sparse matrices, modifying the matrices in place.
Arguments:
H::Vector{AbstractSparseMatrix}: A vector of sparse matrices where small elements will be dropped. The matrices are modified in place.tol::Real=1e-8: The numerical tolerance used to determine which elements are considered too small and should be dropped. Elements with absolute values less thantolare removed from the sparse matrices.
Hamster.chain_rule — Method
chain_rule(dL_dE, dE_dHr, mode)Applies the chain rule to compute the gradient of the loss with respect to the real-space Hamiltonian matrix elements by combining partial derivatives dL_dE and dE_dHr.
Arguments
dL_dE: An array containing the partial derivatives of the loss with respect to the eigenvalues, with shape(m, k), wheremis the eigenvalue index andkis the k-point index.dE_dHr: A 3D array of Matrices containing the partial derivatives of the eigenvalues with respect to the Hamiltonian in real-space coordinates, with shape(R, m, k), whereRis the lattice vector index.mode: Specifies whether the Hamiltonian is sparse or dense, determining the data structure of the result.
Returns
dL_dHr: A real-space Hamiltonian gradient array, where each element contains the accumulated gradient for a specific lattice vector inR. Its shape is determined by the Hamiltonian structure andmode.
Hamster.get_eigenvalue_gradient — Function
get_eigenvalue_gradient(vs, Rs, ks, sp_mode, sp_iterator; nthreads_bands, nthreads_kpoints)Compute the gradient dE_dHr of each energy eigenvalue at each k-point w.r.t. the real-space Hamiltonian matrix elements.
Arguments
-vs: Matrix that contains the (sparse) eigenvectors of each eigenvalue (m, k).
Rs::Matrix{Int64}: Lattice translation vectors in units of the lattice vectors.ks::Matrix{Float64}: The coordinates of each k-point in units of the reciprocal lattice vectors.sp_mode: EitherDenseorSparse, determines whether the gradients are sparsified.sp_iterator: Special iterator to optimize iteration overi, j, Rfor very sparse systems.
Returns
dE_dHr: An array of shape(NR, Nε, Nk)that contains (sparse) matrices of shape(Nε, Nε).
Hamster.hellman_feynman! — Method
hellman_feynman!(dE_dλ, Ψ_i, dHk_ij)Compute the gradient of the eigenvalues using the Hellmann-Feynman theorem and store the results in dE_dλ.
Arguments
dE_dλ::AbstractArray: Pre-allocated array to store the computed gradients (as Nε×Nε matrix), typically of size(NR, Nε, Nk).Ψ_i::AbstractArray: Array of eigenvectors (wavefunctions), typically of size(Nε, Nk).dHk_ij::AbstractArray: Array representing the derivative of the Hamiltonian with respect someλfor each lattice vector and k-point. Its size is typically(NR, Nk).
Details
For each k-point k and eigenstate m, this function computes the matrix element of the form:
⟨Ψ_i[m, k] | dHk_ij[R, k] | Ψ_i[m, k]⟩and stores the real part of this value in dE_dλ[R, m, k]. This is done for each lattice vector R, eigenstate m, and k-point k.
Hamster.read_current — Function
read_current(comm, ind=0;
filename="ham.h5",
space="r",
system="")Read real-space current operators from an HDF5 file.
This function reads sparse current matrices previously written by write_current from the HDF5 file filename. For each lattice translation R, the current operator is reconstructed as a sparse matrix with SVector{3,ComplexF64} entries representing the Cartesian components of the current.
The current matrices are read from the group C<space> (or C<space>_<system>_<ind> if ind ≠ 0), along with the associated lattice translation vectors.
Arguments
comm: MPI communicator used for collective HDF5 access.ind: Index selecting the current block to read (default:0).
Keyword Arguments
filename: HDF5 file containing the current operators.space: Label identifying the representation (e.g."r"for real space).system: Optional system label used in the HDF5 group name.
Returns
C::Vector{SparseMatrixCSC{SVector{3,ComplexF64},Int64}}: A vector of sparse current matrices, one per lattice translation.vecs::AbstractMatrix{<:Real}: Lattice translation vectors corresponding to the current blocks.
Notes
- Sparse matrices are reconstructed from their stored CSC components (
rowval,colptr,xnzval,ynzval,znzval). - The function assumes the file layout produced by
write_current.
Hamster.read_ham — Function
read_ham(comm, ind=0; filename="ham.h5", space="k")Read a Hamiltonian and associated vectors from an HDF5 file previously written with write_ham.
Arguments
comm::MPI.Comm: MPI communicator used to open the HDF5 file in parallel mode.ind::Int=0: Optional index to identify which Hamiltonian group to read.
Keyword Arguments
filename::AbstractString="ham.h5": Name of the HDF5 file to read from.space::AbstractString="k": Label used in the Hamiltonian group name (e.g.,"Hk"or"Hk_1").
Returns
H::Vector{SparseMatrixCSC}: Vector of Hamiltonian blocks reconstructed as sparse matrices.vecs::Array: The stored array of vectors associated with the Hamiltonian.
Hamster.read_hr — Function
read_hr(filename="hamster_hr.dat"; sp_mode=false, verbose=1)Reads Hamiltonian data and corresponding lattice vectors from a file, reconstructing the Hamiltonian matrices and lattice vectors.
Arguments:
filename::String="hamster_hr.dat": The name of the file containing the Hamiltonian data. The default file name is"hamster_hr.dat".sp_mode::Bool=false: Iftrue, enables sparse matrix storage mode for the Hamiltonians. This is useful for large, sparse Hamiltonians to save memory.verbose::Int64: Sets the verbosity.verbose=0deactivates print statements.
Returns:
Hr: A vector of 2D arrays where each elementHr[R]is a Hamiltonian matrix corresponding to the lattice vectorRs[:, R]. EachHr[R]is a 2D array of size(Nε, Nε), whereNεis the size of the Hamiltonian matrices.Rs: A 2D array where each column is a lattice vector corresponding to the Hamiltonians inHr. The array has dimensions(3, NR), representing the lattice vectors in 3D space.
Behavior:
- The function reads the Hamiltonian data from the specified file.
- The first line of the file specifies the size of the Hamiltonian matrix (
Nε). - The second line specifies the number of lattice vectors (
NR). - The function reads the subsequent lines to extract the Hamiltonian elements and their corresponding lattice vectors.
- If
sp_modeistrue, the Hamiltonians are stored in a sparse format. Otherwise, a dense format is used.
Hamster.write_current — Function
write_current(bonds, comm, ind=0;
ham_file="ham.h5",
filename="ham.h5",
system="",
rank=0,
nranks=1)Compute and write real-space current operators to an HDF5 file.
This function constructs the real-space current matrices from the bond vectors bonds and the real-space Hamiltonian read from ham_file. For each lattice translation R, the current operator is computed as
C(R) = -i / ħ · bonds[R] * H(R),and written in sparse CSC format to the HDF5 file filename.
Each MPI rank writes sequentially to the file, synchronized via barriers, to avoid concurrent write conflicts. The resulting datasets are stored under a group named Cr (or Cr_<system>_<ind> if ind ≠ 0), with one subgroup per lattice translation.
Sparse matrices are stored explicitly via their rowval, colptr, and Cartesian components (xnzval, ynzval, znzval) of the nonzero entries.
Arguments
bonds: Vector of sparse bond matrices indexed by lattice translation, withSVector{3,Float64}entries.comm: MPI communicator.ind: Index selecting the Hamiltonian block to read (default:0).
Keyword Arguments
ham_file: HDF5 file containing the real-space Hamiltonian.filename: Output HDF5 file to which current operators are written.system: Optional system label used in the HDF5 group name.rank: MPI rank of the calling process.nranks: Total number of MPI ranks participating in the write.
Notes
- The reduced Planck constant
ħis assumed to be given in units of eV·fs. - The current vectors have units of Å/fs and correspond to velocity matrix elements (current divided by electron charge).
- The function performs no collective MPI I/O; writes are serialized across ranks using barriers.
Hamster.write_ham — Function
write_ham(H, vecs, comm, ind=0; filename="ham.h5", space="k")Write a Hamiltonian, represented as a vector of sparse matrices, into an HDF5 file in a parallel MPI setting.
Arguments
H::Vector{SparseMatrixCSC}: Vector of sparse matrices that form the Hamiltonian blocks.vecs::AbstractArray: Array of vectors with one vector per block (k or R vectors).comm::MPI.Comm: MPI communicator used to open the HDF5 file in parallel mode.ind::Int=0: Optional index label (e.g., for each atomic configuration).
File structure
The Hamiltonian is stored under a group named:
"H$space"ifind == 0"H${space}_$ind"otherwise
Inside this group:
"vecs": dataset containing the suppliedvecs(k or R vectors).- Subgroups
"1","2", …, one for each block inH, containing:"rowval","colptr","nzval": the CSC representation of the sparse matrix."m","n": matrix dimensions.
Hamster.write_hr — Method
write_hr(Hr, Rs; filename="hamster_hr", tol=1e-8, verbose=1)Writes Hamiltonian data Hr and corresponding lattice vectors Rs to a file.
Arguments:
Hr: A vector of matrices where eachHr[R]contains the Hamiltonian elements corresponding to the lattice vectorRs[:, R].Rs: A 2D array where each column is a lattice vector corresponding to the Hamiltonian elements inHr. The array has dimensions(3, NR), representing the lattice vectors in 3D space.filename::String="hamster_hr": The base name of the output file. The function appends.datto this base name to create the final output file name.tol::Float64=1e-8: A tolerance threshold for determining whether a Hamiltonian element should be considered non-zero and written to the file. Elements with absolute values below this threshold are omitted from the output.verbose::Int64: Sets the verbosity.verbose=0deactivates print statements.
Behavior:
- The function writes the Hamiltonian data to a file named
filename.dat. - The first line of the file contains the size of the Hamiltonian matrix (
Nε). - The second line contains the number of lattice vectors (
NR). - The function writes only the non-zero elements of
Hr(as determined bytol) to the file, along with their corresponding lattice vector indices and matrix indices. - The output file format aligns the numeric values to fixed-width columns for readability.
Hamster.TBModel — Type
TBModel(strc::Structure, basis::Basis, conf=get_empty_config(); update_tb, initas)Constructs a TBModel for the given structure strc and basis basis, based on the configuration conf.
Arguments
strc::Structure: The structure of the material or system being modeled.basis::Basis: The basis functions or orbitals used to describe the electronic states in the tight-binding model.conf: (Optional) A configuration object that contains various settings and parameters for building the model.update_tb: (Optional) A flag indicating whether the model's parameters should be updated during optimization. Defaults toget_update_tb(conf).initas: (Optional) Initialization parameters for the model. Defaults toget_init_params(conf).
Returns
- A
TBModelobject with the geometry tensorhand the model's parameters set viainit_params!.
Hamster.TBModel — Type
TBModelA mutable struct representing a tight-binding model.
Fields
h::Matrix{SparseMatrixCSC{Float64, Int64}}: A matrix where each element is a sparse matrix representing the geometry tensor.parameter_labels::Vector: A vector containing the label for each parameter.V::Vector{Float64}: A vector containing the model's parameters.update::Bool: A boolean flag indicating whether the model's parametersVshould be updated during optimization or kept fixed.
Hamster.get_hr — Function
get_hr(h, V=model.V, mode=Val{:dense})Construct the real-space Hamiltonian (Hr) by multiplying the geometry tensor h with the parameters V.
Arguments
h: A 2D array of matrices where each elementh[v, R]represents a Hamiltonian block associated with parametervand lattice vectorR.V: A vector of parameters.mode: Optional argument that specifies the format of the resulting Hamiltonian (Hr). Defaults toVal{:dense}, but can be other types such as sparse.
Returns
Hr: The resulting real-space Hamiltonian matrix (or array of matrices), constructed by summing the weighted Hamiltonian blocks for each lattice vectorR.
Hamster.get_model_gradient — Method
get_model_gradient(model, dL_dHr)Computes the gradient of the model's parameters using the given derivative of the Hamiltonian dLdHr. If dLdHr is not a vector of matrices (i.e., it represents multiple structures), the function assumes it contains gradients for multiple structures and returns the average gradient across these structures.
Arguments
model: A model object containing the parametersVand the geometry tensorh.dL_dHr: A matrix or array representing the derivative of the loss w.r.t. real-space Hamiltonian matrix elements.
Returns
- The gradients for each parameter in
model.V.
Hamster.get_model_gradient — Method
get_model_gradient(ham::EffectiveHamiltonian, indices, reg, dL_dHr)Computes the gradient of the loss w.r.t. the model parameters.
Arguments
ham::EffectiveHamiltonian: The effective Hamiltonian model.indices::AbstractVector: A set of structure indices.reg: A regularization term or parameter used in the gradient computation.dL_dHr: The derivative of the loss function with respect to the Hamiltonian.
Returns
AbstractVector: A collection of gradients, one for each model in theham.models, computed using the provided indices, regularization term, and loss derivative.
Hamster.get_params — Method
get_params(model::TBModel)Retrieve the parameters associated with a TBModel.
Arguments
model::TBModel: The tight-binding model instance from which to extract parameters.
Returns
- The parameters stored in the
paramsfield of the givenTBModelinstance.
Hamster.init_params! — Function
init_params!(model, basis, conf=get_empty_config(); initas=get_init_params(conf))Initialize the parameters of a model based on the provided configuration and initialization method.
Arguments
model: The model whose parameter arrayVwill be initialized.conf: Configuration settings that can be used to customize how parameters are initialized. By default, an empty configuration is used.initas: Initialization method (e.g.,ones,randomor a file).
Keyword Arguments
conf: Configuration settings.initas: The initialization method or file path for parameters. Defaults toones.
Hamster.set_params! — Method
set_params!(model::TBModel, params)Set the parameters of a TBModel instance while ensuring consistency with the model's structure.
Arguments
model::TBModel: The tight-binding model whose parameters are to be updated.params: The new parameter vector to assign to the model'sparamsfield.
Error Conditions
- Throws an error if the parameter vector
paramsis not of the correct size.
Returns
- Updates the
paramsfield of themodelin place if the consistency checks pass.
Hamster.update! — Method
update!(model::TBModel, opt, dV)Updates the parameters of the given TB model model using the provided optimizer opt and the gradient dV.
Arguments
model: ATBModelobject that contains the parameters to be updated.opt: An optimization algorithm or method used to update the model's parameters.dV: The gradient of the loss w.r.t. to the model parameters.
Hamster.write_params — Function
write_params(model::TBModel, conf=get_empty_config())Writes the parameters of a TBModel using its parameter labels and values.
Arguments
model::TBModel: The tight-binding model whose parameters need to be written.conf: (Optional) Configuration settings, defaults to an empty configuration.
SOC
Hamster.Mtrans — Constant
Mtrans: Dictionary mapping the type of orbital ("s", "p", "d") to its corresponding transformation matrix (Ms, Mp, Md).
Hamster.gen_permutation_matrix — Method
gen_permutation_matrix(initial_order::Vector{String}, desired_order::Vector{String}) -> Array{Int, 2}Generate a permutation matrix P that will reorder elements from initial_order to desired_order.
Arguments
initial_order: A vector of strings representing the initial order of elements.desired_order: A vector of strings representing the desired order of elements.
Returns
- The permutation matrix
Pthat reordersinitial_ordertodesired_order.
Hamster.get_Msoc_d — Function
get_Msoc_d(output_basis_order::Vector{String} = ["dz2↑", "dxz↑", "dyz↑", "dx2-y2↑", "dxy↑", "dz2↓", "dxz↓", "dyz↓", "dx2-y2↓", "dxy↓"]) -> Matrix{Complex{Float64}}Construct the spin-orbit coupling matrix for d orbitals in the spatial basis. This function starts by generating the basis in the |lm,s> representation, calculates the spin-orbit coupling matrix in this basis, and then transforms it to the spatial basis. A permutation is applied to align with the specified output basis order, and numerical tolerance is used to set small values effectively to zero.
Arguments
output_basis_order: The order of orbitals and spins in the output matrix, provided as an array of strings. The default order is the one given in the thesis.
Returns
- The spin-orbit coupling matrix for
dorbitals, ordered according tooutput_basis_order.
Hamster.get_Msoc_ho — Method
get_Msoc_ho(axes; mode="sp3dr2") -> BlockDiagonalCalculate the spin-orbit coupling (SOC) matrix for a given atomic axes and hybridization mode.
Arguments
axes::Matrix{Float64}: The orientation axes of the current atom.mode::String: The hybridization mode, either "sp3" or "sp3dr2" (default: "sp3dr2").
Returns
BlockDiagonal: The SOC matrix in the hybridized basis.
Hamster.get_Msoc_p — Function
get_Msoc_p(output_basis_order::Vector{String} = ["pz↑", "px↑", "py↑", "pz↓", "px↓", "py↓"]) -> Matrix{Complex{Float64}}Calculate the spin-orbit coupling matrix for p orbitals. The function constructs the matrix in the |lm,s> basis, transforms it to the spatial basis for p orbitals, applies a permutation to match the specified output basis order, and then applies numerical tolerance to trim small values.
Arguments
output_basis_order: A vector of strings that defines the order of the orbital and spin basis in the output matrix. The default order is the one given in the thesis.
Returns
- A matrix representing the spin-orbit coupling in the spatial basis with the specified output order.
Hamster.get_Msoc_s — Function
get_Msoc_s() -> zeros(Complex{Float64}, 2, 2)Calculate the spin-orbit coupling matrix for the s orbitals / a zero matrix.
Returns
- The spin-orbit coupling matrix
Msoc_sfor s orbitals.
Hamster.get_hybrid_coefficient_matrix — Method
get_hybrid_coefficient_matrix(axes; mode="sp3dr2") -> Matrix{ComplexF64}Calculate the hybrid coefficient matrix for given axes and mode.
Arguments
axes::Matrix{Float64}: The axes for the atom.mode::String: The hybridization mode, either "sp3" or "sp3dr2" (default: "sp3dr2").
Returns
Matrix{ComplexF64}: The hybrid coefficient matrix.
Hamster.get_soc_matrices — Function
get_soc_matrices(strc::Structure) -> Vector{BlockDiagonal}Precompute the spin-orbit coupling (SOC) matrices for a given structure.
Hamster.get_sp3_expansion_coefficients — Method
get_sp3_expansion_coefficients(θ, φ; Nspd=[1, 3, 0]) -> Vector{Float64}Calculate the sp3 expansion coefficients for given angles θ and φ.
Arguments
θ::Float64: Polar angle.φ::Float64: Azimuthal angle.Nspd::Vector{Int}: Relative proportions of s, p, and d orbitals (default: [1, 3, 0]).
Returns
Vector{Float64}: The expansion coefficients in the order: s, px, py, pz.
Hamster.merge_soc_matrices! — Method
merge_soc_matrices!(dict1::Dict, dict2::Dict)Merge dict2 into dict1 in-place, where both dictionaries map keys to SOC matrices.
Arguments
dict1::Dict: The dictionary to be updated in-place.dict2::Dict: The dictionary to merge intodict1.
Returns
dict1::Dict: The updated dictionary containing all keys from both.
Hamster.trans_lm_spatial — Method
trans_lm_spatial(orb::String, Msoc::Array{T, 2}) where T -> Array{T, 2}Transform the spin-orbit coupling matrix Msoc from the spin basis to the spatial basis for the given orbital type orb.
Arguments
orb: Orbital type as a string ("s", "p", or "d").Msoc: Matrix representing the spin-orbit coupling in the spin basis.
Returns
- The transformed spin-orbit coupling matrix in the spatial basis.
Hamster.SOCModel — Type
mutable struct SOCModel{V, M}A mutable struct representing a model for Spin-Orbit Coupling (SOC) effects.
Type Parameters
V: Type representing a structure-specific ion labeling or identifier.M: Type of the matrices describing SOC interactions, e.g.,Matrix{ComplexF64}.
Fields
params::Vector{Float64}: A vector of model parameters.param_labels::Vector{UInt8}: A vector of integer labels identifying which parameters belong to which ion.types_per_strc::Vector{V}: A vector containing the ion labeling or types for each structure in the dataset.matrices::OrderedDict{UInt8, M}: Ordered dictionary mapping integer type keys to SOC matrices for the orbital basis.Rs_info::Matrix{Int64}: Matrix storing R0 and number of translation vectors for each structure.update::Bool: Flag indicating whether the model is currently set to update its parameters.
Hamster.get_hr — Method
get_hr(soc_model::SOCModel, sp_mode, index; apply_soc=true) -> BlockDiagonalConstructs the Hamiltonian representation for a given spin-orbit coupling (SOC) model.
Arguments
soc_model::SOCModel: The spin-orbit coupling model containing ion types, parameters, and matrices.sp_mode: Unused parameter (possibly reserved for future functionality).index: The index of the ion type for parameter retrieval.apply_soc::Bool(default:true): Iftrue, applies SOC-related modifications (not explicitly used in this function).
Returns
- A
BlockDiagonalmatrix where each block corresponds to an ion type, with parameters expanded and applied to SOC matrices.
Hamster.get_model_gradient — Method
get_model_gradient(soc_model::SOCModel, indices, reg, dL_dHr)Computes the gradient of loss w.r.t. the SOC model's parameters.
Arguments:
soc_model::SOCModel: The SOC model.indices: The structure indices (not used here).reg: A regularization term that penalizes certain parameter values to avoid overfitting or enforce specific behavior.dL_dHr: Gradient of the loss w.r.t. the Hamiltonian matrix elements.
Returns:
dparams: A vector containing the gradient of the loss w.r.t. the model parameters.
Hamster.get_params — Method
get_params(soc_model::SOCModel) -> VectorRetrieves the parameters of a given spin-orbit coupling (SOC) model.
Arguments
soc_model::SOCModel: The SOC model containing the parameter set.
Returns
- A vector of parameters associated with the SOC model.
Hamster.init_soc_params — Function
init_soc_params(ions, conf=get_empty_config(); initas=get_soc_init_params(conf)) -> Vector{Float64}Initializes spin-orbit coupling (SOC) parameters for a given set of ions based on the specified initialization method.
Arguments
ions: A collection of ion objects.conf: (Optional) Configuration object used for consistency checks. Defaults toget_empty_config().initas: (Optional) Specifies the initialization method:'z': Initializes all parameters to zero.'o': Initializes all parameters to one.'r': Initializes parameters with random values.- File path or identifier: Reads SOC parameters from an external source.
Hamster.set_params! — Method
set_params!(soc_model::SOCModel, params) -> NothingUpdates the parameters of a spin-orbit coupling (SOC) model.
Arguments
soc_model::SOCModel: The SOC model whose parameters will be updated.params: A vector of new parameters to assign to the model.
Hamster.update! — Method
update!(soc_model::SOCModel, opt, dparams) -> NothingUpdates the parameters of a spin-orbit coupling (SOC) model using an optimization routine.
Arguments
soc_model::SOCModel: The SOC model whose parameters will be updated.opt: The optimizer or update rule to apply to the parameters.dparams: The parameter updates (e.g., gradients or step values).
Hamster.write_params — Function
write_params(soc_model::SOCModel, conf=get_empty_config()) -> NothingWrites the parameters of a spin-orbit coupling (SOC) model to a file.
Arguments
soc_model::SOCModel: The SOC model whose parameters will be written.conf: Configuration settings (default: an empty configuration fromget_empty_config()).
Hamster.convert_block_matrix_to_sparse — Method
convert_block_matrix_to_sparse(M::BlockDiagonal; sp_tol=1e-10) -> SparseMatrixCSCConverts a BlockDiagonal matrix M to a SparseMatrixCSC by iterating through each block and collecting the nonzero entries (within a given tolerance).
Arguments
M::BlockDiagonal: A block diagonal matrix, typically fromBlockDiagonals.jlor similar libraries.
Hamster.get_lms_basis — Method
create_basis_lm(orb::String) -> Vector{Vector{Int64}}Create the basis set in the |lm,s> representation for a given type of orbital specified by orb. This function asserts that orb is one of the strings "s", "p", or "d", which correspond to the different orbital types. It uses the num_mdict to fetch the corresponding m values and constructs a basis set with l, m, and spin quantum numbers.
Arguments
orb: A string specifying the orbital type ("s", "p", or "d").
Returns
basis: A vector of vectors, with each sub-vector containing the quantum numbers[l, m, spin].
Hamster.get_matrix_lmbasis — Method
get_matrix_lmbasis(basis::Vector{Vector{Int}}) -> Matrix{Complex{Float64}}Construct the spin-orbit coupling matrix in the |lm,s> basis. This matrix represents the dot product of the angular momentum operators with the spin operators.
Arguments
basis: A vector of basis sets, each represented by a vector of quantum numbers[l, m, spin].
Returns
- A matrix of type
Complex{Float64}representing the spin-orbit coupling in the given basis.
Hamster.mapLmSp — Method
mapLmSp(lms::Vector{Int}) -> Tuple{Float64, Vector{Int}}Map the |lm,s> state to another state with the momentum and spin ladder operator L-S+. The function calculates the coefficient for the operation and the resulting state.
Arguments
lms: A vector of quantum numbers[l, m, s].
Returns
- A tuple of the coefficient of the operation and the new quantum numbers
[l, m-1, s+2].
Hamster.mapLpSm — Method
mapLpSm(lms::Vector{Int}) -> Tuple{Float64, Vector{Int}}Map the |lm,s> state to another state with the momentum and spin ladder operator L+S-. The function calculates the coefficient for the operation and the resulting state.
Arguments
lms: A vector of quantum numbers[l, m, s].
Returns
- A tuple of the coefficient of the operation and the new quantum numbers
[l, m+1, s-2].
Hamster.mapLzSz — Method
mapLzSz(lms::Vector{Int}) -> Tuple{Int, Vector{Int}}Map the |lm,s> state to itself while calculating the coefficient for the LzSz operation.
Arguments
lms: A vector of quantum numbers[l, m, s].
Returns
- A tuple of the coefficient m for s=1 or -m for s=-1, and the unchanged quantum numbers
[l, m, s].
Hamster.separate_spin_secs — Method
separate_spin_secs(orb_order::Vector{String}) -> Vector{String}Reorder the basis by separating the spin components. This function does not alter the order of spatial dimensions (e.g., s, py, sp3₁), but sorts the spin sector such that all up-spin (↑) components appear before all down-spin (↓) components.
Hamster.thresholding — Function
thresholding(c::Complex, real_threshold::Real=1e-15) -> ComplexApply thresholding to a complex number, setting real and imaginary parts below the threshold to zero.
Arguments
c::Complex: The complex number to threshold.real_threshold::Real: The threshold value for the real and imaginary parts (default: 1e-15).
Returns
Complex: The thresholded complex number.
ML
Hamster.decide_orbswap — Method
decide_orbswap(itype, jtype, l_i, m_i, l_j, m_j) -> BoolDetermines whether two orbitals should be swapped to enforce a consistent ordering, based on their associated ion types and quantum numbers. The ordering is determined by:
- Comparing element types using a periodic table-based numerical ordering (
element_to_number). - If element types are the same, comparing orbital angular momentum quantum numbers (
l_i,l_j). - If
lvalues are equal, comparing magnetic quantum numbers (m_i,m_j).
This helps maintain consistent descriptor or feature vector construction in systems involving atomic orbitals.
Arguments
itype: Symbol or string representing the first ion type (e.g.,:H,"O").jtype: Symbol or string representing the second ion type.l_i: Orbital angular momentum quantum number of the first orbital.m_i: Magnetic quantum number of the first orbital.l_j: Orbital angular momentum quantum number of the second orbital.m_j: Magnetic quantum number of the second orbital.
Returns
trueif the orbitals should be swapped to maintain ordering;falseotherwise.
Hamster.decide_orthogonal — Method
decide_orthogonal(Δr, i, j, l_i, l_j; apply_orthogonality=false) -> BoolDetermine whether two atomic orbitals should be treated as orthogonal.
Arguments
Δr::Real: Distance between the centers of the two orbitals.i::Int: Index of the first orbital.j::Int: Index of the second orbital.l_i::Int: Angular momentum quantum number (or orbital type) of the first orbital.l_j::Int: Angular momentum quantum number (or orbital type) of the second orbital.apply_orthogonality::Bool(keyword, default=false) : Whether to enforce atomic orthogonality rules.
Returns
Bool:trueif the orbitals are considered orthogonal,falseotherwise.
Hamster.farthest_point_sampling — Method
farthest_point_sampling(descriptors, cluster_indices, num_to_take)Selects num_to_take diverse points from a subset of data specified by cluster_indices using greedy farthest-point sampling based on Euclidean distance.
Arguments
descriptors::AbstractMatrix{<:Real}: A matrix of feature vectors where each column corresponds to a data point.cluster_indices::Vector{Int}: Indices of the points indescriptorsthat belong to the cluster to sample from.num_to_take::Int: Number of points to select.
Returns
selected::Vector{Int}: Indices of the selected points (subset ofcluster_indices) representing a diverse subset.
Hamster.get_angular_descriptors — Method
get_angular_descriptors(itype, jtype, ri, rj, iaxis, jaxis, orbswap)Computes angular descriptors based on the relative positions and orbital orientations of two atoms.
Arguments
itype, jtype: Atomic types of the two atoms.ri, rj: Position vectors of the two atoms.iaxis, jaxis: Axes defining the local orbital orientation for each atom.
Returns
φ::Float64: The angle between the two orbital axes.θs::Vector{Float64}: A sorted or conditionally reversed list of angles between each axis and the bond direction.
Behavior
- Computes the normalized bond direction
ΔrijandΔrjidepending on the distance between the atoms. - Determines the angle
φbetween the two orbital axes. - Computes
θs, the angles between each axis (iaxis,jaxis) and the respective bond directions. - Ensures consistent ordering of
θsbased on atomic types and orbital swapping rules.
Hamster.get_environmental_descriptor — Method
get_environmental_descriptor(h, V, strc, basis, conf::Config; apply_params=false, rcut=get_ml_rcut(conf))Computes the environmental descriptor for a given structure, basis, and configuration object.
Arguments
h: The geometry tensor for the given structure.V: A vector of interaction parameters.strc: The structure containing lattice and atomic positions.basis: The basis set defining the system's orbitals.conf::Config: Configuration object.
Keyword Arguments
apply_params: Iftrue, usesVas given; otherwise, is set to ones.rcut: Cut-off radius for interactions, defaults toget_ml_rcut(conf).
Returns
env: A vector representing the environmental descriptor.
Hamster.get_tb_descriptor — Method
get_tb_descriptor(model, strc, conf)Calculate the TB descriptor for a given a TB model, a structure strc and a TBConfig file conf.
Hamster.reshape_structure_descriptors — Method
reshape_structure_descriptors(descriptors) -> Matrix{Float64}Reshapes a nested structure of sparse descriptors into a dense matrix (to be used as input for kmeans).
Arguments
descriptors: A nested collection of sparse matrices representing structure descriptors.
Returns
- A matrix (
Matrix{Float64}) where each column corresponds to a flattened descriptor.
Hamster.sample_structure_descriptors — Method
sample_structure_descriptors(descriptors; Ncluster=1, Npoints=1, alpha=0.5, ml_sampling="random")Selects a subset of descriptor vectors using K-Means clustering, weighted by cluster size and spread.
Arguments
descriptors: A matrix where each column represents a descriptor vector.Ncluster::Int=1: The number of clusters for K-Means.Npoints::Int=1: The total number of descriptor vectors to select.alpha::Float64=0.5: A weighting factor (0 ≤ α ≤ 1) that balances selection between cluster size (α → 1) and spread (α → 0).ml_sampling::String: Determines how points are selected from each cluster. Defaults to random.
Returns
- A matrix of selected descriptor vectors with
Npointscolumns.
Hamster.HamiltonianKernel — Type
HamiltonianKernel(strcs, bases, model, comm, conf;
verbosity=get_verbosity(conf),
Ncluster=get_ml_ncluster(conf),
Npoints=get_ml_npoints(conf),
sim_params=get_ml_sim_params(conf),
update_ml=get_ml_update(conf),
mode=get_ml_mode(conf),
rank=0,
nranks=1)Constructs a HamiltonianKernel model for machine learning-based Hamiltonian parameterization.
Arguments
strcs: Vector ofStructureobjects.bases: Vector ofBasisobjects corresponding to each structure.model: The underlying TB Hamiltonian model.comm: MPI communicator.conf: Configuration object.verbosity: Integer controlling logging output.Ncluster: Number of clusters for ML sampling.Npoints: Number of points to sample.sim_params: Kernel similarity measure.update_ml: Boolean flag controlling whether ML parameters are updated .mode: ML training mode, one of"eval","refit","expand".rank: MPI rank of the current process (default: 0).nranks: Total number of MPI ranks (default: 1).
Returns
A HamiltonianKernel object.
Notes
- MPI is used for distributed sampling of data points; ensure that
comm,rank, andnranksare consistent. - The function supports evaluation-only mode (
mode="eval") where parameters are not updated. - New or expanded parameters are initialized according to the
init_ml_paramsconfiguration.
Hamster.HamiltonianKernel — Type
mutable struct HamiltonianKernel{T1, T2}A kernel structure used for computing weighted similarity functions.
Fields
ws :: Vector{Float64}: Weights for each sample point.xs :: Vector{T1}: Sample points.sim_params :: T2: Parameters for the similarity function.
Hamster.get_hr — Method
get_hr(kernel::HamiltonianKernel, mode, index; apply_soc=false) -> Vector{Matrix{Float64}}Constructs a set of real-space Hamiltonians from a HamiltonianKernel.
Arguments
kernel::HamiltonianKernel: The Hamiltonian kernel used for computing matrix elements.mode: Specifies the sparsity mode.index: Index specifying which structure to evaluate.
Keyword Arguments
apply_soc: Iftrue, applies the spin-orbit coupling (SOC) basis transformation.
Returns
- A vector of real-space Hamiltonian matrices, optionally modified with SOC transformations.
Hamster.get_model_gradient — Method
get_model_gradient(kernel::HamiltonianKernel, indices, reg, dL_dHr) -> Vector{Float64}Computes the gradient of the model parameters for a given HamiltonianKernel.
Arguments
kernel::HamiltonianKernel: The Hamiltonian kernel for which the gradient is computed.indices: Indices specifying which structure descriptors to use.reg: Regularization term.dL_dHr: Gradient of the loss function with respect to the real-space Hamiltonian.
Returns
dparams: A vector containing the computed gradients of the model parameters.
Hamster.get_params — Method
get_params(kernel::HamiltonianKernel)Retrieve the parameters associated with a HamiltonianKernel.
Arguments
kernel::HamiltonianKernel: The Hamiltonian kernel instance from which to extract parameters.
Returns
- The parameters stored in the
wsfield of the givenHamiltonianKernelinstance.
Hamster.init_ml_params! — Function
init_ml_params!(data_points, conf=get_empty_config();
initas=get_ml_init_params(conf),
filename=get_ml_filename(conf),
mode=get_ml_mode(conf),
update_ml=get_ml_update(conf))Initializes ML parameters.
Arguments
data_points: An array of data points associated with the ML parameters.conf: A configuration object.initas: A string specifying the initialization strategy for new parameters:"zeros"or'z': Initialize parameters to zeros."ones"or'o': Initialize parameters to ones."rand"or'r': Initialize parameters with random values."file": Load parameters from a file (initasis interpreted as the filename in eval mode).
filename: A string specifying the file from which old parameters can be loaded whenmode="expand".mode: A string (default:get_ml_mode(conf)) specifying the ML training mode:"refit": Train from scratch."eval": Evaluation mode."expand": Load old parameters fromfilenameand append new parameters initialized according toinitas.
update_ml: Boolean controlling whether ML parameters are updated during training.
Returns
params: Array of initialized ML parameters.data_points: (Updated) array of data points.
Hamster.read_ml_params — Function
read_ml_params(conf=get_empty_config(); filename=get_ml_filename(conf))Reads the parameters for a HamiltonianKernel model from a file and returns the parameters and associated data points.
Arguments
conf: A configuration object (default:get_empty_config()) containing simulation parameters and settings.filename: The name of the.datfile to read from (default:get_ml_filename(conf)).
Hamster.set_params! — Method
set_params!(kernel::HamiltonianKernel, ws)Set the parameters of a HamiltonianKernel instance.
Arguments
kernel::HamiltonianKernel: The kernel model whose parameters are to be updated.ws: The new parameter vector.
Error Conditions
- Throws an error if the parameter vector
wsis not of the correct size.
Returns
- Updates the
Vsfield of thekernelin place if the consistency checks pass.
Hamster.update! — Method
update!(kernel::HamiltonianKernel, opt, grad)Updates the parameters of a HamiltonianKernel using an optimization method opt.
Arguments
kernel::HamiltonianKernel: The Hamiltonian kernel whose parameters are to be updated.opt: The optimizer used to perform the update.grad: The gradient used for updating the parameters.
Hamster.write_params — Function
write_params(kernel::HamiltonianKernel, conf=get_empty_config(); filename=get_ml_filename(conf))Writes the parameters and configuration settings of a HamiltonianKernel object to a file.
Arguments
kernel::HamiltonianKernel: The HamiltonianKernel object containing the parameters and data points to write to the file.conf: A configuration object (default:get_empty_config()) containing simulation parameters and settings.filename: The name of the file to which the data will be written (default:get_ml_filename(conf)).
Optimization
Hamster.Adam — Type
Adam(η = 0.001, β::Tuple = (0.9, 0.999), ϵ = 1.0e-8)Adam optimiser.
Parameters
- Learning rate (
η): Amount by which gradients are discounted before updating the weights. - Decay of momentums (
β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.
Examples
opt = Adam()
opt = Adam(0.001, (0.9, 0.8))Hamster.DataLoader — Type
DataLoader{A, B}A struct to store and manage training and validation datasets.
Fields
train_data::Vector{A}: A vector containing the training dataset. The typeArepresents the data type of the training set.val_data::Vector{B}: A vector containing the validation dataset. The typeBrepresents the data type of the validation set.
Hamster.EigData — Type
EigDataA struct for storing eigenvalue data associated with k-points.
Fields
kp::Matrix{Float64}: A matrix where each column represents a k-point.Es::Matrix{Float64}: A matrix where each column represents the eigenvalues corresponding to the respective k-point.
Hamster.HrData — Type
HrData{M}A struct for storing Hamiltonian data Hr and the associated lattice translation vectors Rs for a system, typically from Wannier90.
Fields
Rs::Matrix{Float64}: A matrix where each column represents a lattice translation vector.Hr::Vector{M}: A vector of Hamiltonian matricesHr, where each entry corresponds to a lattice translation vector inRs. Each element in this vector is a Hamiltonian matrix, withMrepresenting the matrix type (e.g., dense or sparse).
Hamster.get_neig_and_nk — Method
get_neig_and_nk(data::Vector)Get the number of eigenvalues and the number of k-points from a collection of data.
Arguments
data: A vector of eitherEigDataorHrData.
Returns
(Neig, Nk): The number of eigenvalues and k-points of the first data point.Return 0 for HrData.
Hamster.get_translation_vectors_for_hr_fit — Function
get_translation_vectors_for_hr_fit(conf=get_empty_config(); hr_fit=get_hr_fit(conf), train_data=get_train_data(conf))::Matrix{Float64}If fitting the model to Hr data, read the respective translation vectors from the train_data file.
Arguments
conf(default:get_empty_config()): AConfiginstance.hr_fit: If true, model is fit to Hr data.train_data: Path to the training data file.
Returns
Rs::Matrix{Float64}: The translation vectors, if nothr_fit, return zeros (Rs are calculated depending onrcut).
Hamster.GDOptimizer — Type
GDOptimizer(Nε, Nk, conf=get_empty_config(); lr=get_lr(conf), Niter=get_niter(conf))Creates a gradient descent optimizer for a given loss function, regularization term, and optimizer configuration.
Arguments
Nε::Int(optional): Parameter representing the number of energy levels. IfNε == 0, a default configuration is used.Nk::Int(optional): Parameter representing the number of k-points. IfNk == 0, a default configuration is used.conf::Any: Configuration object for the optimizer, defaults toget_empty_config().lr::Float64(optional): Learning rate for the Adam optimizer. Defaults to the value returned byget_lr(conf).Niter::Int(optional): Number of iterations for the optimization process. Defaults to the value returned byget_niter(conf).val_weights::Bool(optional): If true, same weights are used for validation as for training.
Hamster.GDOptimizer — Type
GDOptimizerA gradient descent optimizer for training Hamiltonian models, incorporating loss functions, regularization, and an Adam optimizer for parameter updates.
Fields
loss::Loss: The loss function used for training. Determines how the model's error is measured and minimized during training.val_loss::Loss: The loss function used for validation. Evaluates the model's performance on unseen data.reg::Regularization: Regularization strategy applied during training to prevent overfitting.adam::Adam: The Adam optimizer instance used for updating model parameters with gradient-based methods.Niter::Int64: The number of training iterations.
Usage
This structure encapsulates all components required for optimizing a Hamiltonian model. It is typically passed to training functions, such as train_step! or optimize_model!, to guide the optimization process.
Hamster.Loss — Type
Loss(Nε, Nk; conf=get_empty_config(), loss=get_loss(conf), wE=get_band_weights(conf, Nε), wk=get_kpoint_weights(conf, Nk))Create a Loss object with band weights, k-point weights, and loss norm based on a given configuration.
Arguments
Nε::Int64: Number of energy bands (dimension ofwE).Nk::Int64: Number of k-points (dimension ofwk).conf: Configuration object (default:get_empty_config()). This is used to retrieve parameters for customizing the loss function.loss: A string that specifies the type of loss function. The default value is obtained fromget_loss(conf).wE: Vector of weights for the energy bands, defaulted toget_band_weights(conf, Nε).wk: Vector of weights for the k-points, defaulted toget_kpoint_weights(conf, Nk).
Keyword Arguments
wE: The band weights, used to scale the errors over energy bands (default provided by configuration).wk: The k-point weights, used to scale the errors over k-points (default provided by configuration).
Returns
- A
Lossobject initialized with the appropriate band weights (wE), k-point weights (wk), normalization factor, and loss norm (n).
Hamster.Loss — Type
struct LossA structure representing a (weighted) loss function for evaluating the difference between predicted and true values. The loss is calculated based on a given norm, with optional weights applied to the errors along the prediction and observation dimensions.
Fields
wE::Vector{Float64}: A vector of weights applied to the error terms along theydimension (true values).wk::Vector{Float64}: A vector of weights applied to the error terms along theŷdimension (predicted values).N::Float64: Normalization factor, typically the product of the sums ofwEandwk.n::Int64: The order of the norm used for the loss function (e.g., 1 for L1 norm, 2 for L2 norm, etc.).
Hamster.Regularization — Type
Regularization([conf]; lambda=get_lambda(conf), barrier=get_barrier(conf), lreg=get_lreg(conf)) -> RegularizationCreate a Regularization struct using configuration parameters from the provided configuration or default values.
Arguments
conf: A configuration object (optional). Default values are used if not provided.
Returns
- A
Regularizationstruct initialized with the provided or default configuration values forbarrier,lambda, andlreg.
Hamster.Regularization — Type
struct RegularizationA data structure that defines the regularization parameters used to penalize model complexity during optimization. Regularization is used to penalize large model parameters to avoid overfitting.
Fields
b::Float64: The barrier for the regularization term. Regularization is only applied if parameter values surpass this barrier.λ::Float64: The regularization coefficient (lambda), which controls the intensity of regularization. A higher value leads to stronger regularization.n::Int64: The norm type used for the regularization term, typically corresponding to L1 (n=1), L2 (n=2), or other norm types.
Hamster.backward — Method
backward(l::Loss, y, ŷ)Compute the gradient of the loss function with respect to the predicted values ŷ.
Arguments
l::Loss: ALossobject which specifies how the loss is calculated.y::AbstractVector: The predicted for each band and k-point.ŷ::AbstractVector: The true values (ground truth) for each band and k-point.
Returns
dL::AbstractArray: The gradient of the loss with respect to the predicted valuesy.
Hamster.backward — Method
backward(R::Regularization, x::AbstractVector) -> AbstractVectorCompute the gradient of the regularization penalty with respect to the input (parameter) vector x.
Arguments
R::Regularization: ARegularizationobject.x::AbstractVector: The input (parameter) vector for which the gradient of the regularization penalty is computed.
Returns
AbstractVector: A vector of the same size asx, where each element is the gradient of the penalty with respect to the corresponding element inx.
Hamster.forward — Method
forward(l::Loss, y, ŷ)Compute the forward pass of the loss function given the true values y and the predicted values ŷ.
Arguments
l::Loss: ALossobject which specifies how the loss is calculated.y::AbstractArray: The predicted for each band and k-point.ŷ::AbstractArray: The true values (ground truth) for each band and k-point.
Returns
-L::Float64: The loss between y and ŷ.
Hamster.forward — Method
forward(R::Regularization, x::AbstractVector) -> Float64Compute the regularization penalty for the given input x using the regularization parameters defined in the Regularization struct.
Arguments
R::Regularization: ARegularizationobject.x::AbstractVector: The input (parameter) vector over which the regularization penalty is applied.
Returns
Float64: The total regularization penalty
Hamster.get_weight_index_from_key — Method
get_weight_index_from_key(key::String) -> UnitRange{Int64}Parses a weight key string and returns a range of indices.
Arguments
key::String: A string representing a weight index, either as a single value (e.g.,"key_1") or as a range (e.g.,"key_1-3").
Returns
- A
UnitRange{Int64}representing the parsed index or index range.
Hamster.backward — Function
backward(ham::EffectiveHamiltonian, index, loss, data, cache)Computes the gradient of the loss for a given Hamiltonian model ham with respect to its matrix elements, based on the specified loss function loss and input data data. The function behavior varies depending on the type of data, which can be either EigData or HrData.
Arguments
ham::EffectiveHamiltonian: The Hamiltonian model for which the gradient of the loss is being computed.index: An index that specifies which Hamiltonian structure to use in the gradient computation.loss: A function that calculates the discrepancy between computed and ground truth values.data: Either anEigDataobject containing k-point and ground truth eigenvalues, or anHrDataobject containing real-space Hamiltonian data.cache: A preliminary result fromforwardthat is required to compute the gradient.
Returns
gradient: The computed gradient of the loss with respect to the parameters ofham.
Hamster.forward — Method
forward(ham::EffectiveHamiltonian, index, loss, data)Computes the loss for a given Hamiltonian model ham using a specified loss function loss and input data data. The behavior of the function depends on the type of data, which can be either EigData or HrData.
Arguments
ham::EffectiveHamiltonian: The Hamiltonian model from which effective Hamiltonians or real-space Hamiltonians are derived.index: An index that specifies which structure to compute.loss: A function that calculates the discrepancy between computed and ground truth values.data: Either anEigDataobject containing k-point and ground truth eigenvalues, or anHrDataobject containing real-space Hamiltonian data.
Returns
L_train::Float64: The calculated loss.cache: A preliminary result that is needed to compute the gradient.
Hamster.optimize_model! — Function
optimize_model!(ham_train, ham_val, optim, dl, prof, conf=get_empty_config(); verbosity=get_verbosity(conf), Nbatch=get_nbatch(conf), validate=get_validate(conf), rank=0, nranks=1)Optimizes the model by performing training and optional validation steps.
Arguments
ham_train: The Hamiltonian model used for training.ham_val: The Hamiltonian model used for validation (optional).optim: An optimization configuration, including the optimizer and its settings.dl: A data loader object containing the training data.prof: A profiler object used to store training and validation information.comm: The MPI communicator.conf: AConfiginstance.verbosity: The level of verbosity for logging.Nbatch: The number of batches per training iteration.validate: A flag indicating whether to perform validation during training.
Workflow
- Print the start message.
- For each training iteration, split the training data into batches and perform training steps.
- Optionally validate the model after each training iteration.
- Print the final status once training is complete.
Returns
- Updates the HamsterProfiler
profand the model parameters inham_trainandham_val.
Hamster.train_step! — Function
train_step!(ham_train, indices, optim, train_data)Performs a single training step on a Hamiltonian model by computing gradients and updating model parameters.
Arguments
ham_train: The Hamiltonian model being trained.indices: The indices of the structures to be evaluated.optim: AGDOptimizerinstance.train_data: The training data.prof: AHamsterProfilerinstance.iter: The iteration index.batch_id: The batch index.comm: The MPI communicator.conf: AConfiginstance.rank: The active MPI rank.nranks: The total number of MPI ranks.
Side Effects
- Updates the model parameters in-place within
ham_train. - Writes timing information and training loss to
prof.
Hamster.val_step! — Method
val_step!(ham_val, loss, val_data, prof, iter, comm, rank=0)Evaluates the validation loss for a Hamiltonian model over a given validation dataset, and stores the results in the HamsterProfiler instance. This function also tracks the time taken for validation.
Arguments
ham_val: The Hamiltonian model being validated.loss: The loss function used to evaluate the performance of the model.val_data: A collection of validation data.prof: An instance of theHamsterProfilerstruct that tracks various profiling information, including validation times and losses.iter: The current iteration number, used to store the validation results at the correct index in theprofinstance.
Returns
L_val: The average validation loss computed over all validation structures. This value is also stored inprof.L_valat the index corresponding toiter.- Updates to
prof.val_times: The elapsed time for the validation step is stored inprof.val_times[iter].
Hamster.HamsterProfiler — Type
HamsterProfiler(Ntimes, conf=get_empty_config(); Nbatch=get_nbatch(conf), Niter=get_niter(conf), printeachbatch=get_printeachbatch(conf), printeachiter=get_printeachiter(conf))A constructor function for initializing a HamsterProfiler instance.
Arguments
Ntimes::Int: The number of timing measurements to store for each batch and iteration.conf::Dict: A configuration dictionary (optional). Default is the result ofget_empty_config().Nbatch::Int: The number of batches (optional). Default is determined by the value ofget_nbatch(conf).Niter::Int: The number of iterations (optional). Default is determined by the value ofget_niter(conf).printeachbatch::Bool: A flag to determine whether to print detailed status for each batch (optional). Default is determined by the value ofget_printeachbatch(conf).printeachiter::Int: Specifies the frequency of printing status updates (optional). Default is determined by the value ofget_printeachiter(conf).Nparams::Int: The number of parameters that are optimized.
Returns
- An instance of the
HamsterProfilerstruct.
Hamster.HamsterProfiler — Type
HamsterProfilerA data structure for tracking and managing profiling information during an iterative process, including loss, timing, and verbosity settings.
Fields
L_train::Matrix{Float64}: A 2D array where each row corresponds to training loss values for a specific batch across iterations.L_val::Vector{Float64}: A 1D array containing validation loss values across iterations.printeachbatch::Bool: Indicates whether to print detailed status updates for each batch during training.printeachiter::Int64: Specifies the frequency (in number of iterations) at which status updates are printed.timings::Array{Float64, 3}: A 3D array storing timing information:- First dimension: batches.
- Second dimension: iterations.
- Third dimension: additional timing steps or phases within each iteration.
val_times::Vector{Float64}: A 1D array containing validation timing information for each iteration.param_values::Vector{Float64}: A 2D array where each column stores the parameter values for a given iteration.
Usage
The HamsterProfiler struct is used in training workflows to:
- Record and track training and validation loss values.
- Measure and store timing data for profiling purposes.
- Control the verbosity and frequency of printed status updates.
Hamster.decide_printit — Method
decide_printit(batch_id, Nbatch, iter, printeachbatch, printeachiter; verbosity=verbosity)Determines whether to print status updates based on the current iteration, batch, and verbosity settings.
Arguments
batch_id::Int: The current batch identifier.Nbatch::Int: The total number of batches.iter::Int: The current iteration number.printeachbatch::Bool: Whether to print at the end of each batch.printeachiter::Int: Interval for printing during iterations ifprinteachbatchis false.verbosity::Int: (Keyword argument) The verbosity level. Printing is disabled ifverbosityis less than 1.
Returns
Bool:trueif a status update should be printed,falseotherwise.
Behavior
- If
verbosity < 1, printing is disabled and the function returnsfalse. - If
printeachbatchistrue, the function always returnstrue. - Otherwise, printing occurs only if:
- The current batch is the last batch (
batch_id == Nbatch), and - The current iteration number (
iter) is a multiple ofprinteachiter.
- The current batch is the last batch (
Hamster.print_final_status — Method
print_final_status(prof)Prints the final loss, the total time elapsed, and a message indicating that the run has finished.
Arguments
prof: A HamsterProfiler instance used to computefinal_lossandtotal_time.
Hamster.print_iteration_status — Method
print_iteration_status(iter, Niter, batch_id, Nbatch, L_train, time_iter, time_left)Prints the current status of an iterative process, including iteration number, batch details, loss, and timing information.
Arguments
iter::Int: The current iteration number.Niter::Int: The total number of iterations.batch_id::Int: The current batch identifier (use0if not using batches).Nbatch::Int: The total number of batches (use0if not using batches).L_train::Union{Float64, Int}: The current training loss value. Use0if loss is not being reported.time_iter::Float64: Time elapsed for the current iteration, in seconds.time_left::Float64: Estimated time remaining to complete the process, in seconds.
Behavior
The function adapts its printed output based on the values of batch_id and L_train:
- No batches and loss reported:
- Prints iteration number, total iterations, loss, iteration time, and estimated time left.
- No batches, no loss reported:
- Prints iteration number, total iterations, iteration time, and estimated time left.
- With batches and loss reported:
- Prints batch number, total batches, iteration number, total iterations, loss, iteration time, and estimated time left.
- With batches, no loss reported:
- Prints batch number, total batches, iteration number, total iterations, iteration time, and estimated time left.
Hamster.print_start_message — Method
print_start_message(prof)Prints a message indicating the start of a run, along with the total number of iterations.
Arguments
prof: A HamsterProfiler instance.
Hamster.print_train_status — Method
print_train_status(prof, iter, batch_id; verbosity=1)Prints the training status during an iterative training process, including loss, timing, and iteration progress.
Arguments
prof: A profiling object containing training data, configuration, and timing information. Expected fields include:L_train: A 2D array where each row corresponds to batch loss values across iterations.timings: A 3D array of timing data, where the first dimension corresponds to batch timing, the second to iteration, and the third to another dimension (e.g., steps or phases).printeachbatch: A boolean indicating whether to print details for every batch.printeachiter: A boolean indicating whether to print details for iterations only.
iter::Int: The current iteration number.batch_id::Int: The current batch identifier (use0if not using batches).verbosity::Int(optional): Controls the level of detail in the output. Default is1.
Hamster.print_val_start — Method
print_val_start(; verbosity=1)Prints a message indicating the start of the model validation process.
Arguments
verbosity: (optional) An integer controlling the level of output. Ifverbosity > 0, the message "Validating model..." will be printed. Default is1.
Hamster.print_val_status — Method
print_val_status(prof, iter; verbosity=1)Prints the validation loss and the time taken for validation at a specific iteration during the training process.
Arguments
prof: AHamsterProfilerobject that contains profiling information, including the validation loss (L_val) and validation times (val_times).iter: The current iteration number in the training process.verbosity: (optional) An integer controlling the level of output. Ifverbosity > 0, the validation status will be printed. Default is1.
Hamster.save — Function
write_prof(prof::HamsterProfiler; filename="hamster_out.h5")Write the contents of a HamsterProfiler object to an HDF5 file (only if rank==0).
Arguments
prof::HamsterProfiler: The profiler instance.filename::String="hamster_out.h5": Path to the HDF5 file to write.
Parsing functions
Hamster.parse_commandline — Method
parse_commandline(args::Vector{String}) -> Dict{String, String}Parses command-line arguments from a vector of strings args and returns a dictionary of parsed arguments.
Arguments
args: A vector of command-line arguments passed as strings.
Behavior
- Keyword arguments (
--option): If an argument starts with--, it is treated as a key with an associated value in the following position. If a comma is found at the end of an argument, the following arguments are concatenated until no comma is found. - Flags (
-o): If an argument starts with a single-, it is treated as a flag and is set totrue(empty "–" arguments are also treated as flags). - Positional arguments: stored with key
pos_arg_i.
Returns
args_dict: A dictionary containing parsed command-line arguments. Long options are stored as key-value pairs, flags are stored with a value oftrue.
Hamster.read_eigenval — Function
read_eigenval(file::AbstractString, nmax::Int=1000000)Read the EIGENVAL VASP output file and extract the k-points, energy bands and occupancies.
Arguments
file::AbstractString: The path to theEIGENVALfile.nmax::Int=1000000: The maximum number of bands to read. Default is 1,000,000.
Returns
kpoints::Array{Float64, 2}: A 3 x nkpts array where each column represents a k-point.E_bands::Array{Float64, 2}: An nbands x nkpts array of energy bands.occs::Array{Float64, 2}: An nbrand × nkpts array of band occupancies.
Hamster.Poscar — Type
struct PoscarA structure to represent the data contained in a VASP POSCAR file.
Fields
a::Float64: The scaling factor.lattice::Array{Float64, 2}: A 3x3 array representing the lattice vectors.atom_names::Array{AbstractString, 1}: An array of atom names.atom_numbers::Array{Int64, 1}: An array of the number of each type of atom.rs_atom::Array{Float64, 2}: A 3xNion array of atomic positions.atom_types::Array{String, 1}: An array of atom types corresponding to each atom position.
Hamster.read_poscar — Method
read_poscar(poscar::AbstractString) -> PoscarExtract all data from the POSCAR file at poscar.
Arguments
poscar::AbstractString: The path to the POSCAR file.
Returns
Poscar: APoscarstruct containing all the extracted data from the POSCAR file, including:a: The scaling factor.lattice: The 3x3 array of lattice vectors.atom_names: An array of atom names.atom_numbers: An array of the number of each type of atom.rs_atom: A 3xNion array of atomic positions.atom_types: An array of atom types corresponding to each atom position.
Hamster.collapse_files_with — Method
collapse_files_with!(str)Searches for all output files in the "tmp" directory that contain the substring str in their filename. Reads and combines their data into a single large array, then writes the merged result to a new file named str*".dat".
Arguments
str::String: A substring to match filenames in the"tmp"directory.
Hamster.get_rank_filename — Method
get_rank_filename(filename::AbstractString, rank::Integer) -> StringReturn a modified file path of the form tmp/<basename>_<rank>.<ext>. Example: rankfilename("data.h5", 3) == "tmp/data3.h5"
Hamster.next_line_with — Method
next_line_with(keywords, lines)Find the next line in lines that contains a set of keywords.
Hamster.open_and_read — Method
open_and_read(file::AbstractString) -> Vector{String}Open a file, read all lines, and return them as a vector of strings.
Arguments
file::AbstractString: The path to the file to be read.
Returns
lines::Vector{String}: A vector where each element is a line from the file.
Hamster.parse_lines_as_array — Method
parse_lines_as_array(lines; i1=1, i2=3, type=Float64)Parses a list of strings into a 2D array, extracting and converting elements from each line based on specified indices and type.
Arguments
lines: A list of strings, where each string is a line containing elements to be parsed.i1(optional): The starting index for the elements to extract from each line. Defaults to1.i2(optional): The ending index for the elements to extract from each line. Defaults to3.type(optional): The type to which the extracted elements should be converted. Defaults toFloat64.
Returns
- A 2D array of the specified
type, where each row corresponds to a line and each column corresponds to an extracted element from the line.
Hamster.print_hamster — Function
print_hamster(io_stream=stdout)Prints an ASCII art Hamster logo and description.
Arguments
io_stream::IO: The output stream to which the text should be printed. Defaults tostdout.
Hamster.read_from_file — Method
read_from_file(filename, type)Read an Array M with elements of type from the file with name filename.
Hamster.split_line — Method
split_line(line::String) -> Vector{String}Splits a line of text into individual words, removing any extra spaces.
Arguments
line::String: A string representing the line of text to be split.
Returns
Vector{String}: An array of words from the input line, excluding any empty elements.
Hamster.split_lines — Method
split_lines(lines::Vector{String}) -> Vector{Vector{String}}Split each line of the input vector of strings into its constituent non-empty elements.
Arguments
lines::Vector{String}: A vector of strings, where each string represents a line to be split.
Returns
split_lines::Vector{Vector{String}}: A vector of vectors of strings, where each inner vector
contains the non-empty elements of the corresponding line from the input.
Hamster.write_to_file — Method
write_to_file(M, filename)Write the Array M and shape to a new file with name filename.
Hamster.read_hrdat — Function
read_hrdat(file::String)Read a Wannier90 hr.dat file and extract the Hamiltonian matrix elements, lattice vectors, and degeneracy values.
Arguments
file::String: The path to thehr.datfile.
Returns
- A tuple containing:
Hᴿ::Array{ComplexF64, 3}: The Hamiltonian matrix elements, a 3D array with dimensions (numwann, numwann, NR).Rs::Array{Float64, 2}: The lattice vectors, a 2D array with dimensions (3, NR).deg::Vector{Int64}: The degeneracy values, a vector of length NR.
Hamster.read_xdatcar — Function
read_xdatcar(xdatcar::AbstractString) -> XdatcarRead the configurations in the xdatcar file and store them in an Xdatcar object.
Arguments
xdatcar::AbstractString: The path to the XDATCAR file.frac::Bool=true: If false, coordinates are transformed to cartesian from fractional.verbosity::Int64=1: If greater 1, progress is printed.
Returns
lattice::Array{Float64, 3}: A 3x3 array representing the lattice vectors.configs::Array{Float64, 3}: A 3D array of shape (3, Nion, Nconfig), where each 3xNion slice represents the atomic positions in a configuration.
Main
Hamster.decide_which_task_to_perform — Method
decide_which_task_to_perform(conf::Config)Given a Config instance, decides which type of calculation is to be performed based on certain tags in the input file.
Details
- An
Optimizerwithout aHyperOptblock tells Hamster to run a parameter optimization. - An
Optimizerwith aHyperOptblock tells Hamster to run a hyperparameter optimization. - Otherwise, a standard calculation is performed.
Config
Hamster.ConfigBlock — Type
ConfigBlockA structure representing a block of configuration settings.
The ConfigBlock struct is used to encapsulate a segment of a configuration file, typically consisting of a header and associated content lines. The header usually indicates the section or category of the configuration, while the content contains key-value pairs or other relevant settings.
Fields:
header::Vector{String}: A vector of strings representing the header of the configuration block. This typically identifies the section or category the block belongs to.content::Vector{String}: A vector of strings representing the content of the configuration block. Each string usually corresponds to a line in the configuration file, often containing key-value pairs or other settings.
Hamster.filter_comment — Method
filter_comment(line::String)Removes comments from a line of text based on predefined comment symbols. The function scans for comment symbols, and if found, it removes the comment portion and returns the remaining part of the line.
Arguments:
line::String: The line of text from which comments need to be filtered out.
Returns:
- A
Stringthat contains the line without comments. If the entire line is a comment or becomes empty after removing the comment, an empty string is returned.
Hamster.get_config — Method
get_config(; filename="hconf")Retrieves the configuration from a file if it exists, or returns an empty configuration if the file does not exist.
Arguments
filename(optional): The name of the configuration file to check for existence. Defaults to"hconf".
Returns
Config: AConfiginstance.
Hamster.read_config — Method
read_config()Read the tbconfig file if given, else return default config.
Hamster.read_config_block! — Method
read_config_block!(block::ConfigBlock, conf::Config)Processes a configuration block and updates the configuration object with the parsed key-value pairs.
This function iterates over the lines in a ConfigBlock, parses each line to extract configuration options and their values, and updates the provided Config object. The function handles lines containing the = character, while ignoring comments and empty lines. The updates are made based on whether the block's header ends with "Options" or some other string.
Arguments:
block::ConfigBlock: An object representing a block of configuration lines, typically containing a header and a list of content lines.conf::Config: The configuration object that will be updated with the parsed key-value pairs from the block.
Hamster.read_config_line — Method
read_config_line(line::String) -> Tuple{String, String}Parses a configuration line into a key-value pair.
This function splits a configuration line at the first occurrence of the = character, separating the line into an option key and its corresponding value. Both the key and value are stripped of any leading or trailing whitespace.
Arguments:
line::String: A string representing a single line from a configuration file, typically in the form"key = value".
Returns:
- A tuple
(option_key, option_value)where:option_key::String: The configuration option key, stripped of leading and trailing whitespace.option_value::String: The configuration option value, also stripped of leading and trailing whitespace.
Hamster.split_blocks — Method
split_blocks(lines)Splits a list of lines into blocks of text based on "begin" and "end" markers. Each block is encapsulated in a ConfigBlock struct.
Arguments
lines: A list of strings, where each string is a line from the input text.
Returns
- A list of
ConfigBlockinstances, each containing the header and content of a block found in the input lines.
Hamster.Config — Type
(conf::Config)(key, typekey="none")Retrieve a value associated with a given key from conf. If a typekey is provided and exists in the blocks dictionary, it retrieves the value from the corresponding block. If no typekey is provided or it is set to "none", it retrieves the value from the options dictionary.
Arguments
conf::Config: TheConfiginstance to query.key: The key to look up in theConfiginstance.typekey(optional): The key for the block in theblocksdictionary to look up the value. Defaults to"none".
Returns
- The value associated with the
keyin theoptionsdictionary iftypekeyis"none"and the key exists. - The value associated with the
keyin the specified block of theblocksdictionary iftypekeyis provided and exists, and the key exists in that block. - The string "default" if the key does not exist in the relevant dictionary or block.
Hamster.Config — Type
struct ConfigA configuration structure that holds options and blocks of tags in dictionaries.
Fields
options::Dict{String, String}: A dictionary holding configuration options.blocks::Dict{String, Dict{String, String}}: A dictionary holding configuration blocks.
Hamster.Config — Type
(conf::Config)(keys::Vector{String}, typekey="none")Makes the Config instance callable with a vector of keys to retrieve corresponding values. If a typekey is provided and exists in the blocks dictionary, it retrieves the values from the corresponding block. If no typekey is provided or it is set to "none", it retrieves the values from the options dictionary.
Arguments
conf::Config: TheConfiginstance to query.keys::Vector{String}: A vector of keys to look up in theConfiginstance.typekey(optional): The key for the block in theblocksdictionary to look up the values. Defaults to"none".
Returns
- A vector of values corresponding to the provided keys.
- If
typekeyis"none"and the key exists in theoptionsdictionary, the value from theoptionsdictionary is returned. - If
typekeyis provided and exists in theblocksdictionary, and the key exists in that block, the value from the block is returned. - If the key does not exist in the relevant dictionary or block, the string "default" is returned for that key.
- If
Base.get — Method
Base.get(conf::Config, key, default::T) :: T where {T}
Base.get(conf::Config, key, typekey, default::T) :: T where {T}Retrieve a value associated with key (and typekey) from a configuration object conf. If the value returned by conf(key) is "default", the fallback value default is returned instead.
Arguments
conf::Config: A configuration object, typically implementing callable behavior for key lookups.key: The key to look up in the configuration. Its type depends on theConfigimplementation.default::T: A fallback value of typeTto return if the configuration value forkeyis"default".
Returns
::T: The value associated withkeyinconf, unless that value is"default", in which casedefaultis returned.
Base.haskey — Method
haskey(conf::Config, key)Checks if a given key exists in either the options or blocks dictionary of a Config instance.
Arguments
conf::Config: TheConfiginstance to check.key: The key to check for existence.
Returns
Bool:trueif the key exists in either theoptionsorblocksdictionary,falseotherwise.
Hamster.check_parse — Method
check_parse(type, line)Check if the string or vector of strings line can be converte to type.
Hamster.convert_value — Method
convert_value(value::String)Attempts to convert a string value into its most appropriate data type among Int64, Float64, and Bool. If the string represents a valid value for one of these types, it is parsed and returned as that type. If not, the original string is returned.
Arguments:
value::String: The string representation of a value to be converted.
Returns:
- The converted value in its most appropriate type (either
Int64,Float64, orBool), or the original string if it cannot be converted.
Behavior:
- The function splits the input
valuebased on spaces into components usingsplit_line(value, char=' '). - It then attempts to parse these components into
Int64,Float64, andBooltypes.
Hamster.get_Nconf — Method
**Nconf** = 1number of sample configuration.
Hamster.get_Nconf_max — Method
**Nconf_max** = 1minimum configuration index for sample.
Hamster.get_Nconf_min — Method
**Nconf_min** = 1minimum configuration index for sample.
Hamster.get_Rmax — Method
**Rmax** = 1maximum magnitude of translation vectors used for periodic boundaty conditions (default: determined by rcut).
Hamster.get_bandmin — Method
**bandmin** = 1lowest band index to include in optimization.
Hamster.get_barrier — Method
**barrier** = 0.0parameter magnitude where regularization kicks in.
Hamster.get_current_file — Method
**current_file** = ham.h5File where current operator is stored.
Hamster.get_diag_method — Method
**diag_method** = shift-invertsparse eigensolver when sp_diag=true (shift-invert, krylov-schur).
Hamster.get_eig_target — Method
**eig_target** = 0.0target energy when using sparse eigensolver.
Hamster.get_empty_config — Method
get_empty_config()Returns an empty Config instance.
Returns
Config: An emptyConfiginstance with emptyoptionsandblocksdictionaries.
Hamster.get_grid_size — Method
**grid_size** = get_rcut(conf)size of the grid to divide simulation cell.
Hamster.get_ham_file — Method
**ham_file** = ham.h5File where Hamiltonians are stored.
Hamster.get_hr_fit — Method
**hr_fit** = falseswitches to fitting the model to Hamiltonian data.
Hamster.get_hyperopt_lowerbounds — Method
**lowerbounds** = [0.0]lower bounds of the search space.
Hamster.get_hyperopt_mode — Method
**mode** = randomhyperparameter optimization strategy (random=random search, grid=grid search, tpe=tree-structured Parzen Estimator)
Hamster.get_hyperopt_niter — Method
**niter** = 1number of hyperparameter optimization steps.
Hamster.get_hyperopt_params — Method
**params** = String[]hyperparameters to be optimized as [BLOCK_]PARAM.
Hamster.get_hyperopt_stepsizes — Method
**stepsizes** = ones(length(get_hyperopt_params(conf))) * 1.0e-5minimum difference between two hyperparameter samples
Hamster.get_hyperopt_upperbounds — Method
**upperbounds** = [0.0]upper bounds of the search space.
Hamster.get_init_params — Method
**init_params** = onesTB parameter initialization (file, ones, zeros, rand).
Hamster.get_interpolate_rllm — Method
**interpolate_rllm** = trueforce interpolation of rllm.
Hamster.get_itp_Ninit — Method
**itp_Ninit** = 20number of initial interpolation points.
Hamster.get_itp_Nmax — Method
**itp_Nmax** = 300maximum number of interpolation points.
Hamster.get_itp_tol — Method
**itp_tol** = 1.0e-5convergence criterion for interpolation.
Hamster.get_itp_xmax — Method
**itp_xmax** = get_rcut(conf) + abs(get_rcut_tol(conf)) + 1maximum x value for interpolation.
Hamster.get_itp_xmin — Method
**itp_xmin** = 0.0minimum x value for interpolation.
Hamster.get_kpoints — Method
**kpoints** = gammafile/method for defining k-points (gamma, EIGENVAL, filename.h5).
Hamster.get_lambda — Method
**lambda** = 0.0regularization constant
Hamster.get_load_rllm — Method
**load_rllm** = falseread rllm data from a file.
Hamster.get_loss — Method
**loss** = MAEloss function for optimization (MAE, MSE).
Hamster.get_lr — Method
**lr** = 0.1learning rate for gradient descent.
Hamster.get_lr_min — Method
**lr_min** = get_lr(conf)final learning rate when using learning rate decay if lr≠lr_min.
Hamster.get_lreg — Method
**lreg** = 2norm for regularization (1=L1, 2=L2).
Hamster.get_ml_apply_distance_distortion — Method
**apply_distance_distortion** = falsewhether distortions (distance only) are considered in descriptor.
Hamster.get_ml_apply_distortion — Method
**apply_distortion** = falsewhether distortions are considered in descriptor.
Hamster.get_ml_apply_orthogonality — Method
**apply_orthogonality** = falseenforce orthogonality of atomic orbitals of different l, m (r=0)
Hamster.get_ml_env_scale — Method
**env_scale** = 1.0scaling factor for environment features.
Hamster.get_ml_filename — Method
**filename** = ml_paramsname of ML parameter file.
Hamster.get_ml_init_params — Method
**init_params** = zerosinitialization of ML parameters.
Hamster.get_ml_mode — Method
**mode** = ifelse(get_ml_update(conf), "refit", "eval")ml training mode (eval=evaluation, refit=retrain from scratch, expand=expand on existing)
Hamster.get_ml_model — Method
**model** = haskey(conf, "ML")whether ML model is used.
Hamster.get_ml_ncluster — Method
**ncluster** = 1number of cluster used in kmeans clustering.
Hamster.get_ml_npoints — Method
**npoints** = 1number of kernel support points.
Hamster.get_ml_rcut — Method
**rcut** = get_rcut(conf)ml cutoff radius. Defaults to same as TB.
Hamster.get_ml_sampling — Method
**sampling** = randomsampling method for each cluster of descriptors (random, farthest).
Hamster.get_ml_sim_params — Method
**sim_params** = 0.1similarity parameter for kernel model.
Hamster.get_ml_strc_scale — Method
**strc_scale** = 1.0scaling factor for structural features.
Hamster.get_ml_update — Method
**update** = decide_ml_update(conf)optimization of ML parameters
Hamster.get_nbatch — Method
**nbatch** = 1number of batches to split the data set.
Hamster.get_neig — Method
**neig** = 6number of eigenvalues when using sparse eigensolver.
Hamster.get_niter — Method
**niter** = 1number of gradient descent steps.
Hamster.get_onsite — Method
**onsite** = trueuse separate parameters for onsite matrix elements.
Hamster.get_poscar — Method
**poscar** = POSCARpath to POSCAR file to define base system.
Hamster.get_printeachbatch — Method
**printeachbatch** = get_verbosity(conf) > 1profiler prints after each batch.
Hamster.get_printeachiter — Method
**printeachiter** = 1iteration interval for profiler prints.
Hamster.get_rcut — Method
**rcut** = 7.0Distance beyond which all interactions are neglected.
Hamster.get_rcut_tol — Method
**rcut_tol** = 1.0offset (zero point) of the cutoff function w.r.t. rcut.
Hamster.get_save_vecs — Method
**save_vecs** = falseWhether eigenvectors are stored.
Hamster.get_sepNN — Method
**sepNN** = falseuse separate parameters for nearest-neighbor interactions. This can improve accuracy, however, may at the same time affect transferability negatively.
Hamster.get_skip_diag — Method
**skip_diag** = falseif true, no eigenvalues are computed.
Hamster.get_soc_update — Method
**update** = haskey(conf, "Optimizer") && haskey(conf, "SOC")soc parameters are updated.
Hamster.get_sp_tol — Method
**sp_tol** = 1.0e-10tolerance for value to be considered zero.
Hamster.get_system — Method
**system** = unknownname of the system
Hamster.get_tb_model — Method
**tb_model** = truebuild TB model.
Hamster.get_val_bandmin — Method
**val_bandmin** = get_bandmin(conf)lowest band index to include in validation set.
Hamster.get_val_ratio — Method
**val_ratio** = ifelse(get_validate(conf), 0.2, 0.0)ratio between training and validation set size.
Hamster.get_val_weights — Method
**val_weights** = falseif true, same weights are used for training and validation.
Hamster.get_valeachiter — Method
**valeachiter** = 1iteration interval for validation.
Hamster.get_verbosity — Method
**verbosity** = 1Controls output verbosity (0=minimal, 1=normal, 2=verbose, 3=debug).
Hamster.get_write_current — Method
**write_current** = falseWhether to write current operator.
Hamster.get_write_hk — Method
**write_hk** = falseWhether to write k-space Hamiltonians.
Hamster.get_write_hr — Method
**write_hr** = get_write_current(conf)Whether to write real-space Hamiltonians. Defaults to true if write_current=true.
Hamster.set_value! — Method
set_value!(conf::Config, key, typekey, value)Sets the value of a given key in the specified block of the blocks dictionary of a Config instance. If the block does not exist, it creates a new block with the given key-value pair. Keys are always stored in lowercase.
Arguments
key: The key to set in the specified block.typekey: The key for the block in which the key-value pair should be set.value: The value to set for the specified key.conf::Config: TheConfiginstance where the key-value pair should be set.
Hamster.set_value! — Method
set_value!(conf::Config, key, value)Sets the value of a given key in the options dictionary of a Config instance.
Arguments
key: The key for which the value needs to be set.value: The value to set for the specified key.conf::Config: TheConfiginstance where the key-value pair should be set.
Output
Hamster.append_output_block — Method
append_output_block(block_title, block_tags, block_values; filename="hamster.out")Append a formatted block of output to the specified file, typically used for logging or report generation.
Arguments
block_title::AbstractString: The title of the block to be appended. This title will be written as a header.block_tags::AbstractVector{<:AbstractString}: A vector of tags or labels corresponding to the block's values.block_values::AbstractVector{<:Any}: A vector of values corresponding to the tags, representing the content to be written.filename::AbstractString: The name of the file to which the block will be appended. Defaults to"hamster.out".
Usage
- This function checks if the specified file exists. If it does, it appends a titled block of information with tags and corresponding values.
- Each tag-value pair is written on a new line using the
write_output_linefunction. - A separator line is written after the block for clarity.
Hamster.append_output_line — Method
append_output_line(line; filename="hamster.out")Append a line to the output file hamster.out.
Hamster.clear_hamster_output — Method
clear_hamster_output(; output_files=["hamster_out.h5", "hamster.out", "Es.dat", "vs.dat"])Delete output files generated by Hamster.
Keyword Arguments
output_files::Vector{String}: List of filenames to remove. Defaults to["hamster_out.h5", "hamster.out", "Es.dat", "vs.dat"].
Hamster.generate_output — Function
generate_output(conf::Config)Generates the main output file hamster.out with initial run information.
Arguments
conf::Config: A configuration object containing parameters and settings for the current run.
Details
This function performs the following tasks:
- Opens (creates) the file
hamster.outfor writing. - Writes the current date and time to the file to record when the Hamster run started.
- Writes the list of unique hostnames.
Hamster.write_config_tags — Method
write_config_tags(filename::String, conf::Config; blocks=nothing, show_desc=false)Pretty print configuration tags to an output file in a nicely formatted style.
Arguments
filename: Path to the output file.conf: Configuration object to read current values.blocks: Optional list of block names to print. Ifnothing, all blocks are printed.show_desc: Iftrue, adds the description as a comment on each line.
Hamster.write_output_line — Method
write_output_line(dyntb_out, key, value, L)Write a line with key and value pair to the output file dyntb_out.
Hamster.write_separator — Method
write_separator(hamster_out)Write a separator line of L times charto theio_stream`.
Arguments
io_stream::IO: The io stream to which the separator will be written.