API Reference

This page is generated from the docstrings of the public SHTnsKit module. Optional methods become available in your Julia session when you load the packages that activate their extension.

Calling conventions

  • Allocating transforms use operation(cfg, input...).
  • In-place transforms place outputs before inputs, for example analysis!(plan, alm_out, field) and synthesis!(plan, field_out, alm).
  • analysis(CPU(), ...) and analysis(GPU(), ...) request strict typed device dispatch; ordinary calls infer the backend from array storage.
  • Dense coefficients have shape (cfg.lmax + 1, cfg.mmax + 1). Entries with l < m are unused.
  • Batch APIs add a third, field-index dimension.
  • A configuration's norm, cs_phase, real_norm, and robert_form options apply at every public transform boundary.

See Migrating to v3.0 for changed results and Migrating to v2.0 for removed compatibility signatures and numerical changes.

Extension activation

ExtensionTrigger packages
SHTnsKitAMDGPUExtAMDGPU, GPUArrays, GPUArraysCore, KernelAbstractions
SHTnsKitAdvancedADExtChainRulesCore
SHTnsKitForwardDiffExtForwardDiff
SHTnsKitGPUExtCUDA, GPUArrays, GPUArraysCore, KernelAbstractions
SHTnsKitLoopVecExtLoopVectorization
SHTnsKitMetalExtMetal, KernelAbstractions
SHTnsKitParallelADExtChainRulesCore, MPI, PencilArrays, PencilFFTs
SHTnsKitParallelAMDGPUExtMPI, PencilArrays, PencilFFTs, AMDGPU, GPUArrays, GPUArraysCore, KernelAbstractions
SHTnsKitParallelCUDAExtMPI, PencilArrays, PencilFFTs, CUDA, GPUArrays, GPUArraysCore, KernelAbstractions
SHTnsKitParallelExtMPI, PencilArrays, PencilFFTs
SHTnsKitZygoteExtZygote

Metal loads KernelAbstractions as a dependency, so using SHTnsKit, Metal activates its extension. For setup and supported operations see GPU Acceleration. Package Architecture describes each extension's role.

Public API

SHTnsKit.GPU — Type

GPU compute device.

GPU() is vendor-neutral. A CUDA, AMDGPU, or Metal backend is inferred from an existing device array/prototype, or selected when exactly one loaded GPU adapter is functional.

source
SHTnsKit.SHTConfig — Method
SHTConfig(; lmax, mmax, mres, nlat, nlon, θ, φ, x, w, Nlm, cphi, st,
          norm, cs_phase, real_norm, robert_form,
          nlm, li, mi, nspat,
          grid_type=:gauss, phi_scale=:auto, on_the_fly=false,
          use_plm_tables=false, plm_tables=[], dplm_tables=[],
          NP_tables=[], NdP_tables=[], norm_scale_matrix=Matrix{Float64}(undef,0,0),
          _otf_scratch_P=[], _otf_scratch_dP=[], _otf_scratch_Ps=[], _otf_scratch_Pb=[], _m_order=[],
          howmany=1, spec_dist=0, south_pole_first=false,
          allow_padding=false, nlat_padded=0, spat_dist=0) -> SHTConfig

Flat-kwargs constructor that packages the grid/normalization/tables/scratch kwargs into their respective sub-structs. Keeps the call-site syntax used by create_gauss_config, create_regular_config, copy(::SHTConfig), etc. identical to the pre-restructure behaviour.

source
SHTnsKit.SHTPlan — Method
SHTPlan(cfg::SHTConfig; use_rfft=false)

Create an optimized transform plan with pre-allocated buffers and FFT plans.

This constructor performs the "planning" phase: it allocates all working memory and optimizes FFTW plans for the specific grid configuration. The resulting plan can then be reused for many transforms without additional allocations. For CPU transforms, build a new plan if you increase cfg.lmax beyond its planned degree.

Parameters:

  • cfg: SHTConfig defining the grid and spectral resolution
  • use_rfft: if true, use real-FFT along φ for scalar analysis!/synthesis!. Vector (sphtor) transforms on the plan still use the full complex buffer, so the plan adds a half-spectrum buffer and a real scratch grid to it and holds more memory than a complex-FFT plan. Requires cfg.mmax ≤ cfg.nlon÷2.
source
SHTnsKit.SHTRotation — Type
struct SHTRotation

Holds Euler angles and target sizes for rotation.

  • lmax, mmax: degrees/orders supported by the rotation.
  • α, β, γ: Euler angles (ZYZ by default) in radians.
  • conv: :ZYZ or :ZXZ convention.
source
SHTnsKit.DistTransposePlan — Method
DistTransposePlan(cfg; comm=MPI.COMM_WORLD, nlev=1, with_vector=true, array_type=Array, real_type=Float64, prototype=nothing)

Plan for transpose-based distributed transforms. This is the scalable distributed path, and the only one that runs on CUDA or ROCm storage. A PencilFFTs real FFT along longitude, followed by a latitude/order transpose, gives each rank complete latitudes for its orders. The Legendre stage then needs no further communication.

Allocate operands with allocate_spatial and allocate_spectral, then pass them to dist_analysis!, dist_synthesis!, dist_analysis_sphtor!, dist_synthesis_sphtor!, dist_analysis_qst! or dist_synthesis_qst!. Arrays from another plan are rejected, even if their sizes match.

  • nlev stacks independent fields along a trailing dimension.
  • with_vector=true builds the tables the vector and QST transforms need.
  • array_type selects the storage, for example CuArray or ROCArray. prototype takes the storage and precision from an existing PencilArray.
  • real_type is Float64 or Float32.

Configurations with robert_form are not supported. Requires using MPI, PencilArrays, PencilFFTs, plus CUDA.jl or AMDGPU.jl for a device plan. Construction and every transform are collective over comm.

plan = DistTransposePlan(cfg; comm=MPI.COMM_WORLD, nlev=2)
f = allocate_spatial(plan)      # fill this rank's block, parent(f)
alm = allocate_spectral(plan)
dist_analysis!(plan, alm, f)
dist_synthesis!(plan, f, alm)
source
SHTnsKit.LM_cplx — Method
LM_cplx(cfg::SHTConfig, l::Integer, m::Integer) -> Int

Compatibility helper that mirrors the C macro LM_cplx for mres == 1, returning the zero-based packed complex index for coefficient (l,m).

source
SHTnsKit.LM_cplx_index — Method
LM_cplx_index(lmax::Int, mmax::Int, l::Int, m::Int) -> Int

Packed complex index for coefficient (l,m) where -min(l,mmax) ≤ m ≤ min(l,mmax). Matches SHTns LM_cplx macro (assumes mres == 1).

source
SHTnsKit.LM_index — Method
LM_index(lmax::Int, mres::Int, l::Int, m::Int) -> Int

Convert 2D spherical harmonic indices (l,m) to a 1D packed array index. This implements the SHTns packing convention for efficient memory layout.

The packing scheme groups coefficients by m-order blocks, with each block containing all valid l-degrees for that m. This enables vectorized operations on modes with the same azimuthal symmetry.

Matches SHTns C macro: LM(shtns, l, m)

source
SHTnsKit.LiM_index — Method
LiM_index(lmax::Int, mres::Int, l::Int, im::Int) -> Int

Convenience function to compute packed index using reduced m-index im. This is useful when iterating over m-modes using im = 0, 1, 2, ... instead of m = 0, mres, 2*mres, ...

Equivalent to LM_index(lmax, mres, l, im*mres). Matches SHTns macro: LiM(shtns, l, im)

source
SHTnsKit.SH_Xrotate90 — Method
SH_Xrotate90(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, Rlm::AbstractVector{<:Complex})

Rotate around X-axis by 90 degrees using ZYZ equivalence: Rz(π/2)·Ry(π/2)·Rz(-π/2).

source
SHTnsKit.SH_Yrotate — Method
SH_Yrotate(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, alpha::Real, Rlm::AbstractVector{<:Complex})

Rotate a real-field SH expansion around the Y-axis by angle alpha. Uses Wigner-d mixing per l; dispatches to the general rotation engine.

source
SHTnsKit.SH_Zrotate — Method
SH_Zrotate(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, alpha::Real, Rlm::AbstractVector{<:Complex})

Rotate a real-field SH expansion around the Z-axis by angle alpha. Input and output are packed Qlm vectors (LM order, m ≥ 0). In-place supported if Rlm === Qlm.

Sign convention

R_lm = Q_lm · exp(-i m α). This is the active rotation of the field by +α about ẑ: the rotated field is g(θ, φ) = f(θ, φ - α). Equivalently, a feature at longitude φ₀ moves to φ₀ + α.

Three things pin this sign and would all break if it were flipped to +imα (which is the passive convention, f(θ, φ + α)):

  • the spatial rotation above, verified directly in test/serial/test_rotations.jl against an FFT-grid φ shift;
  • the general Wigner engine — shtns_rotation_apply_real with ZYZ(α, 0, 0) (or ZYZ(0, 0, α)) must equal this function, and it builds diag(e^{-imα}) · d(β) · diag(e^{-imγ});
  • the distributed twins dist_SH_Zrotate and every rotation rrule.
source
SHTnsKit.SH_mul_mx — Method
SH_mul_mx(cfg::SHTConfig, mx::AbstractVector{<:Real}, Qlm::AbstractVector{<:Complex}, Rlm::AbstractVector{<:Complex})

Apply a nearest-neighbor-in-l operator represented by mx to Qlm and write to Rlm. Both Qlm and Rlm are length cfg.nlm packed vectors (m≥0, SHTns LM order). mx uses the layout of mul_ct_matrix and st_dt_matrix, which for non-symmetric operators differs from SHTns's (see "Differences from SHTns" in the normalization guide).

Warning

Rlm must not alias Qlm. Each output couples the l-neighbors of Qlm, and those neighbors are overwritten by earlier iterations, so an in-place call (Rlm === Qlm) reads already-mutated values and gives wrong results. Use a separate output buffer.

source
SHTnsKit.SH_to_grad_point — Method
SH_to_grad_point(cfg::SHTConfig, DrSlm::AbstractVector{<:Complex}, Slm::AbstractVector{<:Complex}, cost::Real, phi::Real)
    -> vr, vt, vp

Evaluate the gradient of a scalar field at a point. DrSlm supplies the radial derivative spectrum and Slm supplies the tangential gradient.

source
SHTnsKit.SH_to_lat — Method
SH_to_lat(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, cost::Real;
          nphi::Int=cfg.nlon, ltr::Int=cfg.lmax, mtr::Int=cfg.mmax) -> Vector{<:Real}

Evaluate a real field along a latitude (fixed cosθ = cost) at nphi equispaced longitudes. Uses orthonormal harmonics and packed real coefficients Qlm (LM order).

source
SHTnsKit.SH_to_lat_cplx — Method
SH_to_lat_cplx(cfg::SHTConfig, alm_packed::AbstractVector{<:Complex}, cost::Real; nphi::Int=cfg.nlon, ltr::Int=cfg.lmax) -> Vector{<:Complex}

Evaluate a complex field along a latitude using packed LM_cplx coefficients.

source
SHTnsKit.SHqst_to_lat — Method
SHqst_to_lat(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, Slm::AbstractVector{<:Complex}, Tlm::AbstractVector{<:Complex}, cost::Real;
             nphi::Int=cfg.nlon, ltr::Int=cfg.lmax, mtr::Int=cfg.mmax) -> (Vr, Vt, Vp)

Evaluate 3D field along latitude (cosθ = cost) at nphi longitudes from packed real spectra. Inputs Qlm, Slm, Tlm are all packed (LM order) vectors for each component.

source
SHTnsKit.SHqst_to_point — Method
SHqst_to_point(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, Slm::AbstractVector{<:Complex}, Tlm::AbstractVector{<:Complex}, cost::Real, phi::Real)
    -> vr, vt, vp

