API Reference

Main Types

System

Magesty.SystemType
System

A collection of structure, symmetry, cluster, and basis set.

Fields

  • config::Parser: Configuration parser
  • structure::Structure: Crystal structure information
  • symmetry::Symmetry: Symmetry operations
  • cluster::Cluster: Cluster information
  • basisset::BasisSet: Basis set information

SpinCluster

Magesty.SpinClusterType
SpinCluster

An extension of System with optimization capabilities.

Fields

  • config::Parser: Configuration parser
  • structure::Structure: Crystal structure information
  • symmetry::Symmetry: Symmetry operations
  • cluster::Cluster: Cluster information
  • basisset::BasisSet: Basis set information
  • optimize::Optimizer: Optimizer instance

Main Functions

System Building

Magesty.build_sce_basisFunction
build_sce_basis(input_dict::Dict{<:AbstractString, <:Any}; verbosity::Bool=false) -> System

Build a System (structure + symmetry + cluster + basis set) from a parsed input dictionary. This is the headless alternative to System(input_dict) and skips the header banner by default; the SALC basis is computed from scratch (use build_sce_basis_from_xml to load a precomputed basis instead).

Arguments

  • input_dict::Dict{<:AbstractString, <:Any}: Dictionary containing the parsed TOML input parameters (typically the result of TOML.parsefile).
  • verbosity::Bool=false: Whether to print detailed progress information.

Returns

  • System: A System instance containing structure, symmetry, cluster, and basis set.

Throws

  • ErrorException: If required parameters are missing or invalid.

Examples

using TOML
input_dict = TOML.parsefile("input.toml")
system = build_sce_basis(input_dict)
Magesty.build_sce_basis_from_xmlFunction
build_sce_basis_from_xml(input_dict::Dict{<:AbstractString, <:Any}, xml_file::AbstractString; verbosity::Bool = true)::System

Build System from input.toml dictionary and XML file. This function constructs structure, symmetry, and cluster from the input dictionary, but loads the basis set from the XML file to avoid expensive SALC computation.

Arguments

  • input_dict::Dict{<:AbstractString, <:Any}: Dictionary containing input parameters (parsed from input.toml)
  • xml_file::AbstractString: Path to XML file containing basis set information
  • verbosity::Bool=true: Whether to print detailed information during initialization

Returns

  • System: A new System instance with basis set loaded from XML file

Throws

  • ErrorException if required parameters are missing or XML file format is invalid

Examples

using TOML
input_dict = TOML.parsefile("input.toml")
system = build_sce_basis_from_xml(input_dict, "scecoeffs.xml")

SpinCluster Creation

Magesty.SpinClusterMethod
SpinCluster

Create a SpinCluster instance from either a dictionary of input parameters, a TOML configuration file, or an existing System instance. This is an extension of System that includes optimization capabilities.

Arguments

  • input_dict::Dict{<:AbstractString, <:Any}: Dictionary containing input parameters.
  • toml_file::AbstractString: Path to the TOML configuration file.
  • system::System: An existing System instance.
  • verbosity::Bool=true: Whether to print detailed information during initialization.

Returns

  • SpinCluster: A new SpinCluster instance containing structure, symmetry, cluster, basis set, and optimizer.

Throws

  • SystemError: If the TOML file cannot be read.
  • ErrorException: If required parameters are missing, invalid, or the TOML parsing fails.

Examples

# Create a SpinCluster from a dictionary
input_dict = Dict("key" => "value")
spin_cluster = SpinCluster(input_dict)

# Create a SpinCluster from a TOML file
spin_cluster = SpinCluster("config.toml")

# Create a SpinCluster from an existing System
system = System("config.toml")
spin_cluster = SpinCluster(system)
Magesty.SpinClusterMethod
SpinCluster(system::System, input_dict::Dict{<:AbstractString, <:Any}; verbosity::Bool = true)

Creates a SpinCluster instance by extending an existing System object with optimization capabilities. This constructor uses a dictionary of input parameters to configure the optimization process.

Arguments

  • system::System: An existing System instance containing structure, symmetry, cluster, and basis set information.
  • input_dict::Dict{<:AbstractString, <:Any}: A dictionary containing input parameters for optimization.
  • verbosity::Bool=true: Whether to print detailed information during initialization.

