API Reference
Main Types
System
Magesty.System — TypeSystemA collection of structure, symmetry, cluster, and basis set.
Fields
config::Parser: Configuration parserstructure::Structure: Crystal structure informationsymmetry::Symmetry: Symmetry operationscluster::Cluster: Cluster informationbasisset::BasisSet: Basis set information
SpinCluster
Magesty.SpinCluster — TypeSpinClusterAn extension of System with optimization capabilities.
Fields
config::Parser: Configuration parserstructure::Structure: Crystal structure informationsymmetry::Symmetry: Symmetry operationscluster::Cluster: Cluster informationbasisset::BasisSet: Basis set informationoptimize::Optimizer: Optimizer instance
Main Functions
System Building
Magesty.build_sce_basis — Functionbuild_sce_basis(input_dict::Dict{<:AbstractString, <:Any}; verbosity::Bool=false) -> SystemBuild 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 ofTOML.parsefile).verbosity::Bool=false: Whether to print detailed progress information.
Returns
System: ASysteminstance 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_xml — Functionbuild_sce_basis_from_xml(input_dict::Dict{<:AbstractString, <:Any}, xml_file::AbstractString; verbosity::Bool = true)::SystemBuild 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 informationverbosity::Bool=true: Whether to print detailed information during initialization
Returns
System: A newSysteminstance with basis set loaded from XML file
Throws
ErrorExceptionif 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.SpinCluster — MethodSpinClusterCreate 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 existingSysteminstance.verbosity::Bool=true: Whether to print detailed information during initialization.
Returns
SpinCluster: A newSpinClusterinstance 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.SpinCluster — MethodSpinCluster(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 existingSysteminstance 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 newSpinClusterinstance 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.SpinCluster — MethodSpinCluster(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 existingSysteminstance.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 fittedSpinClusterinstance.
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_model — Functionfit_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
Optimizerinstance.
Arguments
system: System instance containing structure, symmetry, cluster, and basis setspinconfig_list: Vector of spin configurationsestimator::AbstractEstimator: Estimator to use (default: OLS())weight::Real: Trade-off between energy (1-weight) and torque (weight). Default: 0.5verbosity::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.AbstractEstimator — TypeAbstractEstimatorAbstract type for SCE coefficient estimation methods.
Magesty.Optimize.OLS — TypeOLS <: AbstractEstimatorOrdinary Least Squares estimator (no regularization).
Magesty.Optimize.Ridge — TypeRidge <: AbstractEstimatorL2-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.λ = 0reduces to OLS.
Examples
estimator = Ridge(lambda = 0.1)Output Functions
Magesty.write_xml — Functionwrite_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 namewrite_jphi::Bool=true: Whether to embed the J_ij parameters (set tofalseto 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 writefilename::AbstractString: Output XML file name (default: "jphi.xml")
Examples
system = build_sce_basis(input_dict)
write_xml(system, "system.xml")Data Loading
Magesty.read_embset — Functionread_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
ErrorExceptionif the file format is invalidArgumentErrorif 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_energy — Functioncalc_energy(sc::SpinCluster, spin_config::AbstractMatrix{<:Real})Calculate the energy of a spin configuration using the spin cluster expansion.
Arguments
sc::SpinCluster: ASpinClusterinstance 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 inspin_configdoes 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_torque — Functioncalc_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: ASpinClusterinstance 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 inspin_configdoes 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_j0 — Functionget_j0(sc::SpinCluster) -> Float64Return 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_jphi — Functionget_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_jphi — Functionget_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)wherej0is the bias term in eV andjphiis the vector of SCE coefficients.
Examples
sc = SpinCluster("input.toml")
j0, jphi = get_j0_jphi(sc)Magesty.write_energies — Functionwrite_energies(sc::SpinCluster, filename::AbstractString="energy_list.txt")Write the observed (DFT) and predicted (SCE) energies to a text file.
Arguments
sc::SpinCluster: ASpinClusterinstance 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_torques — Functionwrite_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: ASpinClusterinstance 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.Structure — TypeStructureRepresents a periodic structure built from a Cell, with information about periodicity, atom types, and neighboring images.
Fields
supercell::CellThe 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 tox_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.Symmetry — Typestruct SymmetryContains 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.SymmetryOperation — Typestruct SymmetryOperationRepresents 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.Maps — TypeMaps Maps structure is used in Symmetry structure to map supercell atom to primitive index.
Clusters
Magesty.Clusters.Cluster — Typestruct ClusterRepresents a collection of interaction clusters based on the specified number of bodies and cutoff radii.
Fields
num_bodies::Int: Number of interacting bodiescutoff_radii::OffsetArray{Float64, 3}: Cutoff radii for each atomic element pair and interaction bodymin_distance_pairs::Matrix{Vector{DistInfo}}: Matrix of minimum distance pairs between atomscluster_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_orbits — Functioncluster_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 bodysymmetry::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 orbitBasisSets
Magesty.BasisSets.BasisSet — Typestruct BasisSetRepresents 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 multiplicitiessalc_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 speciessymmetry::Symmetry: Symmetry information for the crystal structurecluster::Cluster: Cluster information for atomic interactionsbody1_lmax::Vector{Int}: Maximum angular momentum values for 1-body interactions for each atomic speciesbodyn_lsum::OffsetArray{Int, 1}: Maximum sum of angular momentum values for multi-body interactionsnbody::Integer: Maximum number of bodies in interactionsisotropy::Bool: Iftrue, only include isotropic terms (Lf=0), default:falseverbosity::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:
- Constructs and classifies coupled basis functions using orbit information
- Constructs projection matrices for each symmetry label
- Generates symmetry-adapted linear combinations (SALCs) of
CoupledBasis_with_coefficientobjects
Spin Configurations
Magesty.SpinConfigs.SpinConfig — TypeSpinConfigA 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
ArgumentErrorif dimensions of input arrays do not matchArgumentErrorif any magnetic moment size is negative
Magesty.SpinConfigs.read_embset — Functionread_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
ErrorExceptionif the file format is invalidArgumentErrorif the file does not exist
Utility Types
Spherical Harmonics Transforms
Magesty.SphericalHarmonicsTransforms.c2r_sph_harm_matrix — Functionc2r_sph_harm_matrix(l::Integer) -> Matrix{ComplexF64}Compute the transformation matrix from complex spherical harmonics to tesseral harmonics.
Magesty.SphericalHarmonicsTransforms.r2c_sph_harm_matrix — Functionr2c_sph_harm_matrix(l::Integer) -> Matrix{ComplexF64}Compute the transformation matrix from tesseral harmonics to complex spherical harmonics.
Atom Cells
Magesty.AtomCells.AtomCell — TypeAtomCell(atom::Int, cell::Int)A structure that stores atom index and imaginary (virtual) cell index.
Fields
atom::Int: Index of the atomcell::Int: Index of the imaginary cell
Examples
julia> ac = AtomCell(1, 2)
(atom: 1, cell: 2)Configuration Parsers
Magesty.ConfigParser.Config4System — TypeConfig4SystemA structure that holds system configuration parameters for molecular dynamics simulations.
Required Parameters
name::String: Name of the systemnum_atoms::Int: Number of atoms in the systemkd_name::Vector{String}: List of chemical species namesnbody::Int: Maximum order of many-body interactionsbody1_lmax::Vector{Int}: Maximum angular momentum for each body 1 and interaction orderbodyn_lmax::OffsetArray{Int, 1}: Maximum angular momentum for each body n and interaction orderbodyn_cutoff::OffsetArray{Float64, 3}: Cutoff radii for interactions between elementslattice_vectors::Matrix{Float64}: Lattice vectors of the systemkd_int_list::Vector{Int}: List of chemical species indices for each atomx_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: Iftrue, only include isotropic terms (Lf=0) [default: false]
Magesty.ConfigParser.Config4Optimize — TypeConfig4OptimizeA 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ₗₘ — FunctionZₗₘ(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Float64Compute 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
- For repeated calls with inputs already checked, use
Zₗₘ_unsafe.
Magesty.MySphericalHarmonics.Zₗₘ_unsafe — FunctionZₗₘ_unsafe(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Float64Same 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}) -> Float64Buffered 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 — Function∂ᵢZlm(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> Vector{Float64}Cartesian gradient $(\partial_x Z_{\ell m}, \partial_y Z_{\ell m}, \partial_z Z_{\ell m})$.
Notes
- For hot paths, use
∂ᵢZlm_unsafe.
Magesty.MySphericalHarmonics.∂ᵢZlm_unsafe — Function∂ᵢ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.rotmat2euler — Functionrotmat2euler(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: Iftrue, the angles are adjusted to be within[0, 2π)forαandγ. Defaults totrue.
Returns
Tuple{Float64, Float64, Float64}: The Euler angles(α, β, γ).
Raises
ArgumentError: If the input matrixmis 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.Δl — FunctionΔ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
ArgumentErroriflis not positive.ArgumentErrorif the resulting matrix contains imaginary parts exceeding the threshold1e-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_energy — Functioncalc_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: Ifspin_directionsis 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_string — Functionversion_string() -> StringReturn 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.SortedVector — TypeSortedVector{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 aSortedVectorby sorting and storing a copy ofdata.SortedVector{T}(): Create an emptySortedVector{T}.SortedVector(): Create an emptySortedVector{Any}.
Magesty.SortedContainer.SortedUniqueVector — TypeSortedUniqueVector{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 aSortedUniqueVectorby sorting, removing duplicates, and storing a copy ofdata.SortedUniqueVector{T}(): Create an emptySortedUniqueVector{T}.
Magesty.SortedContainer.SortedCountingUniqueVector — TypeSortedCountingUniqueVector{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 fromdata, counting each element's occurrences.
Counting Containers
Magesty.CountingContainer.CountingUniqueVector — TypeCountingUniqueVector{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 emptyCountingUniqueVector{T}.CountingUniqueVector(data::AbstractVector{T}): Create a counting vector fromdata, 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)
2Magesty.CountingContainer.getcounts — Functiongetcounts(cuv::CountingUniqueVector{T}, val::T) -> IntGet the count of occurrences of val in the counting vector.
Arguments
cuv::CountingUniqueVector{T}: The counting vector to queryval::T: The value to count
Returns
Int: The number of timesvalappears in the vector
Examples
julia> cuv = CountingUniqueVector([1, 2, 2, 3, 3, 3])
julia> getcounts(cuv, 2)
2