Evaluate 3D field at a single point using packed real spectra.

source
SHTnsKit.allocate_padded_spatial — Function
allocate_padded_spatial(cfg::SHTConfig, T::Type=Float64) -> Array{T}

Allocate a spatial array with proper padding if enabled.

Returns a 2D array of size (nlatpadded, nlon) where nlatpadded >= nlat. The first nlat rows contain the actual data; remaining rows are padding.

Example

cfg = create_gauss_config(64, 66)
set_allow_padding!(cfg)
field = allocate_padded_spatial(cfg)          # (nlat_padded, nlon)
copy_to_padded!(field, data, cfg)
alm = analysis(cfg, spatial_view(cfg, field)) # transforms need exactly nlat rows

The transforms require an array with exactly nlat rows, so a padded buffer must go through spatial_view (or an equivalent view(field, 1:cfg.nlat, :)). The view keeps the padded column stride, preserving what the padding is for.

source
SHTnsKit.allocate_padded_spatial_batch — Function
allocate_padded_spatial_batch(cfg::SHTConfig, nfields::Int, T::Type=Float64) -> Array{T}

Allocate spatial arrays for batch transforms with proper padding if enabled.

Returns a 3D array of size (nlat_padded, nlon, nfields).

source
SHTnsKit.allocate_spatial — Method
allocate_spatial(plan::DistTransposePlan) -> PencilArray

Allocate an uninitialized real spatial PencilArray for plan. Its global size is (nlon, nlat, nlev): longitude comes first, unlike the (nlat, nlon) grids of the cfg-based functions. Latitude is distributed, and the storage follows the plan's array_type.

Requires using MPI, PencilArrays, PencilFFTs.

source
SHTnsKit.allocate_spectral — Method
allocate_spectral(plan::DistTransposePlan) -> PencilArray

Allocate an uninitialized complex spectral PencilArray for plan. Its global size is (lmax+1, nlon÷2+1, nlev), with the second (order) dimension distributed. That dimension indexes the real-FFT bins m = 0:nlon÷2. Only bins with m ≤ mmax and m % mres == 0 hold coefficients: orders plan.m_local, stored in the local columns plan.m_slots. Analysis zeroes the other columns and synthesis ignores them.

Requires using MPI, PencilArrays, PencilFFTs.

source
SHTnsKit.analysis! — Method
analysis!(cfg::SHTConfig, alm_out::AbstractMatrix, f::AbstractMatrix)

In-place forward transform. Writes coefficients into alm_out, which must have size (lmax+1, mmax+1) and may overlap f.

source
SHTnsKit.analysis! — Method
analysis!(plan::SHTPlan, alm_out::AbstractMatrix, f::AbstractMatrix)

In-place forward scalar SHT writing coefficients into alm_out.

source
SHTnsKit.analysis — Method
analysis(cfg::SHTConfig, f::AbstractMatrix) -> Matrix{ComplexF64}

Forward transform on Gauss-Legendre x equiangular grid. Returns coefficients alm[l+1, m+1] in the normalization, real-normalization, and phase convention configured by cfg.

Parallelizes over m-modes using static scheduling for consistent performance.

source
SHTnsKit.analysis_axisym — Method
analysis_axisym(cfg, Vr) -> Vector{ComplexF64}

Axisymmetric (m=0) transform from Gauss latitudes to degree-only coefficients. Input Vr should contain values at Gauss latitudes for a specific longitude mode. Returns coefficients Q_l for l = 0..lmax.

source
SHTnsKit.analysis_batch! — Method
analysis_batch!(cfg::SHTConfig, alm_out::AbstractArray{<:Complex,3},
                fields::AbstractArray{<:Real,3})

In-place batch forward transform.

source
SHTnsKit.analysis_batch — Method
analysis_batch(cfg::SHTConfig, fields::AbstractArray{<:Real,3}) -> Array{ComplexF64,3}

Batch forward transform for multiple scalar fields.

Arguments

  • cfg: SHTConfig with batch size configured
  • fields: 3D array of shape (nlat, nlon, nfields) containing spatial data

Returns

  • 3D array of shape (lmax+1, mmax+1, nfields) with spectral coefficients

Performance

Batch processing is more efficient than processing fields individually because:

  1. Legendre polynomials are computed once and reused across all fields
  2. FFT plans are shared
  3. Better cache utilization from contiguous memory access patterns
source
SHTnsKit.analysis_packed — Method
analysis_packed(cfg, Vr_flat::AbstractVector{<:Real}) -> Vector{ComplexF64}

Packed scalar analysis from flattened grid values (length nlat*nlon) to Qlm (LM order).

source
SHTnsKit.analysis_packed_cplx — Method
analysis_packed_cplx(cfg::SHTConfig, z::AbstractMatrix{<:Complex}) -> Vector{ComplexF64}

Analyze a complex nlat × nlon spatial field into packed complex coefficients in LM_cplx order, which stores both signs of m. Requires cfg.mres == 1.

source
SHTnsKit.analysis_packed_cplx_l — Method
analysis_packed_cplx_l(cfg, z, ltr)

Analyze a complex spatial field into full LM_cplx storage while computing only degrees l ≤ ltr; entries above the limit are zero.

source
SHTnsKit.analysis_packed_l — Method
analysis_packed_l(cfg::SHTConfig, Vr::AbstractVector{<:Real}, ltr::Integer) -> Vector{ComplexF64}

Scalar analysis truncated to degrees l ≤ ltr. The returned packed coefficient vector has length cfg.nlm; coefficients with l > ltr are set to zero.

source
SHTnsKit.analysis_packed_ml — Method
analysis_packed_ml(cfg, mval, Vr_m, ltr) -> Vector{<:Complex}

Transform spatial field for one stored azimuthal order to spherical harmonic coefficients. mval is the zero-based stored-order index, so the physical order is m = mval * cfg.mres. Vr_m contains complex spatial values for that mode. Returns coefficients Q_l for degrees l = m..ltr.

source
SHTnsKit.analysis_qst! — Function
analysis_qst!(plan::DistQstPlan, Qlm_out, Slm_out, Tlm_out, Vrθφ, Vtθφ, Vpθφ) -> (Qlm_out, Slm_out, Tlm_out)

Planned distributed analysis of a 3D vector field with radial Vrθφ, colatitude Vtθφ and longitude Vpθφ components, given as PencilArrays. It writes the radial Qlm, spheroidal Slm and toroidal Tlm coefficients into the output matrices: dense (lmax+1, mmax+1) and filled identically on every rank. Build the plan with DistQstPlan(cfg, prototype_θφ; use_rfft=false) for fields laid out like prototype_θφ; it reuses its buffers across calls. This is the same operation as dist_analysis_qst! with that plan.

Only DistQstPlan methods exist. They are defined when using MPI, PencilArrays, PencilFFTs loads the parallel extension, and they need CPU storage. The call is collective over the plan's communicator.

source
SHTnsKit.analysis_qst — Method
analysis_qst(cfg, Vr, Vt, Vp) -> (Qlm, Slm, Tlm)

Transform 3D spatial vector field to QST spectral coefficients. Input: radial (Vr), colatitude (Vt), and azimuthal (Vp) components. All three coefficient arrays take the precision promoted across the inputs, as in analysis_qst_batch.

source
SHTnsKit.analysis_qst_batch — Method
analysis_qst_batch(cfg::SHTConfig, Vr_batch::AbstractArray{<:Real,3},
                   Vt_batch::AbstractArray{<:Real,3}, Vp_batch::AbstractArray{<:Real,3})

Batch QST analysis for multiple 3D vector fields.

Returns

  • (Qlm_batch, Slm_batch, Tlm_batch): Tuple of 3D arrays with Q, S, T coefficients
source
SHTnsKit.analysis_qst_l — Method
analysis_qst_l(cfg, Vr, Vt, Vp, ltr) -> (Qlm, Slm, Tlm)

Degree-limited version of analysis_qst, computing coefficients only up to degree ltr.

source
SHTnsKit.analysis_qst_ml — Method
analysis_qst_ml(cfg, mval, Vr_m, Vt_m, Vp_m, ltr) -> (Ql, Sl, Tl)

Mode-limited transform for specific azimuthal mode mval.

source
SHTnsKit.analysis_sphtor! — Method
analysis_sphtor!(plan::SHTPlan, Slm_out::AbstractMatrix, Tlm_out::AbstractMatrix, Vt::AbstractMatrix, Vp::AbstractMatrix)

In-place vector analysis. Accumulates Slm/Tlm into preallocated outputs. Uses a two-pass strategy over φ FFTs to avoid extra buffers.

source
SHTnsKit.analysis_sphtor — Method
analysis_sphtor(cfg, Vt, Vp) -> (Slm, Tlm)

Transform horizontal vector field components to spheroidal/toroidal coefficients.

Robert-form analysis with stored m=1 modes requires a grid without nonzero-weight pole nodes. Use Gauss–Legendre, pole-free regular, or Driscoll–Healy grids; pole-inclusive Clenshaw–Curtis grids throw ArgumentError.

source
SHTnsKit.analysis_sphtor_batch — Method
analysis_sphtor_batch(cfg::SHTConfig, Vt_batch::AbstractArray{<:Real,3},
                      Vp_batch::AbstractArray{<:Real,3})

Batch spheroidal-toroidal analysis for multiple vector fields.

Arguments

  • cfg: SHTConfig
  • Vt_batch: 3D array (nlat, nlon, nfields) of theta components
  • Vp_batch: 3D array (nlat, nlon, nfields) of phi components

Returns

  • (Slm_batch, Tlm_batch): Tuple of 3D arrays (lmax+1, mmax+1, nfields) containing spheroidal and toroidal coefficients
source
SHTnsKit.analysis_sphtor_cplx — Method
analysis_sphtor_cplx(cfg, Vt, Vp) -> (Slm, Tlm)

Transform complex horizontal vector components to spheroidal/toroidal coefficients.

source
SHTnsKit.analysis_sphtor_l — Method
analysis_sphtor_l(cfg, Vt, Vp, ltr) -> (Slm, Tlm)

Degree-limited version of analysis_sphtor. It computes the spheroidal and toroidal coefficients up to degree ltr and leaves the higher degrees zero.

source
SHTnsKit.analysis_sphtor_ml — Method
analysis_sphtor_ml(cfg, mval, Vt_m, Vp_m, ltr) -> (Sl, Tl)