Returns

  • SpinCluster: A new SpinCluster instance containing structure, symmetry, cluster, basis set, and optimizer.

Throws

  • ErrorException: If required parameters are missing or invalid.

Example

input_dict = Dict("key" => "value")
system = System(input_dict)
spin_cluster = SpinCluster(system, input_dict)
Magesty.SpinClusterMethod
SpinCluster(system::System,
            input_dict::AbstractDict{<:AbstractString, <:Any},
            spinconfig_list::AbstractVector{SpinConfig};
            verbosity::Bool=true)

Create a SpinCluster from an existing System, an input dictionary, and a caller-supplied list of SpinConfig objects. Use this overload when the spin configurations come from somewhere other than the EMBSET path declared in input_dict (for example, configurations generated programmatically or pulled from a non-standard format).

Arguments

  • system::System: An existing System instance.
  • input_dict::AbstractDict{<:AbstractString, <:Any}: Dictionary with optimization parameters ([regression] section).
  • spinconfig_list::AbstractVector{SpinConfig}: Training spin configurations used in place of those that would be loaded from disk.
  • verbosity::Bool=true: Whether to print detailed information during fitting.

Returns

  • SpinCluster: A fitted SpinCluster instance.

Throws

  • ErrorException: If required [regression] parameters are missing or invalid.

Examples

system = System("input.toml")
configs = [SpinConfig(...), SpinConfig(...)]
sc = SpinCluster(system, input_dict, configs)

Model Fitting

Magesty.Optimize.fit_sce_modelFunction
fit_sce_model(system, spinconfig_list, estimator, weight)

Fit SCE coefficients using the specified estimator.

Description

  • Builds design matrices internally from the System and spin configurations.
  • Dispatches to the appropriate fitting method based on the estimator type.
  • Supports OLS and Ridge estimators.
  • User-facing function for fitting SCE coefficients.
  • Returns an Optimizer instance.

Arguments

  • system: System instance containing structure, symmetry, cluster, and basis set
  • spinconfig_list: Vector of spin configurations
  • estimator::AbstractEstimator: Estimator to use (default: OLS())
  • weight::Real: Trade-off between energy (1-weight) and torque (weight). Default: 0.5
  • verbosity::Bool: Whether to print detailed information (default: false)

Returns

  • Optimizer: Optimizer instance containing fitted coefficients and metrics

Examples

# Using OLS with default weight (0.5)
optimizer = fit_sce_model(system, spinconfig_list)

# Using Ridge with custom regularization and weight
estimator = Ridge(lambda=0.1)
optimizer = fit_sce_model(system, spinconfig_list, estimator, 0.7)

Estimators

Magesty.Optimize.OLSType
OLS <: AbstractEstimator

Ordinary Least Squares estimator (no regularization).

Magesty.Optimize.RidgeType
Ridge <: AbstractEstimator

L2-regularized least-squares (ridge) estimator. The bias column is excluded from the penalty by the dispatch boundary (see solve_coefficients).

Fields

  • lambda::Float64: Regularization strength. λ = 0 reduces to OLS.

Examples

estimator = Ridge(lambda = 0.1)

Output Functions

Magesty.write_xmlFunction
write_xml(sc::SpinCluster, filename::AbstractString="jphi.xml"; write_jphi::Bool=true)

Write the structure, symmetry, basis set, and fitted SCE coefficients held by a SpinCluster to an XML file in SCE format.

Arguments

  • sc::SpinCluster: Spin cluster (structure + symmetry + basis set + optimizer)
  • filename::AbstractString="jphi.xml": Output XML file name
  • write_jphi::Bool=true: Whether to embed the J_ij parameters (set to false to write only the structure/symmetry/basis section)

Examples

write_xml(spin_cluster)
write_xml(spin_cluster, "output.xml", write_jphi=false)

To export a System (no fitted coefficients), use the write_xml(::System, ...) overload instead. To export from standalone components (structure, symmetry, basis_set, optimizer), wrap them with SpinCluster(structure, symmetry, cluster, basis_set, optimizer) first.

write_xml(system::System, filename::AbstractString="jphi.xml")

Write System information to an XML file. This saves the structure, symmetry, and basis set information without optimization results (JPhi).

