Internal API
The names on this page are internal: they are not exported and may be renamed, removed, or have their signatures changed in any release without a deprecation cycle. They are documented here for contributors and for advanced users who need access to lower-level building blocks (e.g. inspecting a SALCBasis after construction). For the stable, user-facing surface see the API Reference.
Submodules
Structures
Magesty.Structures.Structure — Type
StructureRepresents 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 duplication (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 — Type
struct 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 — Type
struct 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 — Type
Maps Maps structure is used in Symmetry structure to map supercell atom to primitive index.
Clusters
Magesty.Clusters.Cluster — Type
struct 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, OrderedDict{Vector{Int}, 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)SALCBases
Magesty.SALCBases.SALCBasis — Type
struct SALCBasisRepresents 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::SortedCounter{CoupledBases.CoupledBasis}: List of coupled angular momentum basis functions with their multiplicitiessalc_list::Vector{Vector{CoupledBases.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
SALCBasis(structure, symmetry, cluster, body1_lmax, bodyn_lsum, nbody; isotropy=false, verbosity=true)
SALCBasis(structure, symmetry, cluster, config; verbosity=true)Constructs a new SALCBasis 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
SALCBasis: 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 = SALCBasis(structure, symmetry, cluster, body1_lmax, bodyn_lsum, 3)
# Create a basis set using configuration
basis = SALCBasis(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
Utility types
Spherical harmonics transforms
Magesty.SphericalHarmonicsTransforms.c2r_sph_harm_matrix — Function
c2r_sph_harm_matrix(l::Integer) -> Matrix{ComplexF64}Compute the transformation matrix from complex spherical harmonics to tesseral harmonics.
Magesty.SphericalHarmonicsTransforms.r2c_sph_harm_matrix — Function
r2c_sph_harm_matrix(l::Integer) -> Matrix{ComplexF64}Compute the transformation matrix from tesseral harmonics to complex spherical harmonics.
This is the inverse of c2r_sph_harm_matrix, obtained as its adjoint. The adjoint equals the inverse only because c2r_sph_harm_matrix is unitary (an L2-orthonormal change of basis between the complex and real harmonics); a future change to the normalization that breaks that unitarity would break this identity. The round-trip r2c * c2r ≈ I is asserted in the tests.
Atom cells
Magesty.AtomCells.AtomCell — Type
AtomCell(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)Input specs
Magesty.InputSpecs.SystemSpec — Type
SystemSpecMaterial-side input: name, atom count, species, lattice, fractional positions, periodicity. Holds no interaction or symmetry parameters.
Fields
name::String: System identifier.num_atoms::Int: Number of atoms in the cell.kd_name::Vector{String}: Unique species labels in user-defined order.kd_int_list::Vector{Int}: Per-atom species index (1-based, intokd_name).lattice_vectors::Matrix{Float64}: 3 x 3 matrix; columns are a, b, c (Angstrom).x_fractional::Matrix{Float64}: 3 x num_atoms fractional coordinates.is_periodic::Vector{Bool}: Length 3, per-direction periodicity.
Magesty.InputSpecs.InteractionSpec — Type
InteractionSpecInteraction-side input: many-body order and per-body / per-species angular momentum and cutoff parameters.
Fields
nbody::Int: Maximum interaction body order (>= 1).body1_lmax::Vector{Int}: Body-1 lmax per species, length =length(kd_name).bodyn_lsum::OffsetArray{Int, 1}: lsum per body, indexed2:nbody. Empty (2:1) whennbody == 1.bodyn_cutoff::OffsetArray{Float64, 3}: Pair cutoff per (body, kdi, kdj), indexed(2:nbody, 1:nkd, 1:nkd). Symmetric in the last two indices.-1.0means "include all pairs". Empty body axis (2:1) whennbody == 1.
Construction
kd_name::Vector{String} is consumed for cross-validation against the species labels but not stored.
Magesty.InputSpecs.SymmetryOptions — Type
SymmetryOptions(; tolerance_sym = 1e-3, isotropy = false)Symmetry-detection options.
Fields
tolerance_sym::Float64: Tolerance for spglib symmetry detection (> 0).isotropy::Bool: Iftrue, keep only isotropic basis terms (Lf = 0).
Magesty.InputSpecs.parse_toml_inputs — Function
parse_toml_inputs(dict::AbstractDict) -> (SystemSpec, InteractionSpec, SymmetryOptions)Parse a TOML-shape dictionary into the three typed input value objects. Wildcard species notation ("*-*", "X-*", "*-Y" for pair tables and "*" for species tables) is expanded here using specificity-based resolution; the returned InteractionSpec is fully concrete (no wildcards survive).
Expected schema:
[general]
name = "..."
nat = N
kd = ["A", "B", ...]
periodicity = [true, true, true] # optional, default [true, true, true]
[symmetry]
tolerance = 1e-3 # optional, default 1e-3
isotropy = false # optional, default false
[interaction]
nbody = M
[interaction.body1.lmax]
"A" = ...
"*" = ... # newly accepted
[interaction.body2]
lsum = ...
[interaction.body2.cutoff]
"A-A" = ...
"A-*" = ... # newly accepted
"*-*" = ... # newly accepted
[structure]
lattice = [[...], [...], [...]]
kd_list = [1, ..., M]
position = [[x, y, z], ...]Utility functions
Spherical harmonics
Magesty.TesseralHarmonics.Zₗₘ — Function
Zₗₘ(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: see the "Tesseral harmonics convention" entry in the Magesty.jl technical notes at https://Tomonori-Tanaka.github.io/Magesty.jl/technical_notes/.
Notes
- For repeated calls with inputs already checked, use
Zₗₘ_unsafe.
Magesty.TesseralHarmonics.Zₗₘ_unsafe — Function
Zₗₘ_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. Numerical result is identical to the unbuffered method.
See the module docstring's "Buffer requirements" section for buf sizing.
Magesty.TesseralHarmonics.∂ᵢ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.TesseralHarmonics.∂ᵢZlm_unsafe — Function
∂ᵢZlm_unsafe(l::Integer, m::Integer, uvec::AbstractVector{<:Real}) -> SVector{3,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 computations through a single _legendre_pair_unsafe! call.
See the module docstring's "Buffer requirements" section for buf sizing. When the value Zₗₘ is also needed at the same (l, m, uvec), prefer Zₗₘ_grad_unsafe, which returns both from one recursion (its gradient block mirrors this function — keep them in sync).
Rotation matrices
Magesty.RotationMatrix.rotmat2euler — Function
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: 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).
MFA spin sampling
Code-agnostic building blocks behind the exported sample_mfa_incar; see Mean-Field Sampling for the theory.
Magesty.MfaSampling.thermal_averaged_m — Function
thermal_averaged_m(τ::Real)::Float64Solve the MFA self-consistency equation $m = \coth(3m/τ) - τ/3m$ for the thermally averaged magnetization $m$ at scaled temperature τ (T/Tc).
Returns 1.0 for $τ < MIN\_TEMP$ (fully ordered) and 0.0 for $τ > MAX\_TEMP$ (fully disordered).
Magesty.MfaSampling.tau_from_magnetization — Function
tau_from_magnetization(m::Real)::Float64Invert the MFA self-consistency equation: return the scaled temperature $τ = T/Tc$ whose thermally averaged magnetization is m.
Returns 1.0 for $m ≤ 0$ (disordered) and 0.0 for $m ≥ 1$ (ordered). Magnetizations whose temperature falls outside $[MIN\_TEMP, MAX\_TEMP]$ are clamped to the ordered (0.0) or disordered (1.0) limit, which the sampler handles directly.
Magesty.MfaSampling.sample_vmf_direction — Function
sample_vmf_direction(mean_dir::SVector{3, Float64}, κ::Real)::SVector{3, Float64}Draw a unit vector on $S^2$ from the von Mises-Fisher distribution with mean direction mean_dir (assumed unit) and concentration κ ≥ 0.
Uses the exact closed-form inverse-CDF construction for $p = 3$ (Ulrich 1984, Wood 1994): the cosine to mean_dir is $w = 1 + κ^{-1}\log(u + (1-u)e^{-2κ})$ with $u ∼ U(0,1)$, combined with a uniform azimuth in the tangent plane. For $κ < KAPPA\_MIN$ the draw is isotropic.
Magesty.MfaSampling.mfa_sample — Function
mfa_sample(spin_matrix::AbstractMatrix{<:Real}, variable::AbstractString,
value::Real)::Matrix{Float64}Draw one sampled configuration from spin_matrix (3 × n_atoms) at the given control value. variable is "tau" (scaled temperature) or "m" (magnetization). Per-atom magnitudes are preserved and zero-norm columns are left untouched. For $τ < MIN\_TEMP$ the input is returned unchanged.
Magesty.MfaSampling.mfa_sweep — Function
mfa_sweep(spin_matrix::AbstractMatrix{<:Real}; variable, start, stop,
num_points, num_samples=1, randomize=false,
fixed_indices=Int[], uniform_indices=Int[]) -> Vector{Matrix{Float64}}Sample configurations from spin_matrix (3 × n_atoms) over an evenly spaced sweep of the control variable.
Keyword arguments
variable::AbstractString:"tau"(scaled temperature) or"m"(magnetization).start::Real,stop::Real,num_points::Integer: the sweep values arerange(start, stop; length = num_points).num_samples::Integer = 1: configurations drawn per sweep value.randomize::Bool = false: apply a single Haar-uniform random global rotation (quantization-axis randomization) to each drawn configuration. Uniform over all ofSO(3), so the sampled orientations are isotropic regardless of the orientationspin_matrixis written in.fixed_indices::AbstractVector{<:Integer} = Int[]: 1-based atom indices kept at their input directions (rotated by the same global rotation whenrandomize), i.e. not sampled.uniform_indices::AbstractVector{<:Integer} = Int[]: 1-based atom indices whose direction is redrawn uniformly on the sphere (the disorderedκ → 0limit) instead of from the vMF distribution, independently of the sweep value. The isotropic draw is applied after sampling and overrides it; indices also infixed_indicesare subsequently reset, sofixed_indicestakes precedence.
Returns
Vector{Matrix{Float64}}: sampled configurations in(value, sample)order (value outer), each3 × n_atomswith per-atom magnitudes preserved.
Magesty.MfaSampling.parse_atom_index_spec — Function
parse_atom_index_spec(spec::AbstractString; max_index::Integer)::Vector{Int}Parse a 1-based atom-index specification such as "1-10", "1-10,12,20-22", or "1 2 5-8" (commas and/or whitespace separate tokens; a-b and a:b are inclusive ranges). Returns sorted, unique indices. An empty spec yields Int[]. Errors on malformed tokens or indices outside 1:max_index.