Mode-limited transform for a single azimuthal order mval (named mval, not im, so it cannot shadow Julia's imaginary unit — see synthesis_sphtor_ml). Input vectors contain Fourier coefficients for mode m at all latitudes. Implements the proper spheroidal-toroidal decomposition using the adjoint of the synthesis formulas: Vθ = ∂S/∂θ - (im/sinθ) * T Vφ = (im/sinθ) * S + ∂T/∂θ

source
SHTnsKit.analysis_turbo — Method
analysis_turbo(cfg, f::AbstractMatrix) -> Matrix

analysis with LoopVectorization-optimized CPU loops. The arguments and result are the same.

Requires using LoopVectorization.

source
SHTnsKit.benchmark_turbo_vs_simd — Method
benchmark_turbo_vs_simd(cfg; trials=3) -> NamedTuple

Time analysis and synthesis against analysis_turbo and synthesis_turbo on random data, keeping the best of trials runs (in seconds). Returns the four timings, plus analysis_speedup, synthesis_speedup, and speedup, which repeats the analysis speedup.

Requires using LoopVectorization.

source
SHTnsKit.build_li_mi — Method
build_li_mi(lmax::Int, mmax::Int, mres::Int)

Build lookup arrays mapping packed indices to spherical harmonic (l,m) values. These arrays enable efficient iteration over spherical harmonic modes when working with packed coefficient arrays.

Returns (li, mi) where li[k] and mi[k] give the degree and order for the k-th packed coefficient.

source
SHTnsKit.check_gpu_memory — Method
check_gpu_memory(required_bytes::Int) -> Bool

Return whether the active CUDA device has at least required_bytes free. It returns false with a warning when memory is short, and false when CUDA is not functional.

Requires using CUDA.

source
SHTnsKit.compute_optimal_padding — Method
compute_optimal_padding(nlat::Int, nlon::Int; sizeof_real::Int=8) -> Int

Compute the optimal padding to add between latitude lines to avoid cache bank conflicts. This mimics the SHTns C library's padding strategy.

Arguments

  • nlat: Number of latitude points
  • nlon: Number of longitude points (phi)
  • sizeof_real: Size of real number in bytes (default 8 for Float64)

Returns

The number of extra elements to add per latitude line (padding amount).

Details

The padding strategy aims to:

  1. Align memory on 32-byte or 64-byte boundaries
  2. Avoid 8KB cache bank conflicts
  3. Avoid L2 cache bank/channel conflicts (especially important for AMD GPUs)

This is most beneficial for:

  • Large transforms where cache effects matter
  • Multi-threaded transforms
  • GPU computing
source
SHTnsKit.copy_from_padded! — Method
copy_from_padded!(dest::AbstractMatrix, src::AbstractMatrix, cfg::SHTConfig)

Copy data from a padded spatial array to a contiguous spatial array.

source
SHTnsKit.copy_to_padded! — Method
copy_to_padded!(dest::AbstractMatrix, src::AbstractMatrix, cfg::SHTConfig)

Copy data from a contiguous spatial array to a padded spatial array.

source
SHTnsKit.create_config — Method
create_config(lmax::Int; mmax=lmax, mres=1, nlat=lmax+2,
               nlon=max(2*lmax+1,4),
               norm::Symbol=:orthonormal, cs_phase::Bool=true,
               real_norm::Bool=false, robert_form::Bool=false,
               grid_type::Symbol=:gauss) -> SHTConfig

Compatibility wrapper for configuration creation used in some docs/snippets. Supports Gauss–Legendre (grid_type = :gauss), regular equiangular (grid_type = :regular or :regular_poles), and Driscoll-Healy (grid_type = :driscoll_healy) grids, forwarding to the appropriate creator. nlat/nlon defaults are adjusted to satisfy accuracy constraints for the chosen grid: the default nlat becomes 2lmax+1 (at least 2) for equiangular grids and 2(lmax+1) for Driscoll-Healy, the smallest latitude counts for which analysis exactly inverts synthesis on those grids. The default is recognised by its value, so passing nlat = lmax+2 for these grids selects the same count; use create_regular_config for a grid of exactly lmax+2 latitudes.

source
SHTnsKit.create_config — Method
create_config(::Type{T}, lmax::Int, nlat::Int, mres::Int=1; kwargs...) -> SHTConfig

Compatibility method that ignores the element type T and calls create_config. Provided to match older example signatures like create_config(Float64, 20, 22, 1).

source
SHTnsKit.create_gauss_config — Method
create_gauss_config(lmax::Int, nlat::Int; mmax::Int=lmax, nlon::Int=_default_nlon(lmax)) -> SHTConfig

Create a Gauss–Legendre based SHT configuration. Constraints:

  • nlat ≥ lmax+1 for exactness up to lmax in θ integration.
  • nlon ≥ 2*mmax+1 to resolve azimuthal orders up to mmax.
source
SHTnsKit.create_gauss_config_spf — Method
create_gauss_config_spf(lmax::Int, nlat::Int; kwargs...) -> SHTConfig

Create a Gauss-Legendre configuration with south-pole-first latitude ordering.

This is equivalent to calling create_gauss_config followed by set_south_pole_first!. All keyword arguments are passed to create_gauss_config.

Example

# Create a south-pole-first configuration
cfg = create_gauss_config_spf(32, 34)
is_south_pole_first(cfg)  # true

See also: create_gauss_config, set_south_pole_first!

source
SHTnsKit.create_gauss_fly_config — Method
create_gauss_fly_config(lmax::Int, nlat::Int; kwargs...) -> SHTConfig

Create a Gauss–Legendre configuration with on-the-fly Legendre polynomial computation.

This mode computes Legendre polynomials during each transform instead of using precomputed tables. Benefits:

  • Lower memory usage: No storage for P_l^m tables (saves O(lmax² × nlat) memory)
  • Better for large lmax: When lmax is large, tables become memory-intensive
  • Good cache behavior: On modern CPUs, on-the-fly computation can be faster due to better cache utilization

Trade-offs:

  • May be slower for repeated transforms with small lmax
  • No speedup from table precomputation

This mirrors the sht_gauss_fly mode in SHTns C library.

Arguments

Same as create_gauss_config.

Example

# For large lmax, on-the-fly mode saves significant memory
cfg = create_gauss_fly_config(1024, 1026)

# Performs transform computing Legendre polynomials on-the-fly
alm = analysis(cfg, field)

See also: create_gauss_config, set_on_the_fly!, set_use_tables!

source
SHTnsKit.create_regular_config — Method
create_regular_config(lmax::Int, nlat::Int; mmax::Int=lmax, mres::Int=1,
                      nlon::Int=_default_nlon(lmax), norm::Symbol=:orthonormal,
                      cs_phase::Bool=true, real_norm::Bool=false,
                      robert_form::Bool=false, include_poles::Bool=false,
                      precompute_plm::Bool=true, use_dh_weights::Bool=false) -> SHTConfig

Create an equiangular (regular) grid configuration. Regular grids use Fejér's first rule on θ = (i+0.5)π/nlat nodes by default; set include_poles=true to use pole-inclusive Clenshaw–Curtis nodes and weights. By default associated Legendre tables are precomputed, which mirrors SHTns' regular-grid behaviour and improves performance. Tables that would exceed 2 GiB (see estimate_table_memory) are skipped and Legendre rows computed on the fly; call prepare_plm_tables! to build them regardless.

Needs `nlat ≥ 2*lmax + 1` to be exact

Fejér and Clenshaw–Curtis rules with nlat nodes integrate polynomials in x = cosθ through degree nlat - 1 exactly, and analysis integrates a product of two degree-lmax Legendre functions — degree 2*lmax. So these grids are exact only from nlat = 2*lmax + 1 upward, whereas Gauss–Legendre needs just nlat = lmax + 1.

Below that threshold analysis(cfg, synthesis(cfg, alm)) does not return alm. Measured relative error at lmax = 8:

nlat:regular:regular_poles
107.2e-23.6e-1
141.3e-27.1e-3
164.2e-31.3e-3
17 (2*lmax+1)7e-167e-16

Nothing warns at run time, so size the grid deliberately: pass nlat ≥ 2*lmax + 1 here, or use create_gauss_config (exact at nlat = lmax + 1) or use_dh_weights=true (exact at nlat = 2*(lmax+1)).

Driscoll-Healy Quadrature

Set use_dh_weights=true to use Driscoll-Healy quadrature for exact spherical harmonic transforms. This requires:

  • include_poles=true
  • nlat = 2*(lmax+1) for exactness up to degree lmax
  • nlat must be even

The DH grid uses θ = πj/n for j=0,...,n-1 (includes north pole, excludes south pole) and provides exact quadrature via specially computed weights.

Reference: Driscoll & Healy (1994), "Computing Fourier transforms and convolutions on the 2-sphere", Adv. Appl. Math., 15, 202-250.

source
SHTnsKit.create_spatial_pencil — Method
create_spatial_pencil(cfg; comm=MPI.COMM_WORLD) -> Pencil

Return the Pencil for distributed spatial fields. Its global size is (nlat, nlon), decomposed along latitude (dimension 1). Prefer it to Pencil((nlat, nlon), comm), which splits longitude; that decomposition does not scale for these transforms.

Requires using MPI, PencilArrays, PencilFFTs. Call it on every rank of comm.

source
SHTnsKit.create_spectral_pencil — Method
create_spectral_pencil(cfg; comm=MPI.COMM_WORLD) -> Pencil

Return the Pencil for distributed spectral coefficients. Its global size is (lmax+1, mmax+1), decomposed along m (dimension 2), so each rank holds every degree of its orders.

Requires using MPI, PencilArrays, PencilFFTs. Call it on every rank of comm.

source
SHTnsKit.destroy_config — Method
destroy_config(cfg::SHTConfig)

No-op placeholder for API symmetry with libraries that require explicit teardown.

source
SHTnsKit.dist_SH_Xrotate90_packed — Method
dist_SH_Xrotate90_packed(cfg, Qlm::AbstractVector{<:Complex}; prototype_lm::PencilArray) -> Vector

Rotate replicated packed LM-layout coefficients by 90° about the x axis; the arguments are as for dist_SH_Zrotate_packed. Needs cfg.mres == 1 and cfg.mmax == cfg.lmax.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_lm. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SH_Yrotate_packed — Method
dist_SH_Yrotate_packed(cfg, Qlm::AbstractVector{<:Complex}, β; prototype_lm::PencilArray) -> Vector

Rotate replicated packed LM-layout coefficients by β about the y axis; the arguments are as for dist_SH_Zrotate_packed. Needs cfg.mres == 1, and also cfg.mmax == cfg.lmax unless β is a multiple of π.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_lm. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SH_Zrotate_packed — Method
dist_SH_Zrotate_packed(cfg, Qlm::AbstractVector{<:Complex}, α; prototype_lm::PencilArray) -> Vector

Rotate packed LM-layout coefficients by α about the z axis. Qlm has length cfg.nlm and is replicated on every rank, and every rank gets a new rotated vector. prototype_lm is any PencilArray on the communicator to use; it supplies the communicator for the collective argument checks.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_lm. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SH_rotate_euler — Method
dist_SH_rotate_euler(cfg, input::PencilArray, α, β, γ, output::PencilArray) -> output

Rotate distributed spectral coefficients by the ZYZ Euler angles: α about z, then β about y, then γ about z. input and output are spectral PencilArrays with the same layout. Needs cfg.mres == 1. Unless β is a multiple of π it also needs cfg.mmax == cfg.lmax, because other angles mix in orders above mmax.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of input. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SH_to_lat — Method
dist_SH_to_lat(cfg, Alm::PencilArray, cost; nphi=cfg.nlon, ltr=cfg.lmax, mtr=cfg.mmax, real_output=true) -> Vector

Evaluate the field with spectral PencilArray coefficients Alm, in cfg's convention, at nphi equally spaced longitudes on the latitude where cos(θ) = cost. The expansion is truncated to degrees ≤ ltr and orders ≤ mtr. Every rank receives the full vector.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Alm. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SH_to_point — Method
dist_SH_to_point(cfg, Alm::PencilArray, cost, phi) -> Real

Evaluate a real field, given by spectral PencilArray coefficients in cfg's convention, at the point where cos(θ) = cost and the longitude is phi. Every rank receives the value.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Alm. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SHqst_to_lat — Method
dist_SHqst_to_lat(cfg, Q::PencilArray, S::PencilArray, T::PencilArray, cost; nphi=cfg.nlon, ltr=cfg.lmax, mtr=cfg.mmax) -> (Vr, Vt, Vp)

Evaluate a 3D vector field at nphi equally spaced longitudes on the latitude where cos(θ) = cost. The field is given by radial Q, spheroidal S and toroidal T spectral PencilArrays. Every rank receives the three component vectors.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Q. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_SHqst_to_point — Method
dist_SHqst_to_point(cfg, Q::PencilArray, S::PencilArray, T::PencilArray, cost, phi) -> (vr, vt, vp)

Evaluate a 3D vector field at one point, where cos(θ) = cost and the longitude is phi. The field is given by radial Q, spheroidal S and toroidal T spectral PencilArrays. Every rank receives the radial, colatitude and longitude components.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Q. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_analysis! — Method
dist_analysis!(plan::DistAnalysisPlan, Alm_out::AbstractMatrix, fθφ::PencilArray) -> Alm_out
dist_analysis!(plan::DistTransposePlan, Alm::PencilArray, f::PencilArray) -> Alm

Planned distributed scalar analysis.

  • DistAnalysisPlan(cfg, prototype_θφ; use_rfft=false) serves fields laid out like prototype_θφ. Each call writes the dense coefficients, replicated on every rank, into Alm_out and reuses the plan's buffers. It needs CPU storage.
  • With a DistTransposePlan, f and Alm must come from allocate_spatial and allocate_spectral of the same plan, and the coefficients stay m-distributed. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_analysis — Method
dist_analysis(cfg, fθφ::PencilArray; use_rfft=false, use_packed_storage=false) -> Matrix

Spherical harmonic analysis of a distributed scalar field. fθφ holds the (nlat, nlon) grid as a PencilArray, best decomposed along latitude (see create_spatial_array). Returns the dense (lmax+1, mmax+1) coefficient matrix in cfg's convention, replicated on every rank. With use_packed_storage=true the same coefficients come packed in LM order, as a cfg.nlm vector. analysis(cfg, fθφ) returns an m-distributed spectral PencilArray instead.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of fθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError; use a DistTransposePlan for device storage.

source
SHTnsKit.dist_analysis_packed — Method
dist_analysis_packed(cfg, fθφ::PencilArray; ltr=cfg.lmax, use_rfft=false) -> Vector

Distributed analysis into the packed LM layout of analysis_packed: a cfg.nlm vector, replicated on every rank. Degrees above ltr are zero.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of fθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_analysis_packed_cplx — Method
dist_analysis_packed_cplx(cfg, z::PencilArray) -> Vector

Analysis of a complex-valued distributed field into the complex packed layout (LM_cplx_index order, both signs of m), replicated on every rank. Needs cfg.mres == 1.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of z. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_analysis_qst! — Method
dist_analysis_qst!(plan::DistQstPlan, Qlm_out, Slm_out, Tlm_out, Vrθφ, Vtθφ, Vpθφ) -> (Qlm_out, Slm_out, Tlm_out)
dist_analysis_qst!(plan::DistTransposePlan, Qlm, Slm, Tlm, Vr, Vt, Vp) -> (Qlm, Slm, Tlm)

Planned analysis of a distributed 3D vector field into radial Qlm, spheroidal Slm and toroidal Tlm coefficients.

  • DistQstPlan(cfg, prototype_θφ; use_rfft=false) writes dense coefficients, replicated on every rank, into the three output matrices. It needs CPU storage. analysis_qst! is the same operation.
  • With a DistTransposePlan built with with_vector=true, all six arrays come from allocate_spatial and allocate_spectral of the plan and must be distinct. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_analysis_qst — Method
dist_analysis_qst(cfg, Vrθφ::PencilArray, Vtθφ::PencilArray, Vpθφ::PencilArray; use_rfft=false) -> (Qlm, Slm, Tlm)

Analysis of a distributed 3D vector field. The radial component Vrθφ gives the coefficients Qlm; the colatitude and longitude components give the spheroidal Slm and toroidal Tlm coefficients. Returns dense (lmax+1, mmax+1) matrices, replicated on every rank.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Vrθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError; use a DistTransposePlan.

source
SHTnsKit.dist_analysis_sphtor! — Method
dist_analysis_sphtor!(plan::DistSphtorPlan, Slm_out, Tlm_out, Vtθφ, Vpθφ) -> (Slm_out, Tlm_out)
dist_analysis_sphtor!(plan::DistTransposePlan, Slm, Tlm, Vt, Vp) -> (Slm, Tlm)

Planned spheroidal/toroidal analysis of a distributed tangent vector field.

  • DistSphtorPlan(cfg, prototype_θφ; use_rfft=false) writes dense coefficients, replicated on every rank, into the matrices Slm_out and Tlm_out. It needs CPU storage.
  • With a DistTransposePlan built with with_vector=true, all four arrays come from allocate_spatial and allocate_spectral of the plan. The outputs must be distinct arrays; the read-only inputs may be the same array. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_analysis_sphtor — Method
dist_analysis_sphtor(cfg, Vtθφ::PencilArray, Vpθφ::PencilArray; use_rfft=false) -> (Slm, Tlm)

Spheroidal/toroidal analysis of a distributed tangent vector field, given by its colatitude (Vtθφ) and longitude (Vpθφ) components on the (nlat, nlon) grid. Returns dense (lmax+1, mmax+1) matrices Slm and Tlm, replicated on every rank. analysis_sphtor(cfg, Vtθφ, Vpθφ) returns spectral PencilArrays instead.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Vtθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError; use a DistTransposePlan.

source
SHTnsKit.dist_scalar_laplacian! — Method
dist_scalar_laplacian!(cfg, outθφ::PencilArray, inθφ::PencilArray; use_rfft=false, real_output=true) -> outθφ

Write the surface Laplacian of inθφ into outθφ. outθφ is a PencilArray with the same layout, and its element type must match the output: real when real_output=true.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of inθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_scalar_laplacian — Method
dist_scalar_laplacian(cfg, fθφ::PencilArray; prototype_θφ=fθφ, use_rfft=false, real_output=true) -> Matrix

Surface Laplacian of a distributed scalar field: analyse, scale degree l by -l(l+1), and synthesize. Returns this rank's block as a plain Matrix, with the local size of prototype_θφ. To write into a PencilArray, use dist_scalar_laplacian!.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of fθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_scalar_roundtrip! — Method
dist_scalar_roundtrip!(cfg, fθφ::PencilArray) -> (rel_local, rel_global)

Round-trip diagnostic: analyse fθφ with dist_analysis, synthesize it back, and return the relative L2 error on this rank and over all ranks. fθφ is not modified. The error is at round-off level only for band-limited fields, with degrees up to cfg.lmax.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of fθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_spatial_divergence — Method
dist_spatial_divergence(cfg, Vtθφ::PencilArray, Vpθφ::PencilArray; prototype_θφ=Vtθφ, use_rfft=false, real_output=true) -> Matrix

Horizontal divergence ∇·V of a distributed tangent vector field, computed spectrally from its spheroidal part. Returns this rank's block as a plain Matrix, with the local size of prototype_θφ.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Vtθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_spatial_vorticity — Method
dist_spatial_vorticity(cfg, Vtθφ::PencilArray, Vpθφ::PencilArray; prototype_θφ=Vtθφ, use_rfft=false, real_output=true) -> Matrix

Radial vorticity r̂·(∇×V) of a distributed tangent vector field, computed spectrally from its toroidal part. Returns this rank's block as a plain Matrix, with the local size of prototype_θφ.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Vtθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.dist_synthesis! — Method
dist_synthesis!(plan::DistPlan, fθφ_out::PencilArray, Alm::PencilArray; real_output=true) -> fθφ_out
dist_synthesis!(plan::DistTransposePlan, f::PencilArray, Alm::PencilArray) -> f

Planned distributed scalar synthesis.

  • DistPlan(cfg, prototype_θφ; use_rfft=false) synthesizes from the spectral PencilArray Alm into fθφ_out, which is laid out like prototype_θφ. It needs CPU storage.
  • With a DistTransposePlan, Alm and f must come from allocate_spectral and allocate_spatial of the same plan. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_synthesis — Method
dist_synthesis(cfg, Alm; prototype_θφ::PencilArray, real_output=true, use_rfft=false) -> Matrix

Synthesize a distributed scalar field from coefficients Alm in cfg's convention. Alm is either a dense (lmax+1, mmax+1) matrix identical on every rank, or a spectral PencilArray (see create_spectral_array). Returns this rank's block of the field as a plain Matrix, with the local size of prototype_θφ; it is complex when real_output=false. For a spectral PencilArray, synthesis(cfg, Alm; prototype_θφ) returns a PencilArray instead.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_θφ. CUDA- and ROCm-backed storage raises BackendUnavailableError; use a DistTransposePlan.

source
SHTnsKit.dist_synthesis_packed — Method
dist_synthesis_packed(cfg, Qlm::AbstractVector; prototype_θφ::PencilArray, real_output=true, ltr=cfg.lmax) -> Matrix

Synthesize a distributed field from packed LM-layout coefficients of length cfg.nlm, which must be identical on every rank. Degrees above ltr are ignored. Returns this rank's block as a plain Matrix, with the local size of prototype_θφ.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_θφ. CUDA- and ROCm-backed storage raises BackendUnavailableError.

source
SHTnsKit.dist_synthesis_packed_cplx — Method
dist_synthesis_packed_cplx(cfg, alm::AbstractVector; prototype_θφ::PencilArray) -> Matrix

Inverse of dist_analysis_packed_cplx: synthesize a complex field from coefficients in the complex packed layout, which must be identical on every rank. Returns this rank's complex block as a plain Matrix, with the local size of prototype_θφ. Needs cfg.mres == 1.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_θφ. CUDA- and ROCm-backed storage raises BackendUnavailableError.

source
SHTnsKit.dist_synthesis_qst! — Method
dist_synthesis_qst!(plan::DistQstPlan, Vrθφ_out, Vtθφ_out, Vpθφ_out, Qlm, Slm, Tlm; real_output=true) -> (Vrθφ_out, Vtθφ_out, Vpθφ_out)
dist_synthesis_qst!(plan::DistTransposePlan, Vr, Vt, Vp, Qlm, Slm, Tlm) -> (Vr, Vt, Vp)

Planned synthesis of a distributed 3D vector field from Qlm, Slm and Tlm.

  • DistQstPlan(cfg, prototype_θφ; use_rfft=false) takes dense coefficient matrices, identical on every rank, and writes the three components into the output PencilArrays. It needs CPU storage. synthesis_qst! is the same operation.
  • With a DistTransposePlan built with with_vector=true, all six arrays come from allocate_spatial and allocate_spectral of the plan and must be distinct. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_synthesis_qst — Method
dist_synthesis_qst(cfg, Qlm, Slm, Tlm; prototype_θφ::PencilArray, real_output=true, use_rfft=false) -> (Vr, Vt, Vp)

Synthesize the radial, colatitude and longitude components of a 3D vector field from Qlm, Slm and Tlm. The coefficients are dense matrices identical on every rank, or spectral PencilArrays. Returns this rank's block of each component as a plain Matrix, with the local size of prototype_θφ.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_θφ. CUDA- and ROCm-backed storage raises BackendUnavailableError; use a DistTransposePlan.

source
SHTnsKit.dist_synthesis_sphtor! — Method
dist_synthesis_sphtor!(plan::DistSphtorPlan, Vtθφ_out, Vpθφ_out, Slm, Tlm; real_output=true) -> (Vtθφ_out, Vpθφ_out)
dist_synthesis_sphtor!(plan::DistTransposePlan, Vt, Vp, Slm, Tlm) -> (Vt, Vp)

Planned synthesis of a distributed tangent vector field from spheroidal and toroidal coefficients.

  • DistSphtorPlan(cfg, prototype_θφ; use_rfft=false) takes dense Slm and Tlm matrices, identical on every rank, and writes the components into the PencilArrays Vtθφ_out and Vpθφ_out. It needs CPU storage.
  • With a DistTransposePlan built with with_vector=true, all four arrays come from allocate_spatial and allocate_spectral of the plan. The outputs must be distinct arrays; Slm and Tlm may be the same array. This is the form that runs on CUDA and ROCm storage.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the plan's communicator.

source
SHTnsKit.dist_synthesis_sphtor — Method
dist_synthesis_sphtor(cfg, Slm, Tlm; prototype_θφ::PencilArray, real_output=true, use_rfft=false) -> (Vt, Vp)

Synthesize the colatitude and longitude components of a tangent vector field from spheroidal and toroidal coefficients. The coefficients are dense matrices identical on every rank, or spectral PencilArrays. Returns this rank's block of each component as a plain Matrix, with the local size of prototype_θφ.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of prototype_θφ. CUDA- and ROCm-backed storage raises BackendUnavailableError; use a DistTransposePlan.

source
SHTnsKit.dist_vector_roundtrip! — Method
dist_vector_roundtrip!(cfg, Vtθφ::PencilArray, Vpθφ::PencilArray) -> ((rel_local, rel_global), (rel_local, rel_global))

Vector counterpart of dist_scalar_roundtrip!. It runs a round trip through dist_analysis_sphtor and dist_synthesis_sphtor and returns the relative L2 errors of the colatitude and longitude components. The inputs are not modified.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Vtθφ. CUDA- and ROCm-backed pencils raise BackendUnavailableError.

source
SHTnsKit.divergence_from_spheroidal! — Method
divergence_from_spheroidal!(cfg, δ, Slm) -> δ

In-place form of divergence_from_spheroidal. Writes the divergence coefficients into δ, which may be Slm itself.

source
SHTnsKit.divergence_from_spheroidal — Method
divergence_from_spheroidal(cfg, Slm) -> Matrix

Return divergence spectral coefficients δlm corresponding to spheroidal modes via δlm = −l(l+1) Slm (`δ{00} = 0`).

source
SHTnsKit.energy_scalar — Method
energy_scalar(cfg, alm; real_field=true) -> Float64

Compute the total energy of a scalar field from its spherical harmonic coefficients.

The energy is E = (1/2) ∫ |f|² dΩ for the field returned by synthesis. Parseval's identity gives (1/2) Σ |a_lm|² in the orthonormal basis. The calculation includes the configured coefficient normalization and longitude scaling. For fixed coefficients, :quad scales energy by 1/(2π)² relative to :dft.

source
SHTnsKit.energy_scalar_l_spectrum — Method
energy_scalar_l_spectrum(cfg, alm; real_field=true) -> Vector{Float64}

Compute energy spectrum as a function of spherical harmonic degree l. Returns E(l) = Σₘ |a_lm|² for each l = 0..lmax.

source
SHTnsKit.energy_scalar_lm — Method
energy_scalar_lm(cfg, alm; real_field=true) -> Matrix{Float64}

Compute per-mode energy distribution Elm = |alm|² for each (l,m) mode. Returns matrix of size (lmax+1, mmax+1) with energy contributions.

source
SHTnsKit.energy_scalar_m_spectrum — Method
energy_scalar_m_spectrum(cfg, alm; real_field=true) -> Vector{Float64}

Compute energy spectrum as a function of spherical harmonic order m. Returns E(m) = Σₗ |a_lm|² for each m = 0..mmax.

source
SHTnsKit.energy_vector — Method
energy_vector(cfg, Slm, Tlm; real_field=true) -> Float64

Compute the total kinetic energy of a vector field from spheroidal/toroidal coefficients, with the same normalization and longitude scaling as energy_scalar.

For a vector field V = ∇×(T Yl^m êᵣ) + ∇ₕ(S Yl^m), the kinetic energy is: KE = (1/2) ∫ |V|² dΩ = (1/2) Σ [l(l+1)|Slm|² + l(l+1)|Tlm|²]

source
SHTnsKit.energy_vector_l_spectrum — Method
energy_vector_l_spectrum(cfg, Slm, Tlm; real_field=true) -> Vector{Float64}

Compute kinetic energy spectrum by degree l for vector fields. Returns KE(l) = Σₘ l(l+1)[|Slm|² + |Tlm|²] for each l = 1..lmax.

source
SHTnsKit.energy_vector_lm — Method
energy_vector_lm(cfg, Slm, Tlm; real_field=true) -> Matrix{Float64}

Compute per-mode kinetic energy KElm = l(l+1)[|Slm|² + |T_lm|²] for vector fields. Returns matrix of size (lmax+1, mmax+1) with energy contributions.

source
SHTnsKit.energy_vector_m_spectrum — Method
energy_vector_m_spectrum(cfg, Slm, Tlm; real_field=true) -> Vector{Float64}

Compute kinetic energy spectrum by order m for vector fields. Returns KE(m) = Σₗ l(l+1)[|Slm|² + |Tlm|²] for each m = 0..mmax.

source
SHTnsKit.energy_vector_packed — Method
energy_vector_packed(cfg, Spacked, Tpacked; real_field=true) -> Float64

Compute vector field kinetic energy from packed S and T coefficients.

source
SHTnsKit.enstrophy — Method
enstrophy(cfg, Tlm; real_field=true) -> Float64

Compute the enstrophy (kinetic energy of vorticity) from toroidal coefficients.

For a toroidal field with coefficients Tlm, the enstrophy is: Z = (1/2) ∫ |∇×V|² dΩ = (1/2) Σ l²(l+1)²|Tlm|²

This is a measure of the small-scale intensity of rotational motion.

source
SHTnsKit.enstrophy_l_spectrum — Method
enstrophy_l_spectrum(cfg, Tlm; real_field=true) -> Vector{Float64}

Compute enstrophy spectrum as a function of degree l. Returns Z(l) = Σₘ l²(l+1)²|T_lm|² for each l = 1..lmax.

source
SHTnsKit.enstrophy_lm — Method
enstrophy_lm(cfg, Tlm; real_field=true) -> Matrix{Float64}

Compute per-mode enstrophy Zlm = l²(l+1)²|Tlm|² for each (l,m) mode. Returns matrix of size (lmax+1, mmax+1) with enstrophy contributions.

source
SHTnsKit.enstrophy_m_spectrum — Method
enstrophy_m_spectrum(cfg, Tlm; real_field=true) -> Vector{Float64}

Compute enstrophy spectrum as a function of order m. Returns Z(m) = Σₗ l²(l+1)²|T_lm|² for each m = 0..mmax.

source
SHTnsKit.estimate_memory_usage — Method
estimate_memory_usage(cfg, operation::Symbol) -> Int

Rough device-memory estimate, in bytes, for a CUDA transform. operation is :analysis, :synthesis or :vector; any other value counts only the spatial and coefficient buffers. The gpu_*_safe wrappers compare this estimate with the free memory reported by gpu_memory_info.

Requires using CUDA.

source
SHTnsKit.estimate_table_memory — Method
estimate_table_memory(lmax::Int, mmax::Int, nlat::Int) -> Int

Estimate memory usage (in bytes) for precomputed Legendre polynomial tables.

Returns the approximate memory needed for both Pl^m and dPl^m/dx tables.

source
SHTnsKit.fdgrad_scalar_energy — Method
fdgrad_scalar_energy(cfg, f) -> ∂E/∂f

Forward-mode (ForwardDiff) gradient of energy_scalar(cfg, analysis(cfg, f)) with respect to f, the full (nlat, nlon) grid. A distributed PencilArray is gathered on every rank, which is a collective call, and its gradient is returned in the same pencil. The cost grows with the number of grid points, so prefer zgrad_scalar_energy beyond small grids.

Requires using ForwardDiff.

source
SHTnsKit.fdgrad_vector_energy — Method
fdgrad_vector_energy(cfg, Vt, Vp) -> (∂E/∂Vt, ∂E/∂Vp)

ForwardDiff gradients of energy_vector(cfg, analysis_sphtor(cfg, Vt, Vp)...). The full-grid requirement and PencilArray handling are as for fdgrad_scalar_energy.

Requires using ForwardDiff.

source
SHTnsKit.fft_phi_backend — Method
fft_phi_backend() -> Symbol

Report the backend of the most recent longitude FFT: :fftw, or :dft for the plain discrete Fourier transform used for element types FFTW cannot handle, such as ForwardDiff duals. Returns :unknown before any transform.

source
SHTnsKit.get_available_gpus — Method
get_available_gpus() -> Vector

List the CUDA devices as named tuples (device=GPU(), id, name), with 0-based id. The list is empty when CUDA is not functional.

Requires using CUDA.

source
SHTnsKit.get_nlat_padded — Method
get_nlat_padded(cfg::SHTConfig) -> Int

Get the padded latitude dimension. Returns cfg.nlat if padding is disabled, or cfg.nlat_padded if padding is enabled.

This is the stride between successive phi (longitude) values in padded spatial arrays.

source
SHTnsKit.get_spat_dist — Method
get_spat_dist(cfg::SHTConfig) -> Int

Get the distance between spatial arrays in batch mode. Returns cfg.nspat if padding is disabled, or the padded spatial distance if enabled.

source
SHTnsKit.gpu_analysis — Method
gpu_analysis(cfg, f; device=GPU()) -> Matrix

Scalar analysis on the active CUDA device, with the coefficients copied back to a host Matrix. They are the coefficients analysis gives for a CuArray. f may be a host array (copied to the device) or a CuArray; analysis(cfg, f) on a CuArray keeps the result on the device.

Requires using CUDA and a functional device; otherwise it raises BackendUnavailableError. device=CPU() is an error. Only the CUDA extension implements this function.

source
SHTnsKit.gpu_analysis_safe — Method
gpu_analysis_safe(cfg, f; device=get_device()) -> Matrix

Like gpu_analysis, but it falls back to CPU analysis in any of these cases:

  • device is CPU();
  • CUDA is not functional;
  • the estimated memory exceeds the free device memory (see estimate_memory_usage);
  • the device runs out of memory.

Requires using CUDA.

source
SHTnsKit.gpu_analysis_sphtor — Method
gpu_analysis_sphtor(cfg, Vt, Vp; device=GPU(), prototype=nothing)

Compatibility wrapper for the historical host-returning GPU vector API. Ordinary analysis_sphtor(GPU(), ...) remains device-resident; this legacy entry point deliberately copies its two results back to CPU storage.

source
SHTnsKit.gpu_apply_laplacian! — Method
gpu_apply_laplacian!(cfg, alm; device=GPU()) -> alm

Multiply dense (lmax+1, mmax+1) coefficients by -l(l+1) in place on the GPU, zeroing degree 0 and unused entries.

  • With using CUDA, alm is a CuArray, or a host matrix that is copied to the device and back.
  • With using Metal, alm is an MtlArray matrix.

ROCm arrays have no method.

source
SHTnsKit.gpu_memory_info — Method
gpu_memory_info() -> (free, total)

Free and total memory of the active CUDA device, in bytes.

Requires using CUDA and a functional device.

source
SHTnsKit.gpu_synthesis — Method
gpu_synthesis(cfg, alm; device=GPU(), real_output=true) -> Matrix

Scalar synthesis on the active CUDA device, returned as a host Matrix (complex when real_output=false). alm may be a host matrix or a CuArray; synthesis(cfg, alm) on a CuArray keeps the result on the device.

Requires using CUDA and a functional device. device=CPU() is an error. Only the CUDA extension implements this function.

source
SHTnsKit.gpu_synthesis_sphtor — Method
gpu_synthesis_sphtor(cfg, S, T; device=GPU(), real_output=true,
                     prototype=nothing)

Compatibility wrapper for the historical host-returning GPU vector API.

source
SHTnsKit.grad_energy_scalar_alm — Method
grad_energy_scalar_alm(cfg, alm; real_field=true) -> Matrix

Compute gradient of scalar field energy with respect to spectral coefficients. Returns ∂E/∂a_lm for use in optimization problems.

source
SHTnsKit.grad_energy_vector_Slm_Tlm — Method
grad_energy_vector_Slm_Tlm(cfg, Slm, Tlm; real_field=true) -> (grad_S, grad_T)

Compute gradients of vector field kinetic energy with respect to S and T coefficients.

source
SHTnsKit.grad_enstrophy_Tlm — Method
grad_enstrophy_Tlm(cfg, Tlm; real_field=true) -> Matrix

Compute gradient of enstrophy with respect to toroidal coefficients. Returns ∂Z/∂Tlm = l²(l+1)² Tlm for optimization applications.

source
SHTnsKit.grad_grid_enstrophy_zeta — Method
grad_grid_enstrophy_zeta(cfg, ζ) -> Matrix

Compute gradient of grid-based enstrophy with respect to vorticity field values. Returns ∂Z/∂ζ for each grid point.

source
SHTnsKit.grad_loss_vorticity_Tlm — Method
grad_loss_vorticity_Tlm(cfg, Tlm, ζ_target) -> Matrix

Compute gradient of vorticity loss with respect to toroidal coefficients. Uses adjoint method for efficient computation.

The gradient follows the convention of the other grad_* helpers and of Zygote: for a perturbation h, dL = real(sum(conj(g) .* h)). Because the vorticity is a real field, each stored m > 0 coefficient stands for the ±m pair, so those entries carry a factor 2 relative to m = 0.

source
SHTnsKit.grid_energy_scalar — Method
grid_energy_scalar(cfg, f) -> Float64

Compute energy of a scalar field directly from its spatial representation. Uses Gauss-Legendre quadrature for accurate integration.

source
SHTnsKit.grid_energy_vector — Method
grid_energy_vector(cfg, Vt, Vp) -> Float64

Compute kinetic energy of a vector field from its θ and φ components. With robert_form=true, supply the sin(θ)-weighted components returned by synthesis_sphtor. Recovering physical energy requires a pole-free grid or zero pole weights when order one is represented.

source
SHTnsKit.grid_enstrophy — Method
grid_enstrophy(cfg, ζ) -> Float64

Compute enstrophy directly from gridded vorticity field using quadrature. Z = (1/2) ∫ ζ² dΩ using Gauss-Legendre integration.

source
SHTnsKit.im_from_lm — Method
im_from_lm(lm::Int, lmax::Int, mres::Int) -> Int

Inverse operation: determine the reduced m-index (im = m/mres) from a packed index. This function searches through the m-blocks to find which block contains the given packed index.

Useful for algorithms that need to determine the azimuthal symmetry of a coefficient from its packed storage location.

source
SHTnsKit.inside — Method
inside(a; buff=1)

Return CartesianIndices range excluding buff layers of cells on all boundaries. Useful for iterating over interior points while respecting boundary conditions.

source
SHTnsKit.is_on_the_fly — Method
is_on_the_fly(cfg::SHTConfig) -> Bool

Check if configuration is set to on-the-fly Legendre computation mode.

source
SHTnsKit.is_south_pole_first — Method
is_south_pole_first(cfg::SHTConfig) -> Bool

Check if the configuration uses south-pole-first latitude ordering.

Returns true if latitude data starts at the south pole (θ=π), false if it starts at the north pole (θ=0, the default).

source
SHTnsKit.local_range — Method
local_range(arr)

Return CartesianIndices for iterating over the local portion of an array. For PencilArrays, this iterates over parent(arr) dimensions. For regular arrays, this is equivalent to CartesianIndices(arr).

Example

# With PencilArray (MPI-distributed)
@sht_loop local_data[I] = value over I ∈ local_range(pencil_arr)

# With regular array
@sht_loop field[I] = value over I ∈ local_range(regular_arr)
source
SHTnsKit.local_size — Method
local_size(arr)

Return the size of the local portion of an array. For PencilArrays, returns size(parent(arr)). For regular arrays, returns size(arr).

source
SHTnsKit.loss_vorticity_grid — Method
loss_vorticity_grid(cfg, Tlm, ζ_target) -> Float64

Compute loss function for vorticity matching problem. L = (1/2) ∫ [ζ(Tlm) - ζ_target]² dΩ where ζ(Tlm) is computed vorticity.

source
SHTnsKit.matrix_to_spectral_pencil — Method
matrix_to_spectral_pencil(cfg, Alm::AbstractMatrix; comm=MPI.COMM_WORLD) -> PencilArray

Distribute a dense (lmax+1, mmax+1) coefficient matrix, which must be identical on every rank, into a spectral PencilArray on create_spectral_pencil. Each rank keeps its own m-columns.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over comm.

source
SHTnsKit.mode_range — Method
mode_range(mmax)

Return a range for iterating over azimuthal modes (0 to mmax). Storage index: m+1 for m ∈ 0:mmax

source
SHTnsKit.mul_ct_matrix — Method
mul_ct_matrix(cfg::SHTConfig, mx::AbstractVector{<:Real})

Fill mx with coupling coefficients for cosθ operator: cosθ Yl^m = al^m Y{l-1}^m + bl^m Y_{l+1}^m.

mx[2lm+1] and mx[2lm+2], with lm the 0-based packed index of (l, m), hold the couplings of Y_l^m to Y_{l-1}^m and Y_{l+1}^m: the layout SH_mul_mx expects. cosθ is symmetric, so this is also the array SHTns's mul_ct_matrix produces.

source
SHTnsKit.nlm_calc — Method
nlm_calc(lmax::Integer, mmax::Integer, mres::Integer) -> Int

Calculate the total number of packed spectral coefficients for a real scalar field. Real fields only need m ≥ 0 modes due to Hermitian symmetry: Yl^{-m} = (-1)^m (Yl^m)*

The packing scheme groups modes by m-order, then by l-degree within each m block. This layout is optimized for vectorized operations and cache efficiency.

source
SHTnsKit.nlm_cplx_calc — Method
nlm_cplx_calc(lmax::Integer, mmax::Integer, mres::Integer) -> Int

Calculate the total number of spectral coefficients for a complex field. Complex fields require both positive and negative m modes, unlike real fields which use Hermitian symmetry to store only m ≥ 0 modes.

This is used for complex-valued spherical harmonic expansions where no symmetry assumptions can be made about the coefficients.

source
SHTnsKit.on_device — Method

Return CPU() for ordinary arrays; vendor extensions specialize this. A wrapper reports the storage of the array it wraps.

source
SHTnsKit.prepare_plm_tables! — Method
prepare_plm_tables!(cfg::SHTConfig)

Precompute associated Legendre tables Pl^m(xi) for all i and m, stored as cfg.plm_tables[m+1][l+1, i]. Enables faster scalar transforms on regular grids.

source
SHTnsKit.scratch_fft — Function
scratch_fft(cfg::SHTConfig, T::Type=ComplexF64) -> Matrix{T}

Allocate a complex buffer sized for φ-FFTs (nlat, nlon). Reuse this across analysis!/synthesis! calls via the fft_scratch keyword to avoid per-call allocations.

source
SHTnsKit.scratch_spatial — Function
scratch_spatial(cfg::SHTConfig, T::Type=Float64) -> Matrix{T}

Allocate a spatial grid buffer of size (nlat, nlon).

source
SHTnsKit.set_allow_padding! — Method
set_allow_padding!(cfg::SHTConfig; auto_compute::Bool=true)

Enable memory padding for cache optimization. When enabled, spatial arrays can have extra padding between latitude lines to avoid cache bank conflicts.

This can improve performance by 1-50% depending on the problem size and hardware, especially for multi-threaded and GPU transforms.

Arguments

  • cfg: SHTConfig to modify
  • auto_compute: If true, automatically compute optimal padding. If false, you must set cfg.nlat_padded manually.

Example

cfg = create_gauss_config(64, 66)
set_allow_padding!(cfg)
println("Padded nlat: $(cfg.nlat_padded)")  # May be > 66

See also: disable_padding!, is_padding_enabled, get_nlat_padded

source
SHTnsKit.set_batch_size! — Method
set_batch_size!(cfg::SHTConfig, howmany::Int; spec_dist::Int=0)

Record the SHTns-style batched-layout descriptors on the configuration.

Advisory metadata

howmany and spec_dist mirror the SHTns C API's batch descriptors and are stored for interoperability, but the Julia batch entry points do not consult them: analysis_batch, synthesis_batch and their sphtor/QST siblings take the field count from size(fields, 3) of the array you pass. Setting a batch size neither constrains nor accelerates those calls, and passing a different number of fields is allowed and works.

Configure the batch descriptors carried by cfg for callers that mirror the SHTns C layout. See the note above for what the Julia batch transforms actually use.

Arguments

  • cfg: SHTConfig to modify
  • howmany: Number of fields to process in each batch (≥1)
  • spec_dist: Distance between spectral coefficient arrays in memory. If 0, arrays are assumed contiguous. Otherwise, this is the stride between the start of successive spectral arrays.

Returns

  • The configured batch size (always ≥1)

Example

cfg = create_gauss_config(32, 34)
set_batch_size!(cfg, 4)   # recorded on cfg; does not bind the call below

fields = rand(cfg.nlat, cfg.nlon, 4)
alms = analysis_batch(cfg, fields)   # count comes from size(fields, 3)
source
SHTnsKit.set_fft_plan_cache! — Method
set_fft_plan_cache!(flag::Bool; clear::Bool=true) -> Bool

Enable or disable φ-FFT plan caching. When disabling with clear=true (the default) the existing entries are dropped as well. Returns flag.

source
SHTnsKit.set_gpu_device — Method
set_gpu_device(id::Int) -> Bool
set_gpu_device(GPU(), id::Int) -> Bool

Make CUDA device id the active device. Ids are 0-based, as listed by get_available_gpus. Returns false and changes nothing when CUDA is not functional.

Requires using CUDA.

source
SHTnsKit.set_loop_backend — Method
set_loop_backend(backend::String)

Set the loop backend preference. Valid values:

  • "auto": Automatically detect from array type (default) - uses GPU when arrays are on GPU
  • "SIMD": Force CPU SIMD path (useful for debugging or when GPU is not desired)
source
SHTnsKit.set_north_pole_first! — Method
set_north_pole_first!(cfg::SHTConfig)

Enable north-pole-first latitude ordering (the default). In this mode, latitude data starts at the north pole (θ=0).

This reverses the internal grid arrays if the configuration was previously in south-pole-first mode, and recalculates any precomputed Legendre tables.

Example

cfg = create_gauss_config(32, 34)
set_south_pole_first!(cfg)  # Data starts at south pole
set_north_pole_first!(cfg)  # Back to default (north pole first)

See also: set_south_pole_first!, is_south_pole_first

source
SHTnsKit.set_on_the_fly! — Method
set_on_the_fly!(cfg::SHTConfig)

Enable on-the-fly Legendre polynomial computation mode. This disables precomputed tables and computes P_l^m(x) during each transform.

Benefits:

  • Lower memory usage (no table storage)
  • Better for large lmax values
  • Can be faster on modern CPUs due to cache effects

See also: set_use_tables!, create_gauss_fly_config

source
SHTnsKit.set_south_pole_first! — Method
set_south_pole_first!(cfg::SHTConfig)

Enable south-pole-first latitude ordering. In this mode, latitude data starts at the south pole (θ=π) instead of the default north pole (θ=0).

This reverses the internal grid arrays (θ, x, w, st) and recalculates any precomputed Legendre tables if necessary.

Example

cfg = create_gauss_config(32, 34)
set_south_pole_first!(cfg)  # Data now starts at south pole

See also: set_north_pole_first!, is_south_pole_first

source
SHTnsKit.set_use_tables! — Method
set_use_tables!(cfg::SHTConfig)

Enable precomputed Legendre polynomial tables. This precomputes Pl^m(xi) for all grid points and stores them for reuse.

Benefits:

  • Faster for repeated transforms with same grid
  • No redundant computation of Legendre polynomials

Trade-offs:

  • Higher memory usage: O(lmax × mmax × nlat)
  • Initial table computation overhead

See also: set_on_the_fly!, prepare_plm_tables!

source
SHTnsKit.shtns_rotation_apply_cplx — Method
shtns_rotation_apply_cplx(r::SHTRotation, Zlm::AbstractVector{<:Complex}, Rlm::AbstractVector{<:Complex})

Apply rotation with Euler angles (ZYZ/ZXZ) to complex SH coefficients in LM_cplx packing (mres==1).

source
SHTnsKit.shtns_rotation_apply_real — Method
shtns_rotation_apply_real(r::SHTRotation, Qlm::AbstractVector{<:Complex}, Rlm::AbstractVector{<:Complex})

Apply rotation to real-field SH coefficients in packed LM layout (m ≥ 0). Requires mres==1.

source
SHTnsKit.shtns_rotation_set_angle_axis — Method
shtns_rotation_set_angle_axis(r::SHTRotation, theta::Real, Vx::Real, Vy::Real, Vz::Real)

Define rotation from angle-axis (theta around vector V). Angles are set in ZYZ convention.

source
SHTnsKit.shtns_rotation_wigner_d_matrix — Method
shtns_rotation_wigner_d_matrix(r::SHTRotation, l::Integer, mx::AbstractVector{<:Real}) -> Int

Fill mx (length ≥ (2l+1)^2) with d^l in row-major order. Returns size 2l+1.

source
SHTnsKit.spatial_view — Method
spatial_view(cfg::SHTConfig, A::AbstractArray) -> SubArray

The (nlat, nlon) (or (nlat, nlon, nfields)) window of a padded spatial buffer, in the form the transforms accept.

allocate_padded_spatial deliberately returns an array whose first dimension is nlat_padded ≥ nlat, while every transform requires exactly nlat rows — so the padded buffer could not be handed to analysis at all, which left the whole padding API unusable. This is the missing bridge:

cfg = create_gauss_config(64, 66)
set_allow_padding!(cfg)
pad = allocate_padded_spatial(cfg)
copy_to_padded!(pad, field, cfg)
alm = analysis(cfg, spatial_view(cfg, pad))     # padded stride preserved

The view does not throw the padding away: a SubArray over the leading rows keeps the padded column stride (nlat_padded, not nlat), which is exactly the cache-conflict avoidance the padding exists for. Results are bit-identical to the unpadded layout.

source
SHTnsKit.spectral_pencil_to_matrix — Method
spectral_pencil_to_matrix(cfg, Alm::PencilArray) -> Matrix

Gather a spectral PencilArray into the dense (lmax+1, mmax+1) matrix, on every rank.

Requires using MPI, PencilArrays, PencilFFTs. The call is collective over the communicator of Alm.

source
SHTnsKit.spectral_range — Method
spectral_range(lmax, mmax)

Return a CartesianIndices range for iterating over valid (l,m) coefficient pairs. Note: Returns range for 1-based indexing of storage array, so iterate as: for idx ∈ spectral_range(lmax, mmax) l, m = idx[1] - 1, idx[2] - 1 # Convert to 0-based degree/order # ... work with alm[l+1, m+1] end

source
SHTnsKit.spheroidal_from_divergence! — Method
spheroidal_from_divergence!(cfg, Slm, δlm) -> Slm

In-place form of spheroidal_from_divergence. Writes the spheroidal coefficients into Slm, which may be δlm itself.

source
SHTnsKit.st_dt_matrix — Method
st_dt_matrix(cfg::SHTConfig, mx::AbstractVector{<:Real})

Fill mx with coupling coefficients for sinθ ∂θ operator: sinθ ∂θ Yl^m = l bl^m Y{l+1}^m - (l+1) al^m Y_{l-1}^m.

Same layout as mul_ct_matrix: each entry pair holds how Y_l^m couples to its neighbours. SHTns stores, for each (l, m), what it receives from its neighbours instead, which differs for this non-symmetric operator; see "Differences from SHTns" in the normalization guide for the conversion.

source
SHTnsKit.suggest_pencil_grid — Function
suggest_pencil_grid(comm_or_nprocs, nlat, nlon; prefer_square=true, allow_one_dim=true)

Return a suggested MPI pencil decomposition (p_theta, p_phi) for a grid of size nlat x nlon. The base package provides a (1,1) fallback so the function is always defined; when SHTnsKitParallelExt is loaded the callback is replaced with an MPI-aware heuristic that favours balanced 2D decompositions.

source
SHTnsKit.synthesis! — Method
synthesis!(cfg::SHTConfig, f_out::AbstractMatrix, alm::AbstractMatrix; real_output::Bool=true)

In-place inverse transform. Writes the spatial field into f_out.

source
SHTnsKit.synthesis! — Method
synthesis!(plan::SHTPlan, f_out::AbstractMatrix, alm::AbstractMatrix; real_output=true)

In-place inverse scalar SHT writing spatial field into f_out. Streams m→k directly without building a (θ×m) intermediate.

source
SHTnsKit.synthesis — Method
synthesis(cfg::SHTConfig, alm::AbstractMatrix; real_output::Bool=true) -> Matrix

Inverse transform back to a grid (nlat, nlon). If real_output=true, Hermitian symmetry is enforced before IFFT.

source
SHTnsKit.synthesis_axisym — Method
synthesis_axisym(cfg, Qlm) -> Vector{Float64}

Axisymmetric synthesis from degree-only coefficients to Gauss latitudes. Input Qlm should contain coefficients Q_l for l = 0..lmax. Returns spatial values at Gauss latitudes.

source
SHTnsKit.synthesis_batch! — Method
synthesis_batch!(cfg::SHTConfig, f_out::AbstractArray,
                 alm_batch::AbstractArray{<:Complex,3}; real_output::Bool=true)

In-place batch inverse transform.

source
SHTnsKit.synthesis_batch — Method
synthesis_batch(cfg::SHTConfig, alm_batch::AbstractArray{<:Complex,3};
                real_output::Bool=true) -> Array

Batch inverse transform for multiple spectral coefficient sets.

Arguments

  • cfg: SHTConfig with batch size configured
  • alm_batch: 3D array of shape (lmax+1, mmax+1, nfields) with spectral coefficients
  • real_output: If true, return real spatial fields; otherwise complex

Returns

  • 3D array of shape (nlat, nlon, nfields) with spatial data
source
SHTnsKit.synthesis_batch_cplx — Method
synthesis_batch_cplx(cfg::SHTConfig, alm_batch::AbstractArray{<:Complex,3}) -> Array{ComplexF64,3}

Complex-output batch inverse transform. Equivalent to synthesis_batch(cfg, alm_batch; real_output=false) with a concrete return type for inference-sensitive callers.

source
SHTnsKit.synthesis_cplx — Method
synthesis_cplx(cfg::SHTConfig, alm::AbstractMatrix) -> Matrix{<:Complex}

Complex-output inverse scalar transform. This is equivalent to synthesis(cfg, alm; real_output=false) but dispatches through a compile-time output mode so callers can rely on a concrete return type.

source
SHTnsKit.synthesis_grad — Method
synthesis_grad(cfg::SHTConfig, Slm::AbstractMatrix; real_output::Bool=true)

Gradient synthesis alias for compatibility with SHTns.

source
SHTnsKit.synthesis_grad_l — Method
synthesis_grad_l(cfg::SHTConfig, Slm::AbstractMatrix, ltr::Int; real_output::Bool=true)

Degree-limited gradient synthesis alias.

source
SHTnsKit.synthesis_grad_ml — Method
synthesis_grad_ml(cfg::SHTConfig, mval::Int, Sl::AbstractVector{<:Complex}, ltr::Int)

Mode-limited gradient synthesis alias.

source
SHTnsKit.synthesis_packed — Method
synthesis_packed(cfg, Qlm::AbstractVector{<:Complex}) -> Vector{Float64}

Packed scalar synthesis from Qlm (LM order) to flattened real grid (length nlat*nlon).

source
SHTnsKit.synthesis_packed_cplx — Method
synthesis_packed_cplx(cfg::SHTConfig, alm_packed::AbstractVector{<:Complex}) -> Matrix{ComplexF64}

Synthesize a complex spatial field from packed complex coefficients in LM_cplx order, which stores both signs of m. Returns an nlat × nlon complex array. Requires cfg.mres == 1.

source
SHTnsKit.synthesis_packed_cplx_l — Method
synthesis_packed_cplx_l(cfg, alm_packed, ltr)

Synthesize a complex spatial field from the LM_cplx coefficients with degrees l > ltr ignored. The input retains the full packed storage shape.

source
SHTnsKit.synthesis_packed_l — Method
synthesis_packed_l(cfg::SHTConfig, Qlm::AbstractVector{<:Complex}, ltr::Integer) -> Vector{Float64}

Scalar synthesis truncated to degrees l ≤ ltr. Contributions from higher degrees are ignored.

source
SHTnsKit.synthesis_packed_ml — Method
synthesis_packed_ml(cfg, mval, Ql, ltr) -> Vector{<:Complex}

Transform spherical harmonic coefficients for specific mode m to spatial field. mval is the zero-based stored-order index (m = mval * cfg.mres); Ql contains coefficients for degrees l = m..ltr. Returns complex spatial values for that azimuthal mode.

source
SHTnsKit.synthesis_point — Method
synthesis_point(cfg, Qlm, cost, phi) -> Real

Evaluate spherical harmonic expansion at a single point (θ,φ) for a real-valued field. cost = cos(θ), phi is the azimuthal angle. Qlm should be a matrix of size (lmax+1, mmax+1) with standard indexing (only m ≥ 0 stored; negative-m reconstructed via Hermitian symmetry). Returns the real field value at the specified point.

source
SHTnsKit.synthesis_point_cplx — Method
synthesis_point_cplx(cfg::SHTConfig, alm::AbstractVector{<:Complex}, cost::Real, phi::Real) -> Complex

Evaluate a complex field represented by packed alm at a single point.

source
SHTnsKit.synthesis_qst! — Function
synthesis_qst!(plan::DistQstPlan, Vrθφ_out, Vtθφ_out, Vpθφ_out, Qlm, Slm, Tlm; real_output=true) -> (Vrθφ_out, Vtθφ_out, Vpθφ_out)

Planned distributed synthesis of a 3D vector field from dense radial Qlm, spheroidal Slm and toroidal Tlm coefficient matrices, which must be identical on every rank. It writes the radial, colatitude and longitude components into the output PencilArrays, laid out like the plan's prototype. This is the same operation as dist_synthesis_qst! with a DistQstPlan.

Only DistQstPlan methods exist. They are defined when using MPI, PencilArrays, PencilFFTs loads the parallel extension, and they need CPU storage. The call is collective over the plan's communicator.

source
SHTnsKit.synthesis_qst — Method
synthesis_qst(cfg, Qlm, Slm, Tlm; real_output=true, use_rfft=false) -> (Vr, Vt, Vp)

Transform QST spectral coefficients to 3D spatial vector field components. Returns radial (Vr), colatitude (Vt), and azimuthal (Vp) components. All three take the precision promoted across the inputs, as in synthesis_qst_batch.

source
SHTnsKit.synthesis_qst_batch — Method
synthesis_qst_batch(cfg::SHTConfig, Qlm_batch::AbstractArray{<:Complex,3},
                    Slm_batch::AbstractArray{<:Complex,3}, Tlm_batch::AbstractArray{<:Complex,3};
                    real_output::Bool=true)

Batch QST synthesis for multiple 3D vector fields.

Returns

  • (Vr_batch, Vt_batch, Vp_batch): Tuple of 3D arrays with spatial components
source
SHTnsKit.synthesis_qst_cplx — Method
synthesis_qst_cplx(cfg, Qlm, Slm, Tlm) -> (Vr, Vt, Vp)

Complex version of QST to spatial transform, preserving complex values.

source
SHTnsKit.synthesis_qst_l — Method
synthesis_qst_l(cfg, Qlm, Slm, Tlm, ltr; real_output=true) -> (Vr, Vt, Vp)

Degree-limited version of synthesis_qst, using coefficients only up to degree ltr.

source
SHTnsKit.synthesis_qst_l_cplx — Method
synthesis_qst_l_cplx(cfg, Qlm, Slm, Tlm, ltr) -> (Vr, Vt, Vp)

Complex-output form of synthesis_qst_l. It is equivalent to real_output=false, with a concrete return type for inference-sensitive code.

source
SHTnsKit.synthesis_qst_ml — Method
synthesis_qst_ml(cfg, mval, Ql, Sl, Tl, ltr) -> (Vr_m, Vt_m, Vp_m)

Mode-limited synthesis for specific azimuthal mode mval.

source
SHTnsKit.synthesis_sph — Method
synthesis_sph(cfg, Slm; real_output=true) -> (Vt, Vp)

Transform only spheroidal component to spatial vector field (Tlm = 0).

source
SHTnsKit.synthesis_sph_cplx — Method
synthesis_sph_cplx(cfg, Slm) -> (Vt, Vp)

Complex-output spheroidal-only synthesis without allocating a dense zero toroidal spectrum.

source
SHTnsKit.synthesis_sph_l_cplx — Method
synthesis_sph_l_cplx(cfg, Slm, ltr) -> (Vt, Vp)

Complex-output form of synthesis_sph_l: the degree-limited synthesis of the spheroidal part alone.

source
SHTnsKit.synthesis_sph_ml — Method
synthesis_sph_ml(cfg::SHTConfig, mval::Int, Sl::AbstractVector{<:Complex}, ltr::Int)

Mode-limited spheroidal-only synthesis wrapper.

source
SHTnsKit.synthesis_sphtor! — Method
synthesis_sphtor!(plan::SHTPlan, Vt_out::AbstractMatrix, Vp_out::AbstractMatrix, Slm::AbstractMatrix, Tlm::AbstractMatrix; real_output=true)

In-place vector synthesis. Streams m→k without forming (θ×m) intermediates; inverse FFT Vt then Vp.

source
SHTnsKit.synthesis_sphtor — Method
synthesis_sphtor(cfg, Slm, Tlm; real_output=true) -> (Vt, Vp)

Transform spheroidal/toroidal coefficients to horizontal vector field components. Returns colatitude (Vt) and azimuthal (Vp) components on the spatial grid.

source
SHTnsKit.synthesis_sphtor_batch — Method
synthesis_sphtor_batch(cfg::SHTConfig, Slm_batch::AbstractArray{<:Complex,3},
                       Tlm_batch::AbstractArray{<:Complex,3}; real_output::Bool=true)

Batch spheroidal-toroidal synthesis for multiple vector fields.

Returns

  • (Vt_batch, Vp_batch): Tuple of 3D arrays (nlat, nlon, nfields) containing theta and phi components
source
SHTnsKit.synthesis_sphtor_l — Method
synthesis_sphtor_l(cfg, Slm, Tlm, ltr; real_output=true) -> (Vt, Vp)

Degree-limited version of synthesis_sphtor, using coefficients only up to degree ltr. Higher degrees in Slm and Tlm are ignored.

source
SHTnsKit.synthesis_sphtor_l_cplx — Method
synthesis_sphtor_l_cplx(cfg, Slm, Tlm, ltr) -> (Vt, Vp)

Complex-output form of synthesis_sphtor_l. It is equivalent to real_output=false, with a concrete return type for inference-sensitive code.

source
SHTnsKit.synthesis_sphtor_ml — Method
synthesis_sphtor_ml(cfg, mval, Sl, Tl, ltr) -> (Vt_m, Vp_m)

Mode-limited synthesis for a single azimuthal order mval: Vθ = ∂S/∂θ - (i·mval/sinθ) * T Vφ = (i·mval/sinθ) * S + ∂T/∂θ

The order argument is named mval, NOT im: a binding called im shadows Julia's imaginary unit, and 1.0im is juxtaposition (1.0 * im), so the coupling terms above silently became real. Do not rename it back.

source
SHTnsKit.synthesis_tor — Method
synthesis_tor(cfg, Tlm; real_output=true) -> (Vt, Vp)

Transform only toroidal component to spatial vector field (Slm = 0).

source
SHTnsKit.synthesis_tor_cplx — Method
synthesis_tor_cplx(cfg, Tlm) -> (Vt, Vp)

Complex-output toroidal-only synthesis without allocating a dense zero spheroidal spectrum.

source
SHTnsKit.synthesis_tor_l_cplx — Method
synthesis_tor_l_cplx(cfg, Tlm, ltr) -> (Vt, Vp)

Complex-output form of synthesis_tor_l: the degree-limited synthesis of the toroidal part alone.

source
SHTnsKit.synthesis_tor_ml — Method
synthesis_tor_ml(cfg::SHTConfig, mval::Int, Tl::AbstractVector{<:Complex}, ltr::Int)

Mode-limited toroidal-only synthesis wrapper.

source
SHTnsKit.synthesis_turbo — Method
synthesis_turbo(cfg, alm::AbstractMatrix; real_output=true) -> Matrix

synthesis with LoopVectorization-optimized CPU loops. The arguments and result are the same.

Requires using LoopVectorization.

source
SHTnsKit.to_device — Method
to_device(device::ComputeDevice, value)
to_device(GPU(), value, prototype)
to_device(value)

Return value on device. to_device(CPU(), x) copies device storage into a host Array, first gathering a wrapped array on its device, and returns host values unchanged. to_device(GPU(), x) copies host data to the one functional GPU backend and returns device arrays unchanged. With a prototype device array it uses that array's backend and device. to_device(value) uses get_device. The value-first forms to_device(value, device) and to_device(value, device, prototype) are equivalent.

source
SHTnsKit.toroidal_from_vorticity! — Method
toroidal_from_vorticity!(cfg, Tlm, ζlm) -> Tlm

In-place form of toroidal_from_vorticity. Writes the toroidal coefficients into Tlm, which may be ζlm itself.

source
SHTnsKit.turbo_apply_laplacian! — Method
turbo_apply_laplacian!(cfg, alm) -> alm

Multiply coefficients by -l(l+1) in place. alm is a dense (lmax+1, mmax+1) matrix, whose orders not stored under cfg.mres are zeroed, or a packed cfg.nlm vector.

Requires using LoopVectorization.

source
SHTnsKit.vorticity_from_toroidal! — Method
vorticity_from_toroidal!(cfg, ζ, Tlm) -> ζ

In-place form of vorticity_from_toroidal. Writes the vorticity coefficients into ζ, which may be Tlm itself.

source
SHTnsKit.vorticity_grid — Method
vorticity_grid(cfg, Tlm) -> Matrix

Transform toroidal coefficients to vorticity on the spatial grid. This combines spectral vorticity calculation with spherical harmonic synthesis.

source
SHTnsKit.vorticity_spectral — Method
vorticity_spectral(cfg, Tlm) -> Matrix{ComplexF64}

Compute vorticity coefficients ζlm from toroidal stream function coefficients Tlm. Relationship: ζlm = -l(l+1) Tlm

source
SHTnsKit.zgrad_enstrophy_Tlm — Method
zgrad_enstrophy_Tlm(cfg, Tlm) -> ∂Z/∂Tlm

Zygote gradient of enstrophy(cfg, Tlm) with respect to the toroidal coefficients Tlm.

Requires using Zygote.

source
SHTnsKit.zgrad_rotation_angles_cplx — Method
zgrad_rotation_angles_cplx(lmax, mmax, Zlm::AbstractVector, α, β, γ; loss=nothing) -> (∂L/∂α, ∂L/∂β, ∂L/∂γ)

Complex counterpart of zgrad_rotation_angles_real, for coefficients in the complex packed LM_cplx layout with degrees up to lmax and orders up to mmax. It takes the same loss keyword.

Defined by the Zygote extension: requires using Zygote.

source
SHTnsKit.zgrad_rotation_angles_real — Method
zgrad_rotation_angles_real(cfg, Qlm::AbstractVector, α, β, γ; loss=nothing) -> (∂L/∂α, ∂L/∂β, ∂L/∂γ)

Gradient of L = loss(R(α, β, γ) Qlm) with respect to the ZYZ Euler angles. R rotates the packed real-field coefficients Qlm as an SHTRotation does, using cfg's normalization and phase convention. Needs cfg.mres == 1.

Without loss, L = ½‖R(α, β, γ) Qlm‖². With norm=:orthonormal and real_norm=true that norm is the field energy, which a rotation preserves, so the gradient is zero. To fit a rotation, pass a loss that compares the rotated coefficients with a target:

loss = rotated -> sum(abs2, rotated .- target) / 2
∂α, ∂β, ∂γ = zgrad_rotation_angles_real(cfg, Qlm, α, β, γ; loss)

Defined by the Zygote extension: requires using Zygote.

source
SHTnsKit.zgrad_scalar_energy — Method
zgrad_scalar_energy(cfg, f) -> ∂E/∂f

Reverse-mode (Zygote) gradient of the spectral energy energy_scalar(cfg, analysis(cfg, f)) with respect to the spatial field f. The gradient has the shape of f. If the parallel extension is also loaded, a distributed PencilArray input gives its gradient in the same pencil.

Requires using Zygote.

source
SHTnsKit.zgrad_vector_energy — Method
zgrad_vector_energy(cfg, Vt, Vp) -> (∂E/∂Vt, ∂E/∂Vp)

Zygote gradients of the vector energy energy_vector(cfg, analysis_sphtor(cfg, Vt, Vp)...) with respect to the colatitude and longitude components, which must have the same size. Distributed PencilArray inputs work as for zgrad_scalar_energy.

Requires using Zygote.

source
SHTnsKit.δ — Method
δ(i, N::Int)
δ(i, I::CartesianIndex{N})

Return a CartesianIndex of dimension N which is one at index i and zero elsewhere. Useful for offsetting indices in a specific direction.

Example

δ(1, CartesianIndex(2,3))  # Returns CartesianIndex(1,0)
source
SHTnsKit.@sht_inside — Macro
@sht_inside <arr[I] = expr>

Convenience macro to loop over interior points of an array, excluding boundaries. Automatically determines the loop range from the array size.

Example

@sht_inside field[I] = 0.5 * (field_old[I+δ(1,I)] + field_old[I-δ(1,I)])
source
SHTnsKit.@sht_loop — Macro
@sht_loop <expr> over <I ∈ R>

Macro to automate fast loops using @simd when running on CPU, or KernelAbstractions when running on GPU (requires GPU extension).

The macro extracts all symbols from the expression, creates kernel functions for both CPU and GPU paths, and dispatches based on the array backend at runtime.

Examples

# Loop over 2D Cartesian range
@sht_loop dest[i, j] = src[i, j] * scale over (i, j) ∈ CartesianIndices((n, m))

# Stencil over the interior points
@sht_loop out[I] = src[I + δ(1, I)] - src[I - δ(1, I)] over I ∈ inside(src)

Notes

  • Detects CPU vs GPU from the first array in the expression
  • GPU path requires GPU extension (CUDA.jl + KernelAbstractions)
  • CPU path uses @simd @fastmath @inbounds for vectorization. Before the loop, the array accesses every iteration makes are bounds-checked, so a BoundsError is raised instead of reading or writing out of range: indices affine in the loop index at the corners of the iteration range, others at every iteration. Accesses that may not run on every iteration (inside if, ?:, &&, ||, an inner loop or closure, or after a possible early exit) and indices that call anything but integer arithmetic are not checked; keep those in range yourself.
  • Every iteration must write its own elements. On a GPU the iterations run concurrently, so an accumulation into a shared element (a[k] += b[i] over i) races and loses updates; reduce with array operations instead.
  • Set SHTnsKit.set_loop_backend("SIMD") to force CPU path

Field accesses in the body (e.g. cfg.scale) are supported: the expression is evaluated once at the call site and passed in under a hygienic name, so it can never pick up an unrelated caller local that happens to share the field name.

source

Configuration lifecycle

SHTConfig is managed by Julia's garbage collector. destroy_config(cfg) is a no-op retained for API symmetry; callers do not need a try/finally teardown pattern.