Arguments

  • system::System: The System to write
  • filename::AbstractString: Output XML file name (default: "jphi.xml")

Examples

system = build_sce_basis(input_dict)
write_xml(system, "system.xml")

Data Loading

Magesty.read_embsetFunction
read_embset(filepath::AbstractString) -> Vector{SpinConfig}

Read spin configurations from an EMBSET file.

Arguments

  • filepath::AbstractString: Path to the EMBSET file

Returns

  • Vector{SpinConfig}: Array of spin configurations

Throws

  • ErrorException if the file format is invalid
  • ArgumentError if the file does not exist

Non-Exported Convenience Functions

The following functions are defined in the Magesty module but are not exported. After using Magesty, access them with the Magesty. prefix:

Magesty.calc_energy(sc, spin_config)
Magesty.calc_torque(sc, spin_config)
Magesty.get_j0(sc)
Magesty.get_jphi(sc)
Magesty.get_j0_jphi(sc)
Magesty.write_energies(sc, filename)
Magesty.write_torques(sc, filename)
Magesty.calc_energyFunction
calc_energy(sc::SpinCluster, spin_config::AbstractMatrix{<:Real})

Calculate the energy of a spin configuration using the spin cluster expansion.

Arguments

  • sc::SpinCluster: A SpinCluster instance containing structure, symmetry, basis set, and optimization information.
  • spin_config::AbstractMatrix{<:Real}: A 3xN matrix representing the spin configuration, where N is the number of atoms in the supercell.

Returns

  • Float64: The calculated energy of the given spin configuration.

Throws

  • ArgumentError: If the number of columns in spin_config does not match the number of atoms in the supercell.

Example

spin_config = rand(3, sc.structure.supercell.num_atoms) # Random spin configuration
energy = calc_energy(sc, spin_config)
Magesty.calc_torqueFunction
calc_torque(sc::SpinCluster, spin_config::AbstractMatrix{<:Real})

Calculate the torque (local magnetic field) for each atom in a spin configuration using the spin cluster expansion.

Arguments

  • sc::SpinCluster: A SpinCluster instance containing structure, symmetry, basis set, and optimization information.
  • spin_config::AbstractMatrix{<:Real}: A 3xN matrix representing the spin configuration, where N is the number of atoms in the supercell.

Returns

  • Matrix{Float64}: A 3xN matrix representing the torque for each atom, where each column corresponds to the torque vector (in eV) for one atom.

Throws

  • ArgumentError: If the number of columns in spin_config does not match the number of atoms in the supercell.

Example

spin_config = rand(3, sc.structure.supercell.num_atoms) # Random spin configuration
torque = calc_torque(sc, spin_config)
Magesty.get_j0Function
get_j0(sc::SpinCluster) -> Float64

Return the fitted reference energy (bias term j0) from a SpinCluster.

Arguments

  • sc::SpinCluster: Spin cluster with a fitted optimizer.

Returns

  • Float64: Reference energy in eV (the constant offset of the SCE expansion).

Examples

sc = SpinCluster("input.toml")
j0 = get_j0(sc)
Magesty.get_jphiFunction
get_jphi(sc::SpinCluster) -> Vector{Float64}

Return the fitted SCE coefficients (jphi) from a SpinCluster.

Arguments

  • sc::SpinCluster: Spin cluster with a fitted optimizer.

Returns

  • Vector{Float64}: SCE coefficients, one entry per SALC basis function.

Examples

sc = SpinCluster("input.toml")
jphi = get_jphi(sc)
Magesty.get_j0_jphiFunction
get_j0_jphi(sc::SpinCluster) -> Tuple{Float64, Vector{Float64}}

Return the reference energy and SCE coefficients as a tuple.

Arguments

  • sc::SpinCluster: Spin cluster with a fitted optimizer.

Returns

  • Tuple{Float64, Vector{Float64}}: (j0, jphi) where j0 is the bias term in eV and jphi is the vector of SCE coefficients.

Examples

sc = SpinCluster("input.toml")
j0, jphi = get_j0_jphi(sc)
Magesty.write_energiesFunction
write_energies(sc::SpinCluster, filename::AbstractString="energy_list.txt")

Write the observed (DFT) and predicted (SCE) energies to a text file.

