Basis

Hamster.AdaptiveInterpolatorType
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 of x in the interpolation range.
  • xmax::Float64: The maximum value of x in 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.
source
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 fields xs containing previous sample points.
  • xmax: The maximum possible value for x.
  • ymax: The maximum possible value of the function f over 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 is 10000).

Returns

  • xnew: A new sampled point xnew that is in a region with either high gradient or high curvature, and sufficiently far from existing points in f.xs.
source
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 of x values (assumed to be sorted in ascending order).
  • ys: A vector of y values corresponding to xs.
  • xnew: The new x value to insert into xs.
  • ynew: The new y value to insert into ys, corresponding to xnew.
source
Hamster.interpolate_fMethod
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 the AdaptiveInterpolator struct 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 of x values where the function has been evaluated.
  • ys: A vector of y values (f(xs)) corresponding to the x values.
source
Hamster.BasisType
Basis(strc::Structure, conf=get_empty_config()) -> Basis

Construct a Basis object from a given Structure and configuration.

Arguments

  • strc::Structure: The Structure object 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 to get_empty_config().

Returns

  • Basis: A Basis object.
source
Hamster.BasisType
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.
source
Base.lengthMethod
length(basis::Basis) -> Int

Compute the total number of orbitals in the basis.

Arguments

  • basis::Basis: The Basis object 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 the basis.
source
Base.sizeMethod
Base.size(basis::Basis) -> Tuple{Int}

Returns the size of the Basis object, which corresponds to the number of orbitals centered on each ion.

Arguments

  • basis::Basis: The basis object containing a set of orbitals.

Returns

  • A tuple containing the number of orbitals in the basis.
source
Hamster.get_bondsFunction
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 in strc.
  • 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 translation R, whose nonzero entries store Cartesian bond vectors as SVector{3,Float64}.
source
Hamster.get_geometry_tensorFunction
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.
source
Hamster.get_oc_and_mode_dictsMethod
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 a type field 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 by IonLabel) to their respective orbital configuration (SymOrb, DefOrb, or MirrOrb).
  • mode_dicts::Vector{Dict{IonLabel, Union{NormalMode, ConjugateMode}}}: A vector of dictionaries, each corresponding to one overlap configuration, mapping ion pairs (represented by IonLabel) to their respective mode type (NormalMode or ConjugateMode).
source
Hamster.get_param_indexMethod
get_param_index(overlap, nnlabel, parameters, orb1, orb2, i, j) :: Int64

Retrieve 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 as nnlabel, overlap_label, and ion_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 index v of the parameter in the parameters vector that matches the conditions. If no match is found, the function returns 0.
source
Hamster.nparamsMethod
nparams(basis::Basis) -> Int

Return the number of TB overlap parameters defined in basis.

Arguments

  • basis::Basis: The Basis object containing orbitals for each ion in the system.

Returns

  • Int: The total number of parameters.
source
Hamster.overlap_contributes_to_matrix_elementMethod
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: Returns true if the overlap contributes to the matrix element, i.e., if the orbital types of orb1 and orb2 match the types in the overlap, and the ion_label matches.
source
Hamster.reshape_geometry_tensorMethod
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 NR matrix h_out where each element is a sparse matrix (SparseMatrixCSC{Float64, Int64}) formed by the corresponding indices and values from the input dictionary h_dict.
source
Hamster.get_index_to_ion_orb_mapMethod
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 to i.
source
Hamster.get_ion_and_orbital_indicesMethod
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 given index.
  • jorb: The index of the orbital for the ion iion corresponding to index.
  • If index is out of bounds, returns (0, 0) as a fallback.
source
Hamster.get_ion_orb_to_index_mapMethod
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 index i_ion and the orbital index i_orb. The value corresponding to each key is the basis state index i.
source
Hamster.IonLabelType
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 two Int64 values representing the types or identifiers associated with the ion. The use of SVector{2, Int64} ensures that the two types are stored efficiently as a fixed-size array.

Constructors

  • IonLabel(type1::Int64, type2::Int64; sorted=true): Creates an IonLabel from two integer types. If sorted=true, the types will be sorted before creating the label, ensuring consistent ordering.
  • IonLabel(type1::String, type2::String; sorted=true): Creates an IonLabel from two element symbols (as Strings). Converts the symbols to atomic numbers and optionally sorts them if sorted=true.
source
Base.isequalMethod
Base.isequal(ion_label1::IonLabel, ion_label2::IonLabel; sorted=false) -> Bool

Compares two IonLabel objects for equality.

Arguments

  • ion_label1::IonLabel: The first IonLabel instance to compare.
  • ion_label2::IonLabel: The second IonLabel instance to compare.
  • sorted::Bool=false: Whether to sort the types fields of both IonLabel instances before comparing them. Defaults to false.

Returns

  • Bool: Returns true if the IonLabel instances are considered equal based on their types fields (with or without sorting), and false otherwise.
source
Base.stringMethod
string(ion_label::IonLabel) -> String

Converts an IonLabel object into a human-readable string representation, where the types are converted into their corresponding element symbols.

Arguments

  • ion_label::IonLabel: The IonLabel instance containing two atomic types represented as atomic numbers.

Returns

  • String: A string representation of the IonLabel, where the two element numbers are converted to their respective element symbols and concatenated with a + sign.
source
Hamster.aresameionsMethod
sameions(ion_label::IonLabel) -> Bool

Checks if both ions in the given IonLabel are of the same type.

Arguments

  • ion_label::IonLabel: The IonLabel object that contains two ion types represented as atomic numbers.

Returns

  • Bool: Returns true if both ions in the IonLabel have the same atomic number, meaning they are the same type of ion; otherwise, returns false.
source
Hamster.areswappedMethod
areswapped(type1, type2) -> Bool

Determines 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: true if the order of type1 and type2 is swapped in the sorted IonLabel, false otherwise.
source
Hamster.get_nn_labelFunction
get_nn_label(r, r_thresh, onsite, sepNN) :: Int64

Returns 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., when r ≈ 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.
source
Hamster.string_to_overlap_labelMethod
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, l1 and l2 will 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, l1 and l2 are 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").
    • m is set to 0 for diagonal and 1 for off-diagonal onsite interactions to differentiate between them.
  • If the string does not contain "diag", it represents an offsite overlap, and l1, l2, and m are determined using lookup tables (ldict_inv and mdict_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).
source
Hamster.DefOrbType
DefOrb()

No symmetry in orbitals: orbital type in label has to be used in the same order as given.

source
Hamster.MirrOrbType
MirrOrb()

No symmetry in orbitals: orbital type in label has to be used in reverse order as given.

source
Hamster.OrbitalConfigurationType
OrbitalConfiguration

Abstract 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.
source
Hamster.OrbitalConfigurationMethod
OrbitalConfiguration(Y1, Y2, Ys1, Ys2; sameions=true, ionswap=false) -> OrbitalConfiguration

Determine 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 an l property for angular momentum).
  • Y2: The second orbital (expected to have an l property 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, DefOrb or MirrOrb.
source
Hamster.SymOrbType
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.
source
Hamster.get_modeMethod
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 maps IonLabels 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 in mode_dicts to 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 given ion_label, after potentially checking for a conjugate mode using check_for_conjugate_mode.
source
Hamster.get_orbconfigMethod
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 maps IonLabels 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 in oc_dicts to 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 using check_for_conjugate_orbconfig.
source
Hamster.OrbitalType
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 by O, 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.
source
Hamster.get_axesFunction
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: A Structure object 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 is get_empty_config().
  • NNaxes: A Boolean flag that determines whether to compute nearest-neighbor axes (true) or directly use predefined orbital axes (false).
source
Hamster.get_axes_from_orbitalsMethod
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 of Orbital.
source
Hamster.get_axisMethod
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 of sp3 (or sp3dr2) hybrid orbitals: [1, 1, 1], [1, -1, -1], [-1, 1, -1], [-1, -1, 1].
  • o::s: Returns the axis [0, 0, 1] for an s orbital.
  • o::px: Returns the axis [1, 0, 0] for a px orbital.
  • o::py: Returns the axis [0, 1, 0] for a py orbital.
  • o::pz: Returns the axis [0, 0, 1] for a pz orbital.
  • o::pxdx2: Returns the axis [1, 0, 0] for a combined px/dx² orbital.
  • o::pydy2: Returns the axis [0, 1, 0] for a combined py/dy² orbital.
  • o::pzdz2: Returns the axis [0, 0, 1] for a combined pz/dz² orbital.
source
Hamster.get_orbitalsFunction
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 to get_empty_config() if no configuration is provided.

Returns

  • orbitals::Vector{Orbital}: A vector of Orbital objects, 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 Orbital objects in a vector.
source
Hamster.TBOverlapType
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, where T is a subtype of MatrixElement. This field indicates the specific kind of matrix element or overlap parameter.
  • orbconfig::OC: Represents the OrbitalConfiguration associated with the TB overlap parameter.
  • ion_label::IonLabel: Labels the ions that are involved in the interaction term.
source
Hamster.VddδType
Vddδ

Overlap parameter for overlaps between two d-orbitals with |m|=2.

source
Hamster.VddπType
Vddπ

Overlap parameter for overlaps between two d-orbitals with |m|=1.

source
Hamster.VddσType
Vddσ

Overlap parameter for overlaps between an s- and a d-orbital with |m|=0.

source
Base.isequalMethod
Base.isequal(ov1::TBOverlap, ov2::TBOverlap)

Compare two TBOverlap objects, ov1 and ov2, for equality.

Arguments

  • ov1::TBOverlap: The first TBOverlap instance.
  • ov2::TBOverlap: The second TBOverlap instance.

Returns

  • Bool: true if the two TBOverlap instances are considered equal, false otherwise.
source
Base.stringMethod
Base.string(p::TBOverlap; apply_oc=false)::String

Converts 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: The TBOverlap instance to be converted into a string.
  • apply_oc::Bool: A flag indicating whether to apply orbital configuration-specific formatting.
source
Hamster.NConstMethod
NConst(baseorb, l₁, l₂)

Determine the normalization constant for the matrix element between orbitals in baseorb with respective components l₁ and l₂.

source
Hamster.decide_orbconfigMethod
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.

source
Hamster.get_baseorb_lsMethod
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: A TBOverlap object representing the overlap between two orbitals in a tight-binding model. The baseorb field contains information about the two orbitals.

Returns

  • A tuple (l1, l2) where l1 is the angular momentum quantum number of the first orbital and l2 is that of the second orbital.
source
Hamster.get_overlapsFunction
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 in ions.
  • conf: Optional configuration parameter (default: get_empty_config()).

Returns

  • Vector{TBOverlap}: A vector containing all computed TBOverlap instances for the ion and orbital pairs.
source
Hamster.get_overlaps_for_orbitalsMethod
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: An IonLabel instance 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 of TBOverlap instances describing the possible overlaps between the orbitals of the two ions, taking into account symmetry and ion swaps.
source
Hamster.me_to_overlap_labelMethod
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.

source
Hamster.same_ion_labelMethod
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.

source
Hamster.ParameterLabelType
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: An IonLabel object 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 of ll'm.
source
Base.stringMethod
string(param_label::ParameterLabel) -> String

Returns 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: The ParameterLabel object 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 nnlabel value:
    • For nnlabel ≠ 0: The overlap string is constructed from ldict and mdict dictionaries using the first two elements of overlap_label.
    • For nnlabel == 0:
      • If overlap_label[3] == 0: The overlap string is "diag" followed by the angular momentum index l.
      • Otherwise, the overlap string is "offdiag" followed by two angular momentum indices l1 and l2.

Returns

  • A concatenated string in the form, e.g., NN1_Ga+As_ssσ.
source
Hamster.check_consistencyMethod
check_consistency(conf_values, conf::Config) -> Bool

Checks 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 _alpha values).
  • conf::Config: A Config object containing the expected values for comparison.

Returns

  • Bool: Returns true if all values in conf_values are consistent with the values in conf, otherwise returns false.
source
Hamster.get_ion_types_from_parametersMethod
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 an ion_label.

Returns

  • A vector of unique ion types (as strings) extracted from the ion_label field of the parameters.
source
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 of TBOverlap objects representing the overlap between orbitals. The function filters those with the same ion type for onsite interactions.
source
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 of TBOverlap objects 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).
source
Hamster.get_parameters_from_overlapsFunction
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 from conf) indicating whether second-nearest-neighbor interactions should be included (true if included, false otherwise).
  • onsite::Bool: A keyword argument (default from conf) indicating whether onsite parameters should be included (true if included, false otherwise).

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).
source
Hamster.read_paramsFunction
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 the ion_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.
source
Hamster.same_param_labelMethod
same_param_label(nnlabel::Int64, ion_label::IonLabel, overlap_label::SVector{3, Int64}, param_label::ParameterLabel) -> Bool