Arguments

  • sc::SpinCluster: A SpinCluster instance containing optimization results.
  • filename::AbstractString="energy_list.txt": Output file name.

Output Format

The file contains:

  • Header line: # data index, DFT_Energy, SCE_Energy
  • Data lines: index, observed energy (eV), predicted energy (eV)

Example

write_energies(sc, "my_energies.txt")
Magesty.write_torquesFunction
write_torques(sc::SpinCluster, filename::AbstractString="torque_list.txt")

Write the observed (DFT) and predicted (SCE) torques for each atom to a text file.

Arguments

  • sc::SpinCluster: A SpinCluster instance containing optimization results.
  • filename::AbstractString="torque_list.txt": Output file name.

Output Format

The file contains:

  • Header line: # atom index, element, DFT_torque_x, DFT_torque_y, DFT_torque_z, SCE_torque_x, SCE_torque_y, SCE_torque_z
  • Data lines: atom index, element symbol, observed torque components (eV), predicted torque components (eV)
  • Data is grouped by configuration index

Example

write_torques(sc, "my_torques.txt")

Submodules

Structures

Magesty.Structures.StructureType
Structure

Represents a periodic structure built from a Cell, with information about periodicity, atom types, and neighboring images.

Fields

  • supercell::Cell The unit cell of the structure, containing lattice vectors, reciprocal vectors, atomic positions, and magnetic moments.

  • is_periodic::Vector{Bool} A vector indicating periodicity along each of the three principal axes. Each element corresponds to whether the structure is periodic (true) or non-periodic (false) along that axis.

  • kd_name::Vector{String} A list of element names present in the structure without deplication (e.g., ["Fe", "Co", "Ni"]).

  • x_image_frac::Array{Float64, 3} Fractional coordinates of atoms in neighboring (imaginary) cells. The dimensions typically represent the number of images, number of atoms, and the three fractional coordinates.

  • x_image_cart::Array{Float64, 3} Cartesian coordinates of atoms in neighboring (imaginary) cells. Similar to x_image_frac, the dimensions represent the number of images, number of atoms, and the three Cartesian coordinates.

  • exist_image::Vector{Bool} Indicates the existence of neighboring cells based on the structure's periodicity. Each element corresponds to whether a particular neighboring cell exists (true) or not (false).

  • atomtype_group::Vector{Vector{Int}} Groups of atom indices categorized by their types. Each sub-vector contains the indices of atoms belonging to a specific element type.

Symmetries

Magesty.Symmetries.SymmetryType
struct Symmetry

Contains the symmetry information of a structure.

Fields

  • international_symbol::String: International symbol of the space group.
  • spacegroup_number::Int: Space group number.
  • nsym::Int: Number of symmetry operations.
  • ntran::Int: Number of pure translation operations.
  • nat_prim::Int: Number of atoms in the primitive cell.
  • tol::Float64: Tolerance for symmetry detection.
  • atoms_in_prim::Vector{Int}: Indices of atoms in the primitive cell.
  • symdata::Vector{SymmetryOperation}: List of symmetry operations.
  • map_sym::Matrix{Int}: Maps atoms in the supercell to corresponding atoms under symmetry operations.
  • map_p2s::Matrix{Int}: Maps atoms in the primitive cell to the supercell.
  • map_s2p::Vector{Maps}: Maps atoms in the supercell to the primitive cell.
  • symnum_translation::Vector{Int}: Indices of pure translation operations.

Constructor

Symmetry(structure, tol::Float64)

Generate symmetry information for the given structure using the specified tolerance.

Magesty.Symmetries.SymmetryOperationType
struct SymmetryOperation

Represents a symmetry operation, including rotation and translation components.

Fields

  • rotation_frac::SMatrix{3, 3, Float64, 9}: The 3x3 rotation matrix in fractional coordinates.
  • rotation_cart::SMatrix{3, 3, Float64, 9}: The 3x3 rotation matrix in Cartesian coordinates.
  • translation_frac::SVector{3, Float64}: The 3x1 translation vector in fractional coordinates.
  • is_translation::Bool: True if the operation is a pure translation.
  • is_proper::Bool: True if the rotation is proper (determinant > 0).

Examples