Check 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 the nnlabel in param_label.
  • ion_label::IonLabel: The ion label to compare with the ion_label in param_label.
  • overlap_label::SVector{3, Int64}: The overlap label to compare with the overlap_label in param_label.
  • param_label::ParameterLabel: The parameter label to compare against.

Returns

  • Bool: Returns true if all components (nnlabel, ion_label, overlap_label) match those of the given param_label, otherwise returns false.
source
Hamster.write_paramsFunction
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 the parameters.
  • 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:

  1. System configuration block: Includes details like rcut, onsite, sepNN, and alpha/n values for each unique ion type.
  2. Tight-binding parameters: Parameters and corresponding values, formatted to align in a readable manner.
  3. SOC parameters (optional): SOC values for each ion type, if provided.
source
Hamster.distance_dependenceMethod
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 numbers n for the two orbitals.
  • αs: A vector containing the exponential decay factors α for the two orbitals.

Returns

  • The integral I of the overlap function between the two orbitals over the given distance r, modified by a sign factor if necessary.
source
Hamster.fcutMethod
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) = 0 for r > rcut.
source
Hamster.get_rllm_from_fileFunction
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 to nothing.
  • load_rllm::Bool: (Keyword argument) If true, load the RLLM data from a file. The file location is provided by rllm_file. Defaults to the value from conf.
  • rllm_file::String: (Keyword argument) Filename for loading or saving the RLLM data. Defaults to the value from conf.
  • interpolate_rllm::Bool: (Keyword argument) If true, interpolate new RLLM data based on the overlaps and save it to a file. Defaults to the value from conf.
  • 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. If load_rllm is true, the data is read from the file. If interpolate_rllm is true, it is interpolated and saved.
source
Hamster.interpolate_overlapMethod
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 as n and α for each ion type involved in the overlap.
source
Hamster.precalc_rllmFunction
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 of Basis objects 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.
source
Hamster.read_rllmMethod
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.
source
Hamster.save_rllmMethod
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 an rllm field with xs (x values) and ys (y values).
  • comm: The MPI communicator.
  • filename::String: The name of the file where the Rllm data will be saved. Defaults to "rllm.dat".
source
Hamster.get_base_orbMethod
baseorb logic

The baseorb of px, py, pz should be the same since since one can transform one into the other by rotation.

source
Hamster.OrbitalFunctionType
(orb::OrbitalFunction)(r⃗)

Evaluate the orbital orb at the point r⃗, which can be one- or two-dimensional or a tuple including the norm.

source
Hamster.OverlapType
Overlap(Ψ₁, r⃗₁, Ψ₂, r⃗₂)

Struct to calculate the overlap integral between two wavefunctions with centers r⃗₁ and r⃗₂.

source
Hamster.get_sphericalMethod
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 = 0 for s, l = 1 for p, l = 2 for d, etc.).
  • m::Int: The magnetic quantum number, which ranges from -l to l.

Returns

  • The corresponding spherical harmonic function as a vector, based on the values of l and m.
source
Hamster.str_to_orbMethod
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.
source

Structure

Hamster.PointGridType
PointGrid(rs_ion, Ts, conf::TBConfig) -> PointGrid

Constructs 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 the PointGrid, such as the grid size.

Returns:

  • PointGrid: A PointGrid object that partitions the real-space simulation cell into a grid and maps atomic positions to these grid cells.
source
Hamster.PointGridType
PointGrid