# Create a symmetry operation
symop = SymmetryOperation(
	rotation_frac = [1 0 0; 0 1 0; 0 0 1],
	rotation_cart = [1 0 0; 0 1 0; 0 0 1],
	translation_frac = [0.0, 0.0, 0.0],
	is_translation = true,
	is_proper = true
)
Magesty.Symmetries.MapsType

Maps Maps structure is used in Symmetry structure to map supercell atom to primitive index.

Clusters

Magesty.Clusters.ClusterType
struct Cluster

Represents a collection of interaction clusters based on the specified number of bodies and cutoff radii.

Fields

  • num_bodies::Int: Number of interacting bodies
  • cutoff_radii::OffsetArray{Float64, 3}: Cutoff radii for each atomic element pair and interaction body
  • min_distance_pairs::Matrix{Vector{DistInfo}}: Matrix of minimum distance pairs between atoms
  • cluster_dict::Dict{Int, Dict{Int, CountingUniqueVector{Vector{Int}}}}: Dictionary of interaction clusters organized by body and primitive atom index

Constructor

Cluster(structure, symmetry, nbody, cutoff_radii)

Creates a new Cluster instance based on the provided structure, symmetry information, number of bodies, and cutoff radii.

Example

cluster = Cluster(structure, symmetry, 3, cutoff_radii)
Magesty.Clusters.cluster_orbitsFunction
cluster_orbits(
	irreducible_cluster_dict::Dict{Int, SortedCountingUniqueVector{Vector{Int}}},
	symmetry::Symmetry,
) -> Dict{Int, Dict{Int, Vector{Vector{Int}}}}

Classify clusters in irreducible_cluster_dict into orbits under spatial symmetry operations.

An orbit is a set of clusters that can be transformed into each other by spatial symmetry operations (rotations, reflections, etc.) combined with translations. Clusters in the same orbit will have the same projection matrix structure, making this classification useful for efficient projection operator construction.

Arguments

  • irreducible_cluster_dict::Dict{Int, SortedCountingUniqueVector{Vector{Int}}}: Dictionary of irreducible clusters organized by body
  • symmetry::Symmetry: Symmetry information containing spatial symmetry operations

Returns

  • Dict{Int, Dict{Int, Vector{Vector{Int}}}}: Dictionary organized as [body][orbit_index] -> [clusters in orbit] where clusters are sorted atom lists

Example

orbits = cluster_orbits(cluster.irreducible_cluster_dict, symmetry)
# orbits[2][1] contains all 2-body clusters in the first orbit

BasisSets

Magesty.BasisSets.BasisSetType
struct BasisSet

Represents a set of basis functions for atomic interactions in a crystal structure. This structure is used to store and manage basis functions that are adapted to the symmetry of the crystal.

Fields

  • coupled_basislist::SortedCountingUniqueVector{Basis.CoupledBasis}: List of coupled angular momentum basis functions with their multiplicities
  • salc_list::Vector{Vector{Basis.CoupledBasis_with_coefficient}}: List of symmetry-adapted linear combinations (SALCs), where each element is a vector of coupled basis functions belonging to the same key group

Constructors

BasisSet(structure, symmetry, cluster, body1_lmax, bodyn_lsum, nbody; isotropy=false, verbosity=true)
BasisSet(structure, symmetry, cluster, config; verbosity=true)

Constructs a new BasisSet instance for atomic interactions in a crystal structure.

Arguments

  • structure::Structure: Structure information containing atomic positions and species
  • symmetry::Symmetry: Symmetry information for the crystal structure
  • cluster::Cluster: Cluster information for atomic interactions
  • body1_lmax::Vector{Int}: Maximum angular momentum values for 1-body interactions for each atomic species
  • bodyn_lsum::OffsetArray{Int, 1}: Maximum sum of angular momentum values for multi-body interactions
  • nbody::Integer: Maximum number of bodies in interactions
  • isotropy::Bool: If true, only include isotropic terms (Lf=0), default: false
  • verbosity::Bool: Whether to print progress information (default: true)

Returns

  • BasisSet: A new basis set instance containing coupled basis functions and symmetry-adapted linear combinations

Examples

# Create a basis set using explicit parameters
body1_lmax = [2, 3]  # lmax for each atomic species
bodyn_lsum = OffsetArray([0, 0, 4, 6], 0:3)  # lsum for each body
basis = BasisSet(structure, symmetry, cluster, body1_lmax, bodyn_lsum, 3)