A 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.
source
Hamster.get_grid_dictMethod
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 vectors SVector{3, Int64}), and the values are vectors of tuples (iion, R), where iion is the index of the ion and R is the index of the translation vector.
source
Hamster.get_grid_dictMethod
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 vectors SVector{3, Int64}), and the values are vectors of ion indices corresponding to the ions located at that grid point.
source
Hamster.get_grid_pointMethod
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 an SVector{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 position r⃗ belongs to.

Returns

  • An SVector{3, Int64} representing the grid point. The grid point is computed by dividing each component of r⃗ by grid_size, flooring the result to obtain the integer grid coordinates.
source
Hamster.iterate_nn_grid_pointsMethod
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: A PointGrid object 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.
source
Hamster.iterate_nn_grid_pointsMethod
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: A PointGrid object 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.
source
Hamster.nn_grid_pointsMethod
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: An SVector{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 of SVector{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 specified grid_point that are present in the grid_dict.
source
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 the grid_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.

source
Hamster.IonType
Ion

A 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.
source
Hamster.findnext_ion_of_typeMethod
findnext_ion_of_type(type, ions::Vector{Ion}) -> Int64

Find 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 of Ion objects, where each Ion has a type field that specifies its ion type.

Returns:

  • The index iion of the first ion in ions whose type matches the input type.
  • If no ion with the specified type is found, the function returns 0.
source
Hamster.get_ion_positionsMethod
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 of Ion objects, where each Ion contains information about its type, position, and distortion.

Returns

  • Vector{SVector{3, Float64}}: A vector of SVector{3, Float64} where each element represents the 3D Cartesian coordinates of an ion.
source
Hamster.get_ion_typesMethod
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 of Ion instances, each containing information about an ion's type, position, and distortion.
  • uniq::Bool=false: If true, the returned array contains only unique ion types.
  • sorted::Bool=false: If true, 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 vector ions. If uniq is set to true, only unique types will be included. If sorted is set to true, the types will be sorted alphabetically.
source
Hamster.get_ionsFunction
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 of positions.
  • 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 of Ion instances, each containing the type, position, and distortion of an ion.
source
Hamster.findR0Method
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 in Rs that contains the vector [0, 0, 0]. If the vector [0, 0, 0] is not found, returns 0.
source
Hamster.get_RmaxFunction
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 to get_empty_config().
  • rcut: (Optional) The cutoff radius used to determine the maximum radius. Defaults to get_rcut(conf).
  • Rmax: (Optional) Initial guess for the maximum radius. Defaults to get_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 radius Rmax contains all points within the cutoff radius rcut.
source
Hamster.get_translation_vectorsFunction
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 like Rmax and rcut. 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 the rcut value to include only those within the specified interatomic distance.
source
Hamster.get_translation_vectorsMethod
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 -M to M.

Returns

  • Rs::Matrix{Float64}: A 3xN matrix where N is the total number of translation vectors. Each column of Rs represents a translation vector with components within the specified magnitude range.
source
Hamster.get_nearest_neighborsMethod
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 in rs to account for periodic boundary conditions.
  • point_grid::PointGrid: A PointGrid structure 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 the kNN nearest neighbors to r0.

Description

This function computes the nearest neighbors of a point r0 by:

  1. Locating the grid point corresponding to r0 in the point_grid.
  2. Iterating over the neighboring grid points to compute distances to all potential neighbor points in rs shifted by translation vectors in Ts.
  3. Sorting these distances to identify the kNN closest neighbors.
  4. Returning the positions of these nearest neighbors in a matrix.
source
Hamster.get_nn_thresholdsFunction
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 is get_empty_config().
  • sepNN: A Boolean flag (optional). If true, separate NN thresholds are calculated for each ion pair. If false, all ion pairs are treated uniformly. Default is get_sepNN(conf).

Keyword Arguments

  • sepNN: Whether to compute separate NN distances for different ion pairs. Default is get_sepNN(conf).

Returns

  • NN_dict::Dict{IonLabel, Float64}: A dictionary where each key is an IonLabel representing a pair of ion types, and the value is the minimum nearest-neighbor distance for that pair.
source
Hamster.get_sk_transform_matrixMethod
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 between r⃗₁ and r⃗₂.
source
Hamster.get_transformed_systemMethod
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 version get_transformed_system(r⃗₁, r⃗₂) to handle the ambiguity in the x-axis.
source
Hamster.rotation_matrix_around_axisMethod
rotation_matrix_around_axis(u⃗::AbstractVector{T}, θ::T) where T

Constructs 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) where T is a numeric type.
  • θ::T: The angle of rotation (in radians) around the axis u⃗.

Returns

  • A 3x3 static matrix representing the rotation around the axis u⃗ by angle θ.
source
Hamster.StructureType
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: A Config instance 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 the PointGrid for efficient neighbor searching.

Returns

  • Structure: A Structure instance.
source
Hamster.StructureType
Structure

A 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. Each Ion includes 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.
source
Hamster.StructureMethod
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 from rs_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) A Config instance.
  • rcut: The cutoff radius for interactions to be taken into account.
  • grid_size: The size of the grid used in the PointGrid for efficient neighbor searching.

Returns

  • Structure: A Structure instance.
source
Hamster.get_config_index_sampleFunction
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 from conf if not specified.
  • Nconf_min: (Optional) The minimum configuration index. Derived from conf if not specified.
  • Nconf_max: (Optional) The maximum configuration index. Derived from conf if not specified.
  • validate: (Optional) Boolean flag indicating whether validation should be performed. Derived from conf if not specified.
  • val_ratio: (Optional) Ratio of validation configurations to training configurations. Used only if train_mode == val_mode.
  • train_mode: (Optional) Mode identifier for training configurations. Derived from conf.
  • val_mode: (Optional) Mode identifier for validation configurations. Derived from conf.

Returns

  • train_config_inds: A vector of indices for training configurations.
  • val_config_inds: A vector of indices for validation configurations.
source
Hamster.get_config_inds_for_systemsFunction
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.
source
Hamster.get_number_of_bands_per_structureMethod
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: A Dict{String, Vector{Int}} containing atomic configuration indices.
  • soc (keyword, default = false): If true, doubles the band count per to account for SOC.

Returns

  • Dict{String, Int}: A dictionary mapping each system name to its number of bands.
source
Hamster.get_structuresFunction
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 using get_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 of Structure objects. Each structure represents the ion positions and their displacements relative to the initial configuration.
source
Hamster.get_systemsMethod
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).
source
Hamster.read_structure_fileFunction
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 to get_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 .h5 file containing configurations.

Returns

A tuple containing:

  1. rs_atom::Matrix{Float64} — Cartesian positions of atoms in the reference structure.
  2. atom_types::Vector{String} — Atomic species labels.
  3. lattice::Matrix{Float64} — Lattice vectors (3×3 matrix).
  4. configs::Array{Float64,3} — Atomic positions for all configurations (shape: 3 × N_atoms × N_configs).
source
Hamster.split_indices_into_chunksMethod
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 to 0.

Returns

  • AbstractVector: The chunk of indices corresponding to the specified rank. If the rank exceeds the number of chunks, an empty array of type Int64[] is returned.
source
Hamster.calc_angleMethod
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 matches v2).
  • v2: Second vector (same dimensionality as v1).
  • ϵ: 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 v1 and v2, calculated using the dot product. If either vector's norm is less than ϵ, the function returns 0..
source
Hamster.get_rotated_anglesMethod
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 vector r⃗.
  • r⃗::AbstractVector{T}: A 3D vector to be rotated, where T is 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.
source
Hamster.normdiffMethod
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 vectors v and w.
source
Hamster.projMethod
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 onto u⃗.

Returns

  • AbstractVector: The projection of v⃗ onto u⃗.
source
Hamster.transform_basisMethod
transform_basis(r⃗::AbstractVector, Ê::AbstractMatrix) -> AbstractVector

Transforms 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 vector r⃗.

Returns:

  • AbstractVector: The transformed vector in the new basis, obtained by multiplying with r⃗.
source
Hamster.transform_to_sphericalMethod
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.
source
Hamster.transform_to_sphericalMethod
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, θ, φ).
source

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.
source
Hamster.get_hamiltonianMethod
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.
source
Hamster.get_hrMethod
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 the ham.models tuple.
source
Hamster.get_sparse_iteratorFunction
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 by R) and contains tuples (i, j) representing the sparse matrix indices for interactions within the cutoff radius.
source
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 ham object in place, updating the parameters of each model it contains.
source
Hamster.write_paramsFunction
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_ham and calls write_params(model) for each.
source
Hamster.apply_spin_basisMethod
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. If true, the order is, e.g., up,down,up,down. If false, the order is, e.g., up,up,down,down.

Returns:

  • A matrix in the spin basis in the specified order.
source
Hamster.diagonalizeMethod
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 of Hk. 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 of Hk. The eigenvectors are computed in the standard basis and are complex-valued.
source
Hamster.diagonalizeMethod
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 to 6, 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 to 0.
  • 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 to Neig.
  • eigenvectors::Matrix{ComplexF64}: A matrix where each column is an eigenvector corresponding to one of the computed eigenvalues.