# Create a basis set using configuration
basis = BasisSet(structure, symmetry, cluster, config)

Note

The constructor performs the following steps:

  1. Constructs and classifies coupled basis functions using orbit information
  2. Constructs projection matrices for each symmetry label
  3. Generates symmetry-adapted linear combinations (SALCs) of CoupledBasis_with_coefficient objects

Spin Configurations

Magesty.SpinConfigs.SpinConfigType
SpinConfig

A configuration of spins in a magnetic structure.

Fields

  • energy::Float64: The energy of the spin configuration [eV]
  • magmom_size::Vector{Float64}: The magnitude of magnetic moments for each atom [μ_B]
  • spin_directions::Matrix{Float64}: The direction cosines (unit vectors) of the spins [3 × num_atoms]
  • local_magfield::Matrix{Float64}: The local magnetic field at each atom [T]
  • local_magfield_vertical::Matrix{Float64}: The component of the local magnetic field perpendicular to the magnetic moments [T]

Constructors

  • SpinConfig(energy, magmom_size, spin_directions, local_magfield): Create a spin configuration

Throws

  • ArgumentError if dimensions of input arrays do not match
  • ArgumentError if any magnetic moment size is negative
Magesty.SpinConfigs.read_embsetFunction
read_embset(filepath::AbstractString) -> Vector{SpinConfig}

Read spin configurations from an EMBSET file.

Arguments

  • filepath::AbstractString: Path to the EMBSET file

Returns

  • Vector{SpinConfig}: Array of spin configurations

Throws

  • ErrorException if the file format is invalid
  • ArgumentError if the file does not exist

Utility Types

Spherical Harmonics Transforms

Atom Cells

Magesty.AtomCells.AtomCellType
AtomCell(atom::Int, cell::Int)

A structure that stores atom index and imaginary (virtual) cell index.

Fields

  • atom::Int: Index of the atom
  • cell::Int: Index of the imaginary cell

Examples

julia> ac = AtomCell(1, 2)
(atom: 1, cell: 2)

Configuration Parsers

Magesty.ConfigParser.Config4SystemType
Config4System

A structure that holds system configuration parameters for molecular dynamics simulations.

Required Parameters

  • name::String: Name of the system
  • num_atoms::Int: Number of atoms in the system
  • kd_name::Vector{String}: List of chemical species names
  • nbody::Int: Maximum order of many-body interactions
  • body1_lmax::Vector{Int}: Maximum angular momentum for each body 1 and interaction order
  • bodyn_lmax::OffsetArray{Int, 1}: Maximum angular momentum for each body n and interaction order
  • bodyn_cutoff::OffsetArray{Float64, 3}: Cutoff radii for interactions between elements
  • lattice_vectors::Matrix{Float64}: Lattice vectors of the system
  • kd_int_list::Vector{Int}: List of chemical species indices for each atom
  • x_fractional::Matrix{Float64}: Fractional coordinates of atoms

Optional Parameters

  • is_periodic::Vector{Bool}: Periodicity flags for each direction [default: [true, true, true]]
  • tolerance_sym::Float64: Tolerance for symmetry operations [default: 1e-3]
  • isotropy::Bool: If true, only include isotropic terms (Lf=0) [default: false]
Magesty.ConfigParser.Config4OptimizeType
Config4Optimize

A structure that holds optimization parameters.

Required Parameters

  • datafile::String: Path to the data file

Optional Parameters

  • ndata::Int: Number of data points to use [default: -1]
  • weight::Float64: Weight for optimization [default: 0.0]

Utility Functions

Spherical Harmonics