source
Hamster.diagonalizeMethod
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 momentum k in 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 column Es[:, k] contains the Neig eigenvalues of the k-th Hamiltonian matrix in Hk.
  • vs::Array{ComplexF64, 3}: A 3D array where each vs[:, :, k] contains the Neig eigenvectors corresponding to the k-th Hamiltonian matrix in Hk. The dimensions of vs are (Nε, Neig, Nk), where is the size of each Hamiltonian matrix, Neig is the number of eigenvectors, and Nk is the number of Hamiltonian matrices.
source
Hamster.get_hamiltonianFunction
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 with Rs to compute phase factors.
  • mode::Dense(): Indicates whether to construct a sparse or dense Hamiltonian. Defaults to Dense.
  • 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 in Rs. These are the degeneracies for the Wannier90 Hamiltonians.

Returns:

  • A vector of Hamiltonian matrices Hk, where each matrix is constructed by combining Hr with phase factors and optionally transformed into a spin basis.
source
Hamster.get_sparsityMethod
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 than sp_tol in magnitude are considered zero.

Returns:

  • sparsity::Float64: The fraction of elements in H that are considered zero according to the specified tolerance. This value lies between 0.0 (no zero elements) and 1.0 (all elements are effectively zero).
source
Hamster.get_sparsityMethod
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 of H should 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 than sp_tol in magnitude are considered zero.

Returns:

  • sparsity::Float64: The fraction of elements across all arrays in H that are considered zero according to the specified tolerance. This value lies between 0.0 (no zero elements) and 1.0 (all elements are effectively zero).
source
Hamster.gradient_apply_spin_basisMethod
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. If false, the function applies the transformation as kron(H, I_spin). If true, it applies the transformation as kron(I_spin, H).
source
Hamster.reshape_and_sparsify_eigenvectorsMethod
reshape_and_sparsify_eigenvectors(vs, mode::SparsityMode; sp_tol=1e-10) -> Matrix

Reshapes 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:

  • n represents the size of each eigenvector.
  • m and k represent the number of eigenvector groups along two axes.

Arguments

  • vs::Array: A 3D array of eigenvectors, where vs[:, 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 when Sparse mode is selected. Defaults to 1e-10.

Returns

  • Matrix{Vector{ComplexF64}} if mode is Dense: A 2D matrix of dense vectors corresponding to eigenvectors in vs.
  • Matrix{SparseVector{ComplexF64, Int64}} if mode is Sparse: A 2D matrix of sparse vectors, where elements smaller than sp_tol are removed.
source
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 than tol are removed from the sparse matrices.
source
Hamster.chain_ruleMethod
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), where m is the eigenvalue index and k is 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), where R is 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 in R. Its shape is determined by the Hamiltonian structure and mode.
source
Hamster.get_eigenvalue_gradientFunction
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: Either Dense or Sparse, determines whether the gradients are sparsified.
  • sp_iterator: Special iterator to optimize iteration over i, j, R for very sparse systems.

Returns

  • dE_dHr: An array of shape (NR, Nε, Nk) that contains (sparse) matrices of shape (Nε, Nε).
source
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.

source
Hamster.read_currentFunction
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.
source
Hamster.read_hamFunction
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.
source
Hamster.read_hrFunction
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: If true, enables sparse matrix storage mode for the Hamiltonians. This is useful for large, sparse Hamiltonians to save memory.
  • verbose::Int64: Sets the verbosity. verbose=0 deactivates print statements.

Returns:

  • Hr: A vector of 2D arrays where each element Hr[R] is a Hamiltonian matrix corresponding to the lattice vector Rs[:, R]. Each Hr[R] is a 2D array of size (Nε, Nε), where is the size of the Hamiltonian matrices.
  • Rs: A 2D array where each column is a lattice vector corresponding to the Hamiltonians in Hr. 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 ().
  • 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_mode is true, the Hamiltonians are stored in a sparse format. Otherwise, a dense format is used.
source
Hamster.write_currentFunction
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, with SVector{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.
source
Hamster.write_hamFunction
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" if ind == 0
  • "H${space}_$ind" otherwise

Inside this group:

  • "vecs": dataset containing the supplied vecs (k or R vectors).
  • Subgroups "1", "2", …, one for each block in H, containing:
    • "rowval", "colptr", "nzval": the CSC representation of the sparse matrix.
    • "m", "n": matrix dimensions.
source
Hamster.write_hrMethod
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 each Hr[R] contains the Hamiltonian elements corresponding to the lattice vector Rs[:, R].
  • Rs: A 2D array where each column is a lattice vector corresponding to the Hamiltonian elements in Hr. 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 .dat to 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=0 deactivates 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 ().
  • The second line contains the number of lattice vectors (NR).
  • The function writes only the non-zero elements of Hr (as determined by tol) 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.
source
Hamster.TBModelType
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 to get_update_tb(conf).
  • initas: (Optional) Initialization parameters for the model. Defaults to get_init_params(conf).

Returns

  • A TBModel object with the geometry tensor h and the model's parameters set via init_params!.
source
Hamster.TBModelType
TBModel

A 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 parameters V should be updated during optimization or kept fixed.
source
Hamster.get_hrFunction
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 element h[v, R] represents a Hamiltonian block associated with parameter v and lattice vector R.
  • V: A vector of parameters.
  • mode: Optional argument that specifies the format of the resulting Hamiltonian (Hr). Defaults to Val{: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 vector R.
source
Hamster.get_model_gradientMethod
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 parameters V and the geometry tensor h.
  • 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.
source
Hamster.get_model_gradientMethod
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 the ham.models, computed using the provided indices, regularization term, and loss derivative.
source
Hamster.get_paramsMethod
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 params field of the given TBModel instance.
source
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 array V will 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, random or a file).

Keyword Arguments

  • conf: Configuration settings.
  • initas: The initialization method or file path for parameters. Defaults to ones.
source
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's params field.

Error Conditions

  • Throws an error if the parameter vector params is not of the correct size.

Returns

  • Updates the params field of the model in place if the consistency checks pass.
source
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: A TBModel object 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.
source
Hamster.write_paramsFunction
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.
source

SOC

Hamster.MtransConstant
  • Mtrans: Dictionary mapping the type of orbital ("s", "p", "d") to its corresponding transformation matrix (Ms, Mp, Md).
source
Hamster.gen_permutation_matrixMethod
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 P that reorders initial_order to desired_order.
source
Hamster.get_Msoc_dFunction
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 d orbitals, ordered according to output_basis_order.
source
Hamster.get_Msoc_hoMethod
get_Msoc_ho(axes; mode="sp3dr2") -> BlockDiagonal

Calculate 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.
source
Hamster.get_Msoc_pFunction
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.
source
Hamster.get_Msoc_sFunction
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_s for s orbitals.
source
Hamster.get_hybrid_coefficient_matrixMethod
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.
source
Hamster.get_soc_matricesFunction
get_soc_matrices(strc::Structure) -> Vector{BlockDiagonal}

Precompute the spin-orbit coupling (SOC) matrices for a given structure.

source
Hamster.get_sp3_expansion_coefficientsMethod
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.
source
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 into dict1.

Returns

  • dict1::Dict: The updated dictionary containing all keys from both.
source
Hamster.trans_lm_spatialMethod
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.
source
Hamster.SOCModelType
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.
source
Hamster.get_hrMethod
get_hr(soc_model::SOCModel, sp_mode, index; apply_soc=true) -> BlockDiagonal

Constructs 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): If true, applies SOC-related modifications (not explicitly used in this function).

Returns

  • A BlockDiagonal matrix where each block corresponds to an ion type, with parameters expanded and applied to SOC matrices.
source
Hamster.get_model_gradientMethod
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.
source
Hamster.get_paramsMethod
get_params(soc_model::SOCModel) -> Vector

Retrieves 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.
source
Hamster.init_soc_paramsFunction
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 to get_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.
source
Hamster.set_params!Method
set_params!(soc_model::SOCModel, params) -> Nothing

Updates 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.
source
Hamster.update!Method
update!(soc_model::SOCModel, opt, dparams) -> Nothing

Updates 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).
source
Hamster.write_paramsFunction
write_params(soc_model::SOCModel, conf=get_empty_config()) -> Nothing

Writes 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 from get_empty_config()).
source
Hamster.convert_block_matrix_to_sparseMethod
convert_block_matrix_to_sparse(M::BlockDiagonal; sp_tol=1e-10) -> SparseMatrixCSC

Converts 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 from BlockDiagonals.jl or similar libraries.
source
Hamster.get_lms_basisMethod
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].
source
Hamster.get_matrix_lmbasisMethod
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.
source
Hamster.mapLmSpMethod
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].
source
Hamster.mapLpSmMethod
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].
source
Hamster.mapLzSzMethod
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].
source
Hamster.separate_spin_secsMethod
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.

source
Hamster.thresholdingFunction
thresholding(c::Complex, real_threshold::Real=1e-15) -> Complex

Apply 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.
source

ML

Hamster.decide_orbswapMethod
decide_orbswap(itype, jtype, l_i, m_i, l_j, m_j) -> Bool

Determines 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:

  1. Comparing element types using a periodic table-based numerical ordering (element_to_number).
  2. If element types are the same, comparing orbital angular momentum quantum numbers (l_i, l_j).
  3. If l values 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

  • true if the orbitals should be swapped to maintain ordering; false otherwise.
source
Hamster.decide_orthogonalMethod
decide_orthogonal(Δr, i, j, l_i, l_j; apply_orthogonality=false) -> Bool

Determine 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 : true if the orbitals are considered orthogonal, false otherwise.
source
Hamster.farthest_point_samplingMethod
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 in descriptors that 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 of cluster_indices) representing a diverse subset.
source
Hamster.get_angular_descriptorsMethod
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 Δrij and Δrji depending 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 θs based on atomic types and orbital swapping rules.
source
Hamster.get_environmental_descriptorMethod
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: If true, uses V as given; otherwise, is set to ones.
  • rcut: Cut-off radius for interactions, defaults to get_ml_rcut(conf).

Returns

  • env: A vector representing the environmental descriptor.
source
Hamster.get_tb_descriptorMethod
get_tb_descriptor(model, strc, conf)

Calculate the TB descriptor for a given a TB model, a structure strc and a TBConfig file conf.

source
Hamster.reshape_structure_descriptorsMethod
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.
source
Hamster.sample_structure_descriptorsMethod
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 Npoints columns.
source
Hamster.HamiltonianKernelType
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 of Structure objects.
  • bases: Vector of Basis objects 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, and nranks are 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_params configuration.
source
Hamster.HamiltonianKernelType
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.
source
Hamster.get_hrMethod
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: If true, applies the spin-orbit coupling (SOC) basis transformation.

Returns

  • A vector of real-space Hamiltonian matrices, optionally modified with SOC transformations.
source
Hamster.get_model_gradientMethod
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.
source
Hamster.get_paramsMethod
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 ws field of the given HamiltonianKernel instance.
source
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 (initas is interpreted as the filename in eval mode).
  • filename: A string specifying the file from which old parameters can be loaded when mode="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 from filename and append new parameters initialized according to initas.
  • 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.
source
Hamster.read_ml_paramsFunction
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 .dat file to read from (default: get_ml_filename(conf)).
source
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 ws is not of the correct size.

Returns

  • Updates the Vs field of the kernel in place if the consistency checks pass.
source
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.
source
Hamster.write_paramsFunction
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)).
source

Optimization

Hamster.AdamType
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))
source
Hamster.DataLoaderType
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 type A represents the data type of the training set.
  • val_data::Vector{B}: A vector containing the validation dataset. The type B represents the data type of the validation set.
source
Hamster.EigDataType
EigData

A 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.
source
Hamster.HrDataType
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 matrices Hr, where each entry corresponds to a lattice translation vector in Rs. Each element in this vector is a Hamiltonian matrix, with M representing the matrix type (e.g., dense or sparse).
source
Hamster.get_neig_and_nkMethod
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 either EigData or HrData.

Returns

  • (Neig, Nk): The number of eigenvalues and k-points of the first data point. Return 0 for HrData.
source
Hamster.get_translation_vectors_for_hr_fitFunction
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()): A Config instance.
  • 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 not hr_fit, return zeros (Rs are calculated depending on rcut).
source
Hamster.GDOptimizerType
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. If Nε == 0, a default configuration is used.
  • Nk::Int (optional): Parameter representing the number of k-points. If Nk == 0, a default configuration is used.
  • conf::Any: Configuration object for the optimizer, defaults to get_empty_config().
  • lr::Float64 (optional): Learning rate for the Adam optimizer. Defaults to the value returned by get_lr(conf).
  • Niter::Int (optional): Number of iterations for the optimization process. Defaults to the value returned by get_niter(conf).
  • val_weights::Bool (optional): If true, same weights are used for validation as for training.
source
Hamster.GDOptimizerType
GDOptimizer

A 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.

source
Hamster.LossType
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 of wE).
  • Nk::Int64: Number of k-points (dimension of wk).
  • 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 from get_loss(conf).
  • wE: Vector of weights for the energy bands, defaulted to get_band_weights(conf, Nε).
  • wk: Vector of weights for the k-points, defaulted to get_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 Loss object initialized with the appropriate band weights (wE), k-point weights (wk), normalization factor, and loss norm (n).
source
Hamster.LossType
struct Loss

A 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 the y dimension (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 of wE and wk.
  • n::Int64: The order of the norm used for the loss function (e.g., 1 for L1 norm, 2 for L2 norm, etc.).
source
Hamster.RegularizationType
Regularization([conf]; lambda=get_lambda(conf), barrier=get_barrier(conf), lreg=get_lreg(conf)) -> Regularization

Create 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 Regularization struct initialized with the provided or default configuration values for barrier, lambda, and lreg.
source
Hamster.RegularizationType
struct Regularization

A 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.
source
Hamster.backwardMethod
backward(l::Loss, y, ŷ)

Compute the gradient of the loss function with respect to the predicted values .

Arguments

  • l::Loss: A Loss object 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 values y.
source
Hamster.backwardMethod
backward(R::Regularization, x::AbstractVector) -> AbstractVector

Compute the gradient of the regularization penalty with respect to the input (parameter) vector x.

Arguments

  • R::Regularization: A Regularization object.
  • x::AbstractVector: The input (parameter) vector for which the gradient of the regularization penalty is computed.

Returns

  • AbstractVector: A vector of the same size as x, where each element is the gradient of the penalty with respect to the corresponding element in x.
source
Hamster.forwardMethod
forward(l::Loss, y, ŷ)

Compute the forward pass of the loss function given the true values y and the predicted values .

Arguments

  • l::Loss: A Loss object 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 .

source
Hamster.forwardMethod
forward(R::Regularization, x::AbstractVector) -> Float64

Compute the regularization penalty for the given input x using the regularization parameters defined in the Regularization struct.

Arguments

  • R::Regularization: A Regularization object.
  • x::AbstractVector: The input (parameter) vector over which the regularization penalty is applied.

Returns

  • Float64: The total regularization penalty
source
Hamster.get_weight_index_from_keyMethod
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.
source
Hamster.backwardFunction
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 an EigData object containing k-point and ground truth eigenvalues, or an HrData object containing real-space Hamiltonian data.
  • cache: A preliminary result from forward that is required to compute the gradient.

Returns

  • gradient: The computed gradient of the loss with respect to the parameters of ham.
source
Hamster.forwardMethod
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 an EigData object containing k-point and ground truth eigenvalues, or an HrData object containing real-space Hamiltonian data.

Returns

  • L_train::Float64: The calculated loss.
  • cache: A preliminary result that is needed to compute the gradient.
source
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: A Config instance.
  • 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

  1. Print the start message.
  2. For each training iteration, split the training data into batches and perform training steps.
  3. Optionally validate the model after each training iteration.
  4. Print the final status once training is complete.

Returns

  • Updates the HamsterProfiler prof and the model parameters in ham_train and ham_val.
source
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: A GDOptimizer instance.
  • train_data: The training data.
  • prof: A HamsterProfiler instance.
  • iter: The iteration index.
  • batch_id: The batch index.
  • comm: The MPI communicator.
  • conf: A Config instance.
  • 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.
source
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 the HamsterProfiler struct 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 the prof instance.

Returns

  • L_val: The average validation loss computed over all validation structures. This value is also stored in prof.L_val at the index corresponding to iter.
  • Updates to prof.val_times: The elapsed time for the validation step is stored in prof.val_times[iter].
source
Hamster.HamsterProfilerType
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 of get_empty_config().
  • Nbatch::Int: The number of batches (optional). Default is determined by the value of get_nbatch(conf).
  • Niter::Int: The number of iterations (optional). Default is determined by the value of get_niter(conf).
  • printeachbatch::Bool: A flag to determine whether to print detailed status for each batch (optional). Default is determined by the value of get_printeachbatch(conf).
  • printeachiter::Int: Specifies the frequency of printing status updates (optional). Default is determined by the value of get_printeachiter(conf).
  • Nparams::Int: The number of parameters that are optimized.

Returns

  • An instance of the HamsterProfiler struct.
source
Hamster.HamsterProfilerType
HamsterProfiler

A 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.
source
Hamster.decide_printitMethod
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 if printeachbatch is false.
  • verbosity::Int: (Keyword argument) The verbosity level. Printing is disabled if verbosity is less than 1.

Returns

  • Bool: true if a status update should be printed, false otherwise.

Behavior

  1. If verbosity < 1, printing is disabled and the function returns false.
  2. If printeachbatch is true, the function always returns true.
  3. Otherwise, printing occurs only if:
    • The current batch is the last batch (batch_id == Nbatch), and
    • The current iteration number (iter) is a multiple of printeachiter.
source
Hamster.print_final_statusMethod
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 compute final_loss and total_time.
source
Hamster.print_iteration_statusMethod
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 (use 0 if not using batches).
  • Nbatch::Int: The total number of batches (use 0 if not using batches).
  • L_train::Union{Float64, Int}: The current training loss value. Use 0 if 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:

  1. No batches and loss reported:
    • Prints iteration number, total iterations, loss, iteration time, and estimated time left.
  2. No batches, no loss reported:
    • Prints iteration number, total iterations, iteration time, and estimated time left.
  3. With batches and loss reported:
    • Prints batch number, total batches, iteration number, total iterations, loss, iteration time, and estimated time left.
  4. With batches, no loss reported:
    • Prints batch number, total batches, iteration number, total iterations, iteration time, and estimated time left.
source
Hamster.print_start_messageMethod
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.
source
Hamster.print_train_statusMethod
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 (use 0 if not using batches).
  • verbosity::Int (optional): Controls the level of detail in the output. Default is 1.
source
Hamster.print_val_startMethod
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. If verbosity > 0, the message "Validating model..." will be printed. Default is 1.
source
Hamster.print_val_statusMethod
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: A HamsterProfiler object 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. If verbosity > 0, the validation status will be printed. Default is 1.
source
Hamster.saveFunction
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.
source

Parsing functions

Hamster.parse_commandlineMethod
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 to true (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 of true.
source
Hamster.read_eigenvalFunction
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 the EIGENVAL file.
  • 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.
source
Hamster.PoscarType
struct Poscar

A 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.
source
Hamster.read_poscarMethod
read_poscar(poscar::AbstractString) -> Poscar

Extract all data from the POSCAR file at poscar.

Arguments

  • poscar::AbstractString: The path to the POSCAR file.

Returns

  • Poscar: A Poscar struct 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.
source
Hamster.collapse_files_withMethod
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.
source
Hamster.get_rank_filenameMethod
get_rank_filename(filename::AbstractString, rank::Integer) -> String

Return a modified file path of the form tmp/<basename>_<rank>.<ext>. Example: rankfilename("data.h5", 3) == "tmp/data3.h5"

source
Hamster.open_and_readMethod
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.
source
Hamster.parse_lines_as_arrayMethod
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 to 1.
  • i2 (optional): The ending index for the elements to extract from each line. Defaults to 3.
  • type (optional): The type to which the extracted elements should be converted. Defaults to Float64.

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.
source
Hamster.print_hamsterFunction
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 to stdout.
source
Hamster.read_from_fileMethod
read_from_file(filename, type)

Read an Array M with elements of type from the file with name filename.

source
Hamster.split_lineMethod
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.
source
Hamster.split_linesMethod
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.

source
Hamster.read_hrdatFunction
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 the hr.dat file.

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.
source
Hamster.read_xdatcarFunction
read_xdatcar(xdatcar::AbstractString) -> Xdatcar

Read 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.
source

Main

Hamster.decide_which_task_to_performMethod
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 Optimizer without a HyperOpt block tells Hamster to run a parameter optimization.
  • An Optimizer with a HyperOpt block tells Hamster to run a hyperparameter optimization.
  • Otherwise, a standard calculation is performed.
source

Config

Hamster.ConfigBlockType
ConfigBlock

A 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.
source
Hamster.filter_commentMethod
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 String that contains the line without comments. If the entire line is a comment or becomes empty after removing the comment, an empty string is returned.
source
Hamster.get_configMethod
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: A Config instance.
source
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.
source
Hamster.read_config_lineMethod
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.
source
Hamster.split_blocksMethod
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 ConfigBlock instances, each containing the header and content of a block found in the input lines.
source
Hamster.ConfigType
(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: The Config instance to query.
  • key: The key to look up in the Config instance.
  • typekey (optional): The key for the block in the blocks dictionary to look up the value. Defaults to "none".

Returns

  • The value associated with the key in the options dictionary if typekey is "none" and the key exists.
  • The value associated with the key in the specified block of the blocks dictionary if typekey is 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.
source
Hamster.ConfigType
struct Config

A 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.
source
Hamster.ConfigType
(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: The Config instance to query.
  • keys::Vector{String}: A vector of keys to look up in the Config instance.
  • typekey (optional): The key for the block in the blocks dictionary to look up the values. Defaults to "none".

Returns

  • A vector of values corresponding to the provided keys.
    • If typekey is "none" and the key exists in the options dictionary, the value from the options dictionary is returned.
    • If typekey is provided and exists in the blocks dictionary, 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.
source
Base.getMethod
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 the Config implementation.
  • default::T: A fallback value of type T to return if the configuration value for key is "default".

Returns

  • ::T: The value associated with key in conf, unless that value is "default", in which case default is returned.
source
Base.haskeyMethod
haskey(conf::Config, key)

Checks if a given key exists in either the options or blocks dictionary of a Config instance.

Arguments

  • conf::Config: The Config instance to check.
  • key: The key to check for existence.

Returns

  • Bool: true if the key exists in either the options or blocks dictionary, false otherwise.
source
Hamster.check_parseMethod
check_parse(type, line)

Check if the string or vector of strings line can be converte to type.

source
Hamster.convert_valueMethod
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, or Bool), or the original string if it cannot be converted.

Behavior:

  • The function splits the input value based on spaces into components using split_line(value, char=' ').
  • It then attempts to parse these components into Int64, Float64, and Bool types.
source
Hamster.get_RmaxMethod
**Rmax** = 1

maximum magnitude of translation vectors used for periodic boundaty conditions (default: determined by rcut).

source
Hamster.get_empty_configMethod
get_empty_config()

Returns an empty Config instance.

Returns

  • Config: An empty Config instance with empty options and blocks dictionaries.
source
Hamster.get_hyperopt_modeMethod
**mode** = random

hyperparameter optimization strategy (random=random search, grid=grid search, tpe=tree-structured Parzen Estimator)

source
Hamster.get_itp_xmaxMethod
**itp_xmax** = get_rcut(conf) + abs(get_rcut_tol(conf)) + 1

maximum x value for interpolation.

source
Hamster.get_lr_minMethod
**lr_min** = get_lr(conf)

final learning rate when using learning rate decay if lr≠lr_min.

source
Hamster.get_ml_modeMethod
**mode** = ifelse(get_ml_update(conf), "refit", "eval")

ml training mode (eval=evaluation, refit=retrain from scratch, expand=expand on existing)

source
Hamster.get_sepNNMethod
**sepNN** = false

use separate parameters for nearest-neighbor interactions. This can improve accuracy, however, may at the same time affect transferability negatively.

source
Hamster.get_val_ratioMethod
**val_ratio** = ifelse(get_validate(conf), 0.2, 0.0)

ratio between training and validation set size.

source
Hamster.get_write_hrMethod
**write_hr** = get_write_current(conf)

Whether to write real-space Hamiltonians. Defaults to true if write_current=true.

source
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: The Config instance where the key-value pair should be set.
source
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: The Config instance where the key-value pair should be set.
source

Output

Hamster.append_output_blockMethod
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_line function.
  • A separator line is written after the block for clarity.
source
Hamster.clear_hamster_outputMethod
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"].
source
Hamster.generate_outputFunction
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:

  1. Opens (creates) the file hamster.out for writing.
  2. Writes the current date and time to the file to record when the Hamster run started.
  3. Writes the list of unique hostnames.
source
Hamster.write_config_tagsMethod
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. If nothing, all blocks are printed.
  • show_desc: If true, adds the description as a comment on each line.
source
Hamster.write_separatorMethod
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.
source