Magesty.MySphericalHarmonics.ZₗₘFunction
Zₗₘ(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Float64

Compute the tesseral harmonic Zₗₘ.

Arguments

  • l: Angular momentum quantum number (≥ 0)
  • m: Magnetic quantum number (-l ≤ m ≤ l)
  • uvec: Normalized 3D direction vector [r̂x, r̂y, r̂z]

Mathematical Details

For m = 0: Zₗₘ = P̄ₗₘ(r̂z) For m > 0: Zₗₘ = (-1)ᵐ√2 P̄ₗₘ(r̂z) ∑ₖ (-1)ᵏ (m,2k) r̂x^(m-2k) r̂y^(2k) For m < 0: Zₗₘ = (-1)ⁿ√2 P̄ₗₘ(r̂z) ∑ₖ (-1)ᵏ (n,2k+1) r̂x^(n-2k-1) r̂y^(2k+1)

where n = |m| and (n,k) denotes binomial coefficient.

Reference: Equation (***) in T. Tanaka and Y. Gohda, ***

Notes

Magesty.MySphericalHarmonics.Zₗₘ_unsafeFunction
Zₗₘ_unsafe(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Float64

Same as Zₗₘ but does not validate l, m, or uvec. Caller must ensure -l ≤ m ≤ l, l ≥ 0, and uvec is a length-3 unit vector. Violations may produce wrong results or errors from lower-level code.

Zₗₘ_unsafe(l, m, uvec, buf::AbstractVector{Float64}) -> Float64

Buffered variant of Zₗₘ_unsafe that reuses buf as the cache for LegendrePolynomials.dnPl, eliminating the per-call heap allocation. buf must satisfy length(buf) >= l - |m| + 1; allocating Vector{Float64}(undef, max_l + 1) once per thread covers all (l, m) with l ≤ max_l. Numerical result is identical to the unbuffered method.

Magesty.MySphericalHarmonics.∂ᵢZlm_unsafeFunction
∂ᵢZlm_unsafe(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Vector{Float64}

Same as ∂ᵢZlm without validating l, m, or uvec.

∂ᵢZlm_unsafe(l, m, uvec, buf::AbstractVector{Float64}) -> SVector{3,Float64}

Buffered variant of ∂ᵢZlm_unsafe. buf is reused as the cache for both the P̄ₗₘ and dP̄ₗₘ_unsafe calls (each call overwrites buf independently; result is read before the next call). buf must satisfy length(buf) >= l - |m| + 1; Vector{Float64}(undef, max_l + 1) per thread covers all (l, m) with l ≤ max_l.

Rotation Matrices

Magesty.RotationMatrix.rotmat2eulerFunction
rotmat2euler(m::AbstractMatrix{<:Real}, mod_positive::Bool = true) -> Tuple{Float64, Float64, Float64}

Converts a 3x3 rotation matrix m to Euler angles (α, β, γ).

Arguments

  • m::AbstractMatrix{<:Real}: A 3x3 rotation matrix.
  • mod_positive::Bool: If true, the angles are adjusted to be within [0, 2π) for α and γ. Defaults to true.

Returns

  • Tuple{Float64, Float64, Float64}: The Euler angles (α, β, γ).

Raises

  • ArgumentError: If the input matrix m is not 3x3.

Examples

m = [1 0 0; 0 cos(pi/4) -sin(pi/4); 0 sin(pi/4) cos(pi/4)]
angles = rotmat2euler(m)
println(angles)  # (0.0, 0.7853981633974483, 0.0)
Magesty.RotationMatrix.ΔlFunction
Δl(l::Int, α::Float64, β::Float64, γ::Float64)::Matrix{Float64}

Compute the Δ matrix for a given l, α, β, and γ.

Arguments

  • l::Int: Positive integer representing the angular momentum quantum number.
  • α::Float64, β::Float64, γ::Float64: Euler angles in radians.

Returns

  • A real-valued matrix Δ::Matrix{Float64}.

Throws

  • ArgumentError if l is not positive.
  • ArgumentError if the resulting matrix contains imaginary parts exceeding the threshold 1e-12.

Notes

  • The resulting matrix is converted to real if the imaginary parts are negligible.

References

  • M.A. Blanco et al., Journal of Molecular Structure (Theochem) 419 19-27 (1997).

Energy Calculations

Magesty.EnergyTorque.calc_energyFunction
calc_energy(salc_list, spin_directions, symmetry, optimize)

Calculate the energy of a spin configuration using the spin cluster expansion.

Description

Computes the energy for a given spin configuration by evaluating the spin cluster expansion model. The energy is calculated as the dot product of the design vector (computed from the spin directions and basis functions) with the optimized SCE coefficients, plus the reference energy.

Arguments

  • salc_list::AbstractVector{Vector{Basis.CoupledBasis_with_coefficient}}: List of symmetry-adapted linear combinations (SALCs), where each element is a vector of coupled basis functions belonging to the same key group.
  • spin_directions::AbstractMatrix{<:Real}: A 3×N matrix representing the spin configuration, where each column is a unit vector (x, y, z) representing the spin direction at each atom. N is the number of atoms in the supercell.
  • symmetry::Symmetry: Symmetry information of the crystal structure.
  • optimize::Optimizer: Optimizer instance containing the optimized SCE coefficients (optimize.SCE) and reference energy (optimize.reference_energy).

Returns

  • Float64: The calculated energy of the spin configuration in eV.

Throws

  • ArgumentError: If spin_directions is not a 3×N matrix.

Example

# Calculate energy for a spin configuration
spin_config = rand(3, num_atoms)
# Normalize to unit vectors
for i in 1:num_atoms
    spin_config[:, i] ./= norm(spin_config[:, i])
end
energy = calc_energy(salc_list, spin_config, symmetry, optimizer)

Version Information

Magesty.Version.version_stringFunction
version_string() -> String

Return the package version as a string by reading it from Project.toml via pkgversion. Bumping the version is therefore a single-file edit in Project.toml; no constants need to be kept in sync here.

Returns "unknown" if the module was loaded outside of a package context (e.g., included directly from a script).

Container Types

Sorted Containers

Magesty.SortedContainer.SortedVectorType
SortedVector{T} <: AbstractSortedVector{T}

A mutable sorted vector of elements of type T. This structure maintains its internal data::Vector{T} in sorted order.

Fields

  • data::Vector{T}: The underlying sorted array storing all elements.

Constructors

  • SortedVector(data): Create a SortedVector by sorting and storing a copy of data.
  • SortedVector{T}(): Create an empty SortedVector{T}.
  • SortedVector(): Create an empty SortedVector{Any}.
Magesty.SortedContainer.SortedUniqueVectorType
SortedUniqueVector{T} <: AbstractSortedVector{T}

A mutable sorted vector that maintains unique elements of type T.

Fields

  • data::Vector{T}: The underlying array, always sorted and without duplicates.

Constructors

  • SortedUniqueVector(data): Create a SortedUniqueVector by sorting, removing duplicates, and storing a copy of data.
  • SortedUniqueVector{T}(): Create an empty SortedUniqueVector{T}.
Magesty.SortedContainer.SortedCountingUniqueVectorType
SortedCountingUniqueVector{T} <: AbstractSortedVector{T}

A mutable sorted vector of unique elements (like SortedUniqueVector) that also tracks how many times each element was inserted.

Fields

  • data::SortedUniqueVector{T}: The underlying sorted collection of unique elements.
  • counts::Dict{T,Int}: A dictionary mapping each element to its insertion count.

Constructors

  • SortedCountingUniqueVector{T}(): Create an empty counting vector.
  • SortedCountingUniqueVector(data::AbstractVector{T}): Create a counting vector from data, counting each element's occurrences.

Counting Containers

Magesty.CountingContainer.CountingUniqueVectorType
CountingUniqueVector{T} <: AbstractVector{T}

A mutable vector of unique elements with counts of each element's occurrences.

Fields

  • data::Vector{T}: The underlying array of unique elements.
  • counts::Dict{T, Int}: A dictionary mapping each element to its insertion count.

Constructors

  • CountingUniqueVector(): Create an empty CountingUniqueVector{T}.
  • CountingUniqueVector(data::AbstractVector{T}): Create a counting vector from data, counting each element's occurrences.

Examples

julia> cuv = CountingUniqueVector([1, 2, 2, 3, 3, 3])
counts: 1 data: 1
counts: 2 data: 2
counts: 3 data: 3

julia> getcounts(cuv, 2)
2
Magesty.CountingContainer.getcountsFunction
getcounts(cuv::CountingUniqueVector{T}, val::T) -> Int

Get the count of occurrences of val in the counting vector.

Arguments

  • cuv::CountingUniqueVector{T}: The counting vector to query
  • val::T: The value to count

Returns

  • Int: The number of times val appears in the vector

Examples

julia> cuv = CountingUniqueVector([1, 2, 2, 3, 3, 3])
julia> getcounts(cuv, 2)
2