API Reference

Plan construction

NUFSHT.make_plan — Function
make_plan([FE = float(eltype(θ_nodes)),] θ_nodes, φ_nodes, lmax; execution = AutoBackend(), tol=1e-8, ntrans=1, …)

Construct a scalar plan for M scattered points at colatitudes θ_nodes ∈ [0,π] and longitudes φ_nodes ∈ [0,2π), up to spherical harmonic degree lmax, transforming ntrans co-located fields per call: a NUSHTplan for host nodes, a RingNUSHTplan for device nodes. Builds the NUFFT plans over the nodes once; close! frees them.

FE is the field element type, positional as it is for zeros(T, …). A real FE asserts the field values are real, so the mode array is conjugate-symmetric in kθ; on a NUFFT backend with a real-data transform (either FlowTransformBindings library) only the kθ ≥ 0 half is built and real strengths come back. A complex FE builds the full array. Both are the same spherical harmonic transform.

Keyword arguments:

  • execution: where the plan runs, a ComputationalBackends backend. SerialBackend() runs it on one thread and ThreadedBackend() on Threads.nthreads(); AutoBackend(), the default, runs it on the host at nthreads. GPUBackend(b) puts the nodes, and so the plan, in b's memory (with KernelAbstractions and GPUArraysCore), as device nodes passed under any other local backend do. DistributedBackend(inner) divides the points among the worker processes and MPIBackend(inner) among the ranks of its communicator (with Distributed, MPI), each share's plan built under inner with the other keywords; both plans take and return the whole field.
  • tol: NUFFT accuracy tolerance, raised to eps(T).
  • nufft: SpectralBackends.AutoSpectralBackend() (default), FlowTransformBindings.NonuniformFFTsBackend(), FlowTransformBindings.FINUFFTBackend() or SpectralBackends.DirectSumSpectralBackend().
  • ntrans: batch size B — transform B co-located fields (same nodes) per call.
  • nthreads: the thread count the NUFFT and FastTransforms' OpenMP regions run at, and the per-column sphere steps divide among tasks at; nothing or 0 takes Threads.nthreads(). Inside an OhMyThreads farm, and in the tasks of the per-column loop, FastTransforms runs on one thread. An explicit count takes precedence over the one execution sets, except under SerialBackend(), which runs on one thread and raises an ArgumentError for any count other than 1. FINUFFT takes any count, while NonuniformFFTs parallelises over Julia's own threads and so reaches only 1 and Threads.nthreads() — a count it cannot deliver is an error.
  • upsampfac: the NUFFT's oversampling factor; nothing takes the library's own.
  • point_count: FixedCount (default) or VariableCount, which lets set_nodes! change the point count.
  • directions: SynthesisAndAnalysis (default) or SynthesisOnly.
source
make_plan(FE, θ, φ, lmax, TensorProduct(); kwargs...)

Build a scalar tensor-product transform in the existing scalar coefficient layout.

source
NUFSHT.AbstractScalarNUSHTplan — Type
AbstractScalarNUSHTplan{T,FE} <: AbstractNUSHTplan

Supertype of the scalar plans, NUSHTplan and RingNUSHTplan, of precision T and field element type FE, whose coefficients are in FastTransforms' sph_mode layout. The scalar transforms, fits, analyses and filters take either.

source
NUFSHT.NUSHTplan — Type
NUSHTplan{T}

Pre-computed plan for non-uniform spherical harmonic transforms at M scattered points, up to degree lmax, transforming B co-located fields per call (ntrans = B).

Fields:

  • lmax, Nθ = lmax+1, Nφ = 2lmax+1, B (batch size / NUFFT ntrans)
  • tol: NUFFT accuracy tolerance
  • ntasks: the plan's thread count, which its FastTransforms calls run at and its sphere-column loop divides among tasks
  • nodes: the AbstractNodeSet holding θ_nodes, φ_nodes (colatitudes ∈ [0,π] and longitudes ∈ [0,2π) of the M points), the (M, B) strengths buffer fbuf, and the two NUFFT handles. set_nodes! re-points it.
  • C: filter scratch, empty until the first filter call (_filter_scratch). F: the bivariate Fourier coefficients P·C. Both (Nθ, Nφ, B) with eltype FE
  • Fhat: the complex mode array the NUFFT evaluates, assembled from F by _assemble_modes!. The φ axis carries wavenumbers -lmax…lmax (Nφ = 2lmax+1), the θ axis -(lmax+1)…lmax+1 (2lmax+3) — one further out, since an odd-order column of the coefficient array reaches θ-frequency lmax+1. Where the field is real and the NUFFT backend has a real-data transform, only the kθ ≥ 0 half is stored (lmax+2 rows) and that backend supplies the rest.
  • Fslice: (Nθ, Nφ) scratch Matrix each batch slice is copyto!-ed through for the S-step. FastTransforms has no Float32 sphere plan, so it stays double precision and the copy converts.
  • sph_plan, sph_plan_adj: FastTransforms plan_sph2fourier (P) and its adjoint on a (Nθ, Nφ) slice. P alone is the whole S-step — its output is already the bivariate Fourier series, so synthesis is P·C → assemble → one NUFFT, with no equiangular grid in between.

nodes.nufft_type2 is the type-2 handle (iflag = +1, synthesis N) and nodes.nufft_type1 the type-1 handle (iflag = -1, adjoint N†). iflag = +1 supplies the reconstruction sign directly, so the modes need no conjugate-transpose. The axis convention is x = θ, y = φ, and both mode axes are in FlowTransformBindings.CenteredModes() order, the signed wavenumber ranges above, so nothing is shifted per point.

FastTransforms runs on the host, so a NUSHTplan holds host arrays; make_plan builds a RingNUSHTplan for device nodes.

source
NUFSHT.RingNUSHTplan — Type
RingNUSHTplan{T,FE}

A scalar transform through a spin-0 plan, in precision T, on the host or the nodes' device. make_plan builds one for device nodes and for TensorProduct grids. Its coefficients are (lmax+1, 2lmax+1, B) in the sph_mode layout and pass through the spin-0 layout by scalar_to_spin0! and spin0_to_scalar!. It supports scalar transforms, fits, analyses and filters. Synthesis reads the slots of degree l ≤ lmax; the adjoint writes zero in the others.

Fields: lmax, B and tol as a NUSHTplan's; spin, the spin-0 plan; sf, the spin-0 coefficients the conversions pass through; C, the filter scratch.

source
NUFSHT.TensorProduct — Type
TensorProduct()

Declare separate latitude and longitude axes for a spherical transform.

Longitudes sample one full circle at equal spacing, with the endpoint excluded. Fields follow (length(θ), length(φ), ntrans) in column-major order.

source
NUFSHT.close! — Function
close!(plan::NUSHTplan)

Free every NUFFT plan the plan owns, now: its own and any narrower set _build_width! cached for a compacted solve. A plan left unreachable has its host NUFFT plans freed by collection, and its cuFINUFFT plans only by this. Safe to call more than once.

source
NUFSHT.set_nodes! — Function
set_nodes!(plan, θ_nodes, φ_nodes) -> plan

Move a plan's nodes to new positions, reusing every structure fixed by (lmax, B, T) — the FastTransforms sphere plans, the FFTW plans and all coefficient buffers. The NUFFT plans' point tables are rebuilt, and any reduced-width plan pair a batched solve cached is released, to be rebuilt at the new nodes if a later solve narrows again.

The points may move anywhere. Changing how many there are additionally needs the plan's point-indexed buffers to be replaced, which requires make_plan(…; point_count = VariableCount()); a plan built with the default FixedCountNodes throws a DimensionMismatch.

With the count unchanged and no reduced-width plans cached, this rewrites array contents only.

source
NUFSHT.plan_memory — Function
plan_memory(plan) -> NamedTuple

Bytes held by each of the plan's own buffers, plus their total, so a caller can see where a plan's memory goes and what upsampfac, ntrans or the element type do to it.

This counts what the plan allocates in Julia. A backend holding its oversampled grid in C (FINUFFT) is invisible to any Julia-side accounting, Base.summarysize included — measure that as the resident set of a process that builds one plan. An empty slot counts as zero.

source
NUFSHT.coefficient_size — Function
coefficient_size(plan) -> NTuple{3,Int}

The shape of the coefficient array plan transforms: (Nθ, Nφ, B) for a scalar plan in FastTransforms' layout, (lmax+1, 2lmax+1, B) for a spin plan.

source
NUFSHT.allocate_coefficients — Function
allocate_coefficients(plan) -> AbstractArray

A zeroed coefficient array for plan, of coefficient_size(plan), in the plan's coefficient element type and array type, so a device plan returns a device array.

source

Which directions a plan holds

directions says which transform directions a plan holds; asking a synthesis-only plan to analyse raises. Where a backend's plan carries no direction of its own, both directions share one object and the choice costs nothing either way.

NUFSHT.AbstractPlanDirections — Type
AbstractPlanDirections

Which transform directions a plan is built for. A plan built for synthesis alone holds no type-1 NUFFT, and anything needing the adjoint throws, naming the keyword to change. A backend allocates most of its working memory when a transform executes, so the saving is the type-1 plan's own storage.

source
NUFSHT.SynthesisOnly — Type
SynthesisOnly <: AbstractPlanDirections

Build the synthesis (type-2) plan only. nusht_type2! works; anything needing the adjoint throws and names the keyword to change.

source

Node sets

A plan's points can be moved without rebuilding it. The node set, chosen by point_count, fixes whether the point count may change too.

NUFSHT.AbstractNodeSet — Type
AbstractNodeSet

The point-dependent half of a plan: the M scattered nodes, the (M, B) strengths buffer, and the NUFFT handles, which own the loaded point tables and so belong with the points.

Both concrete forms let the nodes move freely (that only rewrites array contents). They differ in whether the count may change, which is the only thing that requires rebinding a field: FixedCountNodes is immutable, VariableCountNodes is not. make_plan's point_count keyword picks one; the immutable form is the default.

source
NUFSHT.FixedCountNodes — Type
FixedCountNodes <: AbstractNodeSet

Immutable node set — the default. The nodes may move anywhere via set_nodes!; only their count is fixed, because it sizes the point-indexed buffers.

source
NUFSHT.VariableCountNodes — Type
VariableCountNodes <: AbstractNodeSet

Node set whose three point-sized fields are assignable, so set_nodes! also accepts a different number of points. The NUFFT handles stay const; setting their points updates the count in place. Request one with make_plan(…; point_count = VariableCount()).

source

Core transforms

NUFSHT.nusht_type2! — Function
nusht_type2!(f, C, plan)

Type 2 (synthesis): evaluate the field with spherical harmonic coefficients C at the M scattered points, writing values into f. Batched: C is (Nθ, Nφ) / (Nθ, Nφ, B) and f is length-M / (M, B).

Algorithm A = N·F·S: plan_sph2fourier to the bivariate Fourier series (S) → assemble the complex mode array (F) → NUFFT type 2 (N). A RingNUSHTplan converts C to spin-0 coefficients and synthesizes those, reading only the slots of degree l ≤ lmax.

source
nusht_type2!(fs, Cs, plans; execution = AutoBackend()) -> fs

Synthesize a collection of independent problems: for each i, nusht_type2!(fs[i], Cs[i], plans[i]). execution = ThreadedBackend() runs the problems on concurrent tasks and requires using OhMyThreads; AutoBackend() takes it when Julia has more than one thread and OhMyThreads is loaded, and SerialBackend() otherwise.

source
NUFSHT.nusht_type1! — Function
nusht_type1!(C, f, plan)

Type 1 (adjoint): given field values f at the M scattered points, apply A† and write the result to C. This is the exact Euclidean adjoint of nusht_type2!, its transpose, so A†A is Hermitian positive semidefinite and usable by an iterative solver. It carries no quadrature weights. On a NUSHTplan it fills every slot of C, the supernumerary ones included; a RingNUSHTplan writes zero in those. nusht_analyze! gives the coefficients of f.

source
nusht_type1!(C, f_local, plan, execution) -> C

A†f over the points of every process execution names, plan and f_local being this process's: under MPIBackend(; comm) (with MPI loaded) each rank's share, summed over the ranks of comm into C on every rank. A local or AutoBackend() backend names this process alone, and gives nusht_type1!(C, f_local, plan).

source
nusht_type1!(Cs, fs, plans; execution = AutoBackend()) -> Cs

Adjoint analysis over a collection of independent problems; see nusht_type2!.

source
NUFSHT.nusht_analyze! — Function
nusht_analyze!(C, f, plan; weights = nothing, ws, maxiter, rtol, conlim) -> (; C, iterations, residual, converged)

The coefficients of the field f sampled at the points of a scalar or spin plan, written into C. With weights, one per point in the plan's array type, the quadrature Cₖ = Σⱼ wⱼ fⱼ conj(Yₖ(xⱼ)): one adjoint transform, iterations = 0, residual = 0, converged = true, and the expansion of a degree-lmax field when the rule integrates the product of two degree-lmax harmonics exactly. Without, the least-squares fit nusht_solve! (spin: nusht_solve_spin!), which takes the remaining keywords; the quadrature does not use them.

A point of zero weight contributes nothing to the quadrature, whatever f holds there (a NaN on masked land). A scalar plan's slots above degree lmax are zero, and a real-field spin plan returns the Hermitian coefficients of the real field. The quadrature allocates nothing, the fit nothing once ws is held.

source
nusht_analyze!(C, f_local, plan, execution; weights = nothing, …) -> (; C, iterations, residual, converged)

The analysis over the points of every process execution names, plan, f_local and weights being this process's: under MPIBackend(; comm) (with MPI loaded) the quadrature summed over the ranks of comm, or the fit nusht_solve!(C, f_local, plan, execution) (spin: nusht_solve_spin!), with the coefficients on every rank. A local or AutoBackend() backend names this process alone, and gives nusht_analyze!(C, f_local, plan).

source
nusht_analyze!(Cs, fs, plans; execution = AutoBackend(), weights = nothing, kwargs...) -> Cs

Analysis over a collection of independent problems, scalar or spin plans: for each i, nusht_analyze!(Cs[i], fs[i], plans[i]; weights = weights[i], kwargs...), the fit when weights is nothing. execution is as in nusht_type2!.

source
NUFSHT.nusht_solve! — Function
nusht_solve!(C, f, plan; ws = FlowTransformBindings.LSMRWorkspace(plan), weights = nothing,
             maxiter = 500, rtol = 1e-6, conlim = 0) -> (; C, iterations, residual, converged)
nusht_solve!(C, f, FlowTransformBindings.RangeWeighted(plan, weights); ws, …)

Exact inversion: solve min ‖A c − f‖ for the coefficients C of each of the B columns by LSMR (FlowTransformBindings.lsmr!), ws holding the solver's arrays so a solve that reuses it allocates nothing.

weights, nonnegative and one per point, makes it min Σⱼ wⱼ |(A c − f)ⱼ|²; a zero weight leaves its point out, whatever f holds there (a masked NaN, say). The points' quadrature weights or their areas bring A^H W A close to a multiple of the identity, and the iteration count down with it; for data the degree-lmax harmonics represent, the solution is the unweighted one. The second form takes the weighted operator built once, so a repeated weighted solve allocates nothing either.

A column stops once ‖A†r‖ ≤ rtol ‖A†f‖, when LSMR's estimate of cond(A) reaches conlim (1/eps(T) at 0), or when its Krylov process ends exactly; residual is the largest ‖A†r‖/‖A†f‖, at least eps(T), and ws.residual and ws.status hold each column's. Points that do not determine the coefficients (M below (lmax+1)², or clustered) make A rank deficient, and a column then stops on conlim with converged == false.

source
nusht_solve!(C, f_local, plan, execution; ws, weights = nothing, …) -> (; C, iterations, residual, converged)
nusht_solve!(C, f_local, FlowTransformBindings.RangeWeighted(plan, weights), execution; ws, …)

The fit over the points of every process execution names, plan, f_local and weights being this process's: under MPIBackend(; comm) (with MPI loaded) each rank's share, the coefficients replicated on every rank of comm. A local or AutoBackend() backend names this process alone, and gives nusht_solve!(C, f_local, plan). The keywords are those of nusht_solve!(C, f, plan); the second form takes this process's weighted operator built once.

source
nusht_solve!(Cs, fs, plans; execution = AutoBackend(), kwargs...) -> Cs

Exact inversion over a collection of independent problems; kwargs go to the single-problem method. execution is as in nusht_type2!.

source

Spin-weighted transforms

Synthesis/analysis/inversion of spin-weighted (spin = s) fields at arbitrary scattered points: the ring S-step turns the coefficients into a bivariate Fourier series and a 2-D NUFFT evaluates it. Spin-1 is the tangent-vector case (velocity u_θ + i u_φ), enabling vector / Helmholtz decomposition on scattered spherical data.

NUFSHT.make_spin_plan — Function
make_spin_plan([FE = Complex{float(eltype(θ_nodes))},] θ_nodes, φ_nodes, lmax, s; execution = AutoBackend(), tol=1e-10, ntrans=1, …)

Build a SpinNUSHTplan. Colatitudes θ ∈ [0,π], longitudes φ ∈ [0,2π).

FE is the field element type, positional as in make_plan; a spin field is complex in general, hence the default. A real FE asserts the field's values are real, which makes the mode array conjugate-symmetric, so the plan forms and transforms only its m' ≥ 0 half — correct only if the coefficients satisfy the reality condition.

The step from coefficients to the bivariate Fourier series is the ring S-step (SpinNUSHTplan).

nthreads and upsampfac are as in make_plan; nthreads is also the task count of the S-step, which divides its orders among them. execution is SerialBackend(), ThreadedBackend(), AutoBackend() (the default) or GPUBackend(b) as in make_plan, with the same precedence of an explicit nthreads. A spin plan holds one process's points; an MPI fit passes each rank's plan to nusht_solve_spin!(sf, f_local, plan, MPIBackend(; comm)), and an MPI analysis to nusht_analyze!(sf, f_local, plan, MPIBackend(; comm)).

source
make_spin_plan(FE, θ, φ, lmax, s, TensorProduct(); ntrans = 1, execution = AutoBackend())

Build a spin transform using latitude degree sums and longitude FFTs.

θ contains colatitudes in [0, π]; φ is a range of at least 2lmax + 1 longitudes.

source
NUFSHT.SpinNUSHTplan — Type
SpinNUSHTplan{T}

Plan for spin-s non-uniform spherical harmonic transforms at M scattered points up to degree lmax, transforming B co-located fields per call. Owns persistent NUFFT plans (type 2 iflag=+1, type 1 iflag=−1) over the nodes (−θ, φ), and the ring S-step (_RingEngine) that takes coefficients to the bivariate Fourier series G and back: each order's degree sum on equispaced colatitudes by the recurrence of d^ℓ_{m,−s} in ℓ, then one FFT per order, in the plan's precision T, on the host or on the nodes' device; its relative error grows as lmax eps(T) in Float32 and as lmax^{3/2} eps(T) in wider precisions.

source
NUFSHT.nusht_type2_spin! — Function
nusht_type2_spin!(f, sf, plan) -> f

Spin-weighted synthesis: evaluate the spin-s field with coefficients sf at the M scattered points, writing complex values into f. Batched: sf is (lmax+1, 2lmax+1[, B]), f is length-M / (M, B).

source
nusht_type2_spin!(fs, sfs, plans; execution = AutoBackend()) -> fs

Spin-weighted synthesis over a collection of independent problems, execution as in nusht_type2!.

source
NUFSHT.nusht_type1_spin! — Function
nusht_type1_spin!(sf, f, plan) -> sf

Exact Euclidean adjoint of nusht_type2_spin!: scattered values f → spin-s coefficients sf, with no quadrature weights; nusht_analyze! gives the coefficients of f.

source
nusht_type1_spin!(sfs, fs, plans; execution = AutoBackend()) -> sfs

Spin-weighted adjoint analysis over a collection; see nusht_type2_spin!.

source
NUFSHT.nusht_solve_spin! — Function
nusht_solve_spin!(sf, f, plan; ws = FlowTransformBindings.LSMRWorkspace(plan), weights = nothing,
                  maxiter = 500, rtol = 1e-6, conlim = 0)
nusht_solve_spin!(sf, f, FlowTransformBindings.RangeWeighted(plan, weights); ws, …)
nusht_solve_spin!(sf, f_local, plan, execution; ws, weights = nothing, …)
nusht_solve_spin!(sf, f_local, FlowTransformBindings.RangeWeighted(plan, weights), execution; ws, …)

Exact inversion of the spin-weighted synthesis at arbitrary scattered points: solve min ‖A sf − f‖ by LSMR on the Golub–Kahan bidiagonalization of A. Batched (B > 1) runs the columns as independent single-column solves. Same contract, return and weights as nusht_solve!: weights, nonnegative and one per point, makes the fit min Σⱼ wⱼ |(A sf − f)ⱼ|², a zero weight leaving its point out, and the forms taking a RangeWeighted take that weighted operator built once. The four-argument forms are the fit over the points of every process execution names, plan, f_local and weights being this process's.

On a real-field plan the fit runs over the (lmax+1)² real degrees of a real field's coefficients (_hermitian_domain), a quarter of the unknowns.

That subspace exists only at s = 0: conjugation maps spin s to -s (conj(ₛY_ℓm) = (-1)^{m+s} ₋ₛY_ℓ,-m), so a real-field plan at s ≠ 0 has no subspace on which the fit is determined, and the solve throws. Its synthesis and adjoint are exact. nusht_analyze! takes the same plans, with quadrature weights or by this fit.

source
nusht_solve_spin!(sfs, fs, plans; execution = AutoBackend(), kwargs...) -> sfs

Spin-weighted exact inversion over a collection; see nusht_type2_spin!.

source
NUFSHT.sYlm — Function
sYlm(s, ℓ, m, θ, φ) -> Complex

Spin-weighted spherical harmonic ₛY_{ℓm}(θ,φ) = N_ℓ d^ℓ_{m,−s}(θ) e^{imφ} in the Goldberg / Newman–Penrose convention, with d the rotation matrix of wigner_d.

source
NUFSHT.spin_coeff_index — Function
spin_coeff_index(ℓ, m, lmax) -> CartesianIndex

Index into the dense (lmax+1, 2lmax+1) spin coefficient array for degree ℓ, order m.

source
NUFSHT.scalar_to_spin0! — Function
scalar_to_spin0!(sf, C) -> sf

The spin-0 coefficients of the field with scalar coefficients C, written into sf: C in a scalar plan's sph_mode layout, sf complex in a spin plan's spin_coeff_index layout, both (lmax+1, 2lmax+1[, B]). A spin-0 plan synthesizes from sf the field a scalar plan synthesizes from C; the slots of C above degree lmax are not read.

source
NUFSHT.spin0_to_scalar! — Function
spin0_to_scalar!(C, sf) -> C

The inverse of scalar_to_spin0!: the scalar coefficients of the field with spin-0 coefficients sf, written into C, its slots above degree lmax zeroed. A real C receives the coefficients of the field's real part, the whole field when sf is Hermitian, sf[ℓ,-m] = (-1)^m conj(sf[ℓ,m]).

source
NUFSHT.wigner_d — Function
wigner_d(ℓ, m, n, β)

Wigner small-d matrix element d^ℓ_{mn}(β) = ⟨ℓm|exp(-iβ Jy)|ℓn⟩ in the Condon–Shortley basis, by the three-term recurrence in ℓ (FlowTransformBindings.wigner_d!), within ℓ eps of the exact value.

source
NUFSHT._RingEngine — Type
_RingEngine

The latitude recurrence of a spin plan in the plan's precision R: per ring u and pos, u = 1 − x where pos (σ = 1) and 1 + x elsewhere, pos shared by the rings of a host chunk, and x + xl, the ring cosine to twice R's precision (all padded to a whole number of chunks); log2 cos(θ_j/2) and log2 sin(θ_j/2) in S, the precision of the starting values; and per order m the constants of d^{ℓ0}_{m,−s}(θ) = sg · 2^{lC + p1 log2 cos(θ/2) + p2 log2 sin(θ/2)}. work holds one latitude workspace per task on the host, with _RingWork adding the circle FFTs for a scattered-node transform; device plans hold their buffers and FFT plans in work.

source
NUFSHT._RingWork — Type
_RingWork

One host task's latitude recurrence workspace and circle buffer with its FFT plans.

source
NUFSHT._LatitudeWork — Type
_LatitudeWork

One host task's buffers for the ring S-step: the step coefficients A, Cp, Cm, Γ (α, c₊, c₋, γ) of an order and the weighted coefficients cr, ci of up to two batch columns, (lmax+1) long; the ring values Fr, Fi of those columns; the adjoint's ring state Ys, Es, Ks between sweeps and its per-lane sums Q over a sweep's degrees, (lane, degree, re/im, column).

source
NUFSHT._ring_tables — Function
_ring_tables(R, S, lmax, s, padded) -> NamedTuple

The host tables of a ring engine: u in R from 2sin²(θ_j/2) or 2cos²(θ_j/2) in BigFloat, pos true on the chunks whose middle lies at θ ≤ π/2, x, xl in R from cos θ_j in BigFloat, and the logarithms and order constants in S, formed in Float64 at least. padded rounds the ring count up to whole chunks, the extra rings starting at zero.

source
NUFSHT._ring_check_interval — Function
_ring_check_interval(R, lmax) -> Int

Steps a host chunk takes between scale checks. One step multiplies a value by at most √(2ℓ+1) + 2 at degree ℓ ≤ lmax, so over the interval a value below 2^{K/2} stays below 2^{K−8}, and a value held at weight zero stays below 2^{−K−8} of the largest.

source

Filtering

NUFSHT.nusht_synthesize! — Function
nusht_synthesize!(f_out, C, filter, plan) -> f_out

Scale coefficients C by filter's transfer function and synthesize at the plan's points. C is not modified — the scaling runs in the plan's own scratch — so one analysis feeds any number of filters:

nusht_solve!(C, f, plan; ws = ws)
for (out, filt) in zip(outs, filters)
    nusht_synthesize!(out, C, filt, plan)
end

nusht_filter! is a solve followed by this, and so re-fits per filter; use the pair when filtering one field at several scales, since the fit is the expensive half.

source
NUFSHT.nusht_filter! — Function
nusht_filter!(f_out, f_in, filter, plan; ws = FlowTransformBindings.LSMRWorkspace(plan), kwargs...)

Apply a spectral filter to f_in at the scattered points, writing to f_out (both length-M / (M, B)): fit coefficients with nusht_solve! → apply_transfer! (× H(ℓ)) → nusht_type2!. kwargs (rtol, maxiter, …) go to the solve. Uses the plan's coefficient scratch, and is allocation-free when a ws is supplied.

The filter is A H A⁺, with A⁺ the least-squares fit. At scattered points the adjoint A† is the transpose of the synthesis, and A H A† is a smoothing; the two agree only on a quadrature grid. The fit is iterative, so hold a ws and reuse it across calls.

source
nusht_filter!(outs, ins, filter, plans; execution = AutoBackend()) -> outs

Spectral filtering over a collection of independent problems; see nusht_type2!.

source
NUFSHT.nusht_filter_renorm! — Function
nusht_filter_renorm!(f_out, mask, filter, plan; mask_filt=similar(f_out), ws, C_mask=nothing,
                     threshold=0.01)

Renormalise the output of nusht_filter! to correct for land/ocean masking: divide by the filtered mask (the fraction of kernel weight over ocean). f_out must have been produced by nusht_filter!(f_out, f .* mask, filter, plan). Points where the filtered mask is below threshold are set to 0. Pass a reusable mask_filt scratch (shaped like f_out) to run allocation-free.

source

Transfer functions (spectral filters)

NUFSHT.GaussianTransfer — Type
GaussianTransfer

Gaussian spectral filter: H(ℓ) = exp(-ℓ(ℓ+1) σ²/2)

where σ = scalem / Rm is the dimensionless filter width. It is the heat kernel of the unit sphere at time σ²/2, exp(σ²Δ/2) with Δ Y_ℓm = -ℓ(ℓ+1) Y_ℓm, the sphere's counterpart of a Gaussian convolution in the plane. At degree ℓ the spatial scale is approximately R/ℓ.

source
NUFSHT.gaussian_from_scale — Function
gaussian_from_scale(scale_m, R_m=6.371e6)

Construct a GaussianTransfer from a physical filter scale in meters, with σ = scale_m / R_m; GaussianTransfer(σ²) takes the squared dimensionless width itself.

source
NUFSHT.TopHatTransfer — Type
TopHatTransfer

Ideal low-pass (sharp spectral cutoff) filter: H(ℓ) = 1 for ℓ ≤ L, else 0. Physical-space equivalent is a convolution with a zonal kernel whose Legendre spectrum is a boxcar. Note: this is spectrally sharp but spatially oscillatory (Gibbs phenomenon).

source
NUFSHT.kernel_transfer — Function
kernel_transfer(filter, ℓ) -> H

Evaluate the spectral transfer function H(ℓ) for a given filter type and degree ℓ. Returns a real scalar in [0, 1].

source
NUFSHT.cutoff_degree — Function
cutoff_degree(scale_m, R_m=6.371e6)

Compute the spherical harmonic cutoff degree L corresponding to a physical filter scale in meters on a sphere of radius R_m.

The relationship is L ≈ π * Rm / scalem, analogous to Nyquist for a circle of circumference 2π R_m.

source

Parallel execution

Parallelism is selected by a ComputationalBackends.AbstractExecutionBackend, with the backends themselves provided by the accelerator extensions (using OhMyThreads / KernelAbstractions / Distributed / MPI). See the performance section of the README for the threads-vs-processes trade-offs.

make_plan and make_spin_plan take the execution keyword for where the plan runs, and the collection entry points farm independent problems across it. nusht_type1!, nusht_analyze!, nusht_solve! and nusht_solve_spin! take a backend as a fourth argument, MPIBackend(; comm) for instance, and then treat the plan as one rank's share of a single transform's points.

NUFSHT.nusht_type2 — Function
nusht_type2(θs, φs, Cs, lmax; execution = AutoBackend(), tol, ntrans, …) -> fs

Synthesize N independent problems given their node sets: for each i a plan is built from (θs[i], φs[i]) with the remaining keywords, Cs[i] is evaluated, and the field is returned as fs[i].

execution = DistributedBackend() (with Distributed loaded) takes this form, each worker building its own plans. A local backend runs the problems in turn on the calling process, where the plan-collection nusht_type2! reuses plans already built; AutoBackend() resolves as it does there.

source
NUFSHT.nusht_solve — Function
nusht_solve(θs, φs, fs, lmax; execution = AutoBackend(), tol, rtol, maxiter, …) -> Cs

Exact inversion of N independent problems given their node sets; see nusht_type2.

source

Plotting

NUFSHT.plot_field — Function
plot_field(θ, φ, f; colormap=:RdBu, markersize=8, title="", colorbarlabel="Field value") -> Figure

Scatter-plot a scalar field f sampled at scattered colatitude/longitude points (θ ∈ [0,π], φ ∈ [0,2π)), coloured by real(f) (so a complex/spin field plots its real part). Longitude on x, colatitude on y (poles top/bottom). Method supplied by NUFSHTCairoMakieExt — load it with using CairoMakie.

source

Internal helpers

NUFSHT.apply_transfer! — Function
apply_transfer!(C, filter, lmax)

Multiply a FastSphericalHarmonics coefficient array C — size (lmax+1, 2lmax+1) or batched (lmax+1, 2lmax+1, B) — in-place by the transfer function H(ℓ) for each degree ℓ (broadcast across the batch dimension).

source
NUFSHT._nusht_true_adjoint! — Function
_nusht_true_adjoint!(C, f, plan, k = plan.B, kdfn = k)

The exact Euclidean adjoint of nusht_type2!: type-1 NUFFT, the transpose of the mode assembly, then P' per column. k bounds the columns the sphere loop visits and kdfn the NUFFT plan width.

source
NUFSHT._assemble_modes! — Function
_assemble_modes!(Z, G, lmax, fold)

G (bivariate Fourier coefficients, sph2fourier layout, (lmax+1, 2lmax+1, B)) → Z, the complex mode array with Z[kθ+offθ, kφ+offφ] the coefficient of exp(i(kθ·θ + kφ·φ)), exactly. The device method is a @kernel over the same _mode_entry.

Z is the full (2lmax+3, 2lmax+1, B) array, or with fold the kθ ≥ 0 half (lmax+2 rows) a real field's Hermitian array stores (_folded). Every entry is written, so Z needs no fill!.

source
NUFSHT._assemble_modes_adjoint! — Function
_assemble_modes_adjoint!(G, Z, lmax, fold)

Exact Euclidean adjoint of _assemble_modes!, one entry of G per _mode_adjoint_entry. A real G takes the real part, which is the adjoint of the real→complex embedding; a complex one does not. The device method is a @kernel over the same per-element map.

source
NUFSHT._mode_entry — Function
_mode_entry(CT, G, lmax, r, c, b, offθ, offφ, n0, nm, h) -> CT

The coefficient of exp(i(kθ·θ + kφ·φ)) at mode-array position (r, c) of batch slice b, gathered from the bivariate Fourier coefficients G. offθ/offφ map a wavenumber to its index, so the folded layout is just offθ = 1 — every row it holds has kθ ≥ 0 and the gather is unchanged.

source
NUFSHT._mode_adjoint_entry — Function
_mode_adjoint_entry(CT, Z, lmax, i, j, b, offθ, offφ, fold, n0, nm, h) -> CT

Entry (i, j) of batch slice b of the exact Euclidean adjoint: conj(w)·Z summed over the (up to four) mode slots _mode_entry draws that entry into.

On a folded array the kθ < 0 slots are absent, and each retained kθ > 0 row carries twice the weight. The forward needs no such factor — writing the half and letting the backend's complex-to-real transform imply the conjugate is exact — but its transpose does: the embedding E maps the half to the full array by Z[-k] = conj(Z[k]), so E† gives Ẑ[k] + conj(Ẑ[-k]), and with real strengths conj(Ẑ[-k]) = Ẑ[k]. Hence {1, 2, 2, …}: one at kθ = 0, which is its own partner, two above it. The θ axis has odd length 2lmax+3, so it has no self-paired Nyquist row and no third weight.

source
NUFSHT._filter_scratch — Function
_filter_scratch(plan) -> AbstractArray

The coefficient scratch filtering scales in, so the caller's array is left unmodified. Allocated on the first filter call and reused after; a plan that never filters holds none.

source
NUFSHT._valid_indices — Function
_valid_indices(proto, lmax) -> AbstractVector{Int}

Linear positions, within one coefficient column, of the (lmax+1)^2 slots holding degrees l ≤ lmax, in the plan's array type. The index rule is FastTransforms' own (sphones): column 1 carries m = 0 for every degree, and the column pair 2j, 2j+1 carries m = ∓j for l = j … lmax, so it occupies only its first lmax+1-j rows; the other lmax(lmax+1) slots hold the supernumerary degrees lmax < l ≤ lmax+|m|.

The solver's vectors are packed to these, (K, B) with K = (lmax+1)^2, so every reduction and update of the iteration runs over the packed length.

source
NUFSHT._sph_pool — Function
_sph_pool(Fslice, P, Padj, nslots, n)

One Fslice and one set of sphere plans per task for nslots tasks, for threading the per-column sphere loops, the first entry the plan's own (Fslice, P, Padj) and the rest built at the plan's thread count n. A FastTransforms plan is not safe to apply concurrently, and the loop's slice buffer is shared, so both have to be replicated. Empty when there is nothing to thread, so a single-threaded plan pays nothing.

Index the result by task chunk. A spawned task owns its chunk index for its whole life, while tasks migrate between threads, so two tasks keyed by Threads.threadid() can share an entry.

source
NUFSHT._plan_threads — Function
_plan_threads(execution, nthreads) -> Union{Nothing,Integer}

The thread count a plan built under execution runs at, given the caller's nthreads: 1 under SerialBackend, which refuses any other count; nthreads under ThreadedBackend when given and Threads.nthreads() when not; nthreads itself under any other backend.

source
NUFSHT._resolve_execution — Function
_resolve_execution(execution) -> AbstractExecutionBackend

NUFSHT's resolution of AutoBackend for a collection of independent problems: ThreadedBackend when Julia has more than one thread and the OhMyThreads extension is loaded, otherwise SerialBackend. Every other backend is returned as given.

source
NUFSHT._PointShare — Type
_PointShare(plan, reduce!)

plan over one share of the points, as the operator of the fit over every share: reduce!(A) sums A in place across the shares, and is applied to the two sums over points LSMR takes, the per-column ‖u‖² and A†u. The coefficients are the same on every share, so every share runs the same recurrence and stops on the same iteration.

source

NUFFT backends and batched widths

NUFSHT.DirectSumNUFFTPlan — Type
DirectSumNUFFTPlan{T,V,S}

Handle for the direct-summation backend: built once over its nodes, points rewritten by _nufft_setpts!, executed repeatedly. nthreads is resolved at construction (0 meaning all Julia threads) and bounds the split in _nufft_exec!.

The phase separates, e^{is(k₁x + k₂y)} = e^{isk₁x} e^{isk₂y}, so a point's n₁·n₂ exponentials are the products of two tables of n₁ and n₂. ex and ey hold those tables, one column per thread.

source
NUFSHT._FTBNUFFT — Type
_FTBNUFFT{P}

A FlowTransformBindings plan read in one direction: type = 2 synthesis, type = 1 its adjoint. The type-1 handle of a plan is derived, reading the plan the type-2 handle owns.

source
NUFSHT._resolve_nufft — Function
_resolve_nufft(backend, FE) -> backend

A concrete backend passes through unchanged. AutoSpectralBackend takes NonuniformFFTs when it is loaded, FINUFFT when only it is, and direct summation when neither is. Override with nufft=.

source
NUFSHT._real_capable — Function
_real_capable(backend) -> Bool

Whether the backend implements a real-data transform: real non-uniform values, and the uniform side stored as the half-spectrum a real signal determines. false by default.

A real field's mode array is exactly Hermitian, so every plan stores only its kθ ≥ 0 half. A backend with a real-data transform reconstructs the conjugate half itself and takes real strengths, halving the spreading and interpolation as well as the FFT; FlowTransformBindings gives one on both libraries. Without one the transform is a half-height complex one, whose missing half _fold_weights! pays for.

Correctness never depends on this: the folded and full assemblies represent the same series.

source
NUFSHT._nufft_share_directions — Function
_nufft_share_directions(backend) -> Bool
_nufft_as_type1(type2_handle) -> handle

Whether one plan serves both transform directions, and the type-1 handle onto the type-2 one when it does. A FlowTransformBindings plan evaluates both, so the analysis handle reads the synthesis plan in the other direction and holds no second plan.

source
NUFSHT._nufft_derived — Function
_nufft_derived(p) -> Bool

Whether this handle reads a plan another handle owns, so its points are set whenever that one's are. false by default. set_nodes! re-points only the handle that owns the plan.

source
NUFSHT._width_narrowable — Function
_width_narrowable(backend) -> Bool
_width_polymorphic(backend) -> Bool

Whether a batched solve can narrow the backend's NUFFT to its live columns once the rest have retired, and whether its plans share one concrete type at every transform count. FlowTransformBindings' FINUFFT plan holds the count at runtime, so one pool element type serves every width. Its NonuniformFFTs plan carries the count in the library's type, so the pool holds one slot per width, typed by FlowTransformBindings.plan_type and filled on first use.

Correctness never depends on either. The per-column sphere loop and the solver's vector reductions narrow on every backend.

source
NUFSHT._pool_sizes — Function
_pool_sizes(B) -> Vector{Int}

Working batch sizes a solve may shrink to: powers of two up to B, plus B itself. Powers of two bound the number of plan sets at log2(B)+1 while never wasting more than a factor of two of transform width, so a column retiring early costs at most one halving of unused work.

source
NUFSHT._nufft_size_pool — Function
_nufft_size_pool(backend, nufft_type2, nufft_type1, widths) -> pool

The store of reduced-width plan sets a batched solve narrows into, filled on demand through _with_pool_entry. Where the backend's plans share one type at every width (_width_polymorphic) it is an empty Vector typed from the plan's full-width pair. Otherwise it holds one slot per width, a Ref whose element type FlowTransformBindings.plan_type derives without building anything, so a width nobody uses is never built and never specialised.

Nothing is built here: only a solve that narrows pays for a width. An empty widths disables narrowing and nothing is ever stored.

source
NUFSHT._pool_recipe — Function
_pool_recipe(backend, nt, uf)

The build inputs a narrower plan set needs that cannot be recovered from a plan: the resolved NUFFT backend, its thread count and its oversampling factor. Everything else — mode counts, tolerance, nodes, realness — is read back off the plan when a width is built. narrowable is _width_narrowable of the backend; how the widths are stored is _nufft_size_pool's.

source
NUFSHT._build_width! — Function
_build_width!(plan, k, E) -> E

Build the NUFFT plan pair for working width k as the pool entry type E, whose handle types the library plan is asserted to (_make_nufft_as).

Called on a pool miss, which stores the entry in plan.size_pool, so it is not safe to call concurrently on a shared plan — the same restriction a plan already carries, since a NUFFT plan cannot be executed concurrently either.

source
NUFSHT._pool_lookup! — Function
_pool_lookup!(pool, k, build) -> entry

The plan pair for working width k in a Vector pool, built by build(k, E) as the pool's element type E and stored on a miss.

source
NUFSHT._pool_built — Function
_pool_built(pool) -> Int

How many reduced widths currently hold plans, for either pool shape: an on-demand Vector holds only the built widths, and a per-width slot holds nothing until its width is built.

source

Spin plans: folds, the real-field fit and the ring engine

NUFSHT.FullModes — Type
FullModes, FoldedComplex, FoldedReal

Which Hermitian treatment a spin plan's mode array needs. A complex field has no symmetry to exploit (FullModes); a real one stores only m' ≥ 0 either way, and the two folded kinds differ in who supplies the absent m' < 0 half, which fixes the row indexing and the weights.

The kind is read off the plan: only a half-height complex transform has a θ_shift, and only a real-data transform has real strengths, so the pair (θ_shift, fbuf) names all three.

source
NUFSHT._hermitian_domain — Function
_hermitian_domain(plan) -> Bool

Whether the plan's field is real, and so whether its coefficients are constrained.

A real field's coefficients are Hermitian, sf[ℓ,-m] = (-1)^m conj(sf[ℓ,m]) from conj(Y_ℓm) = (-1)^m Y_ℓ,-m: (lmax+1)² real numbers, of the (lmax+1)(2lmax+1) complex ones the array holds. A solve runs on that subspace. Off it the operator's values are set by the backend's fold, so a fit over the whole array has no unique answer.

source
NUFSHT._herm_entry — Function
_herm_entry(CT, p, ℓ, m, po) -> CT

The entry _unpack_herm! writes at degree ℓ, order m, from the packed column starting after linear offset po of p: zero where |m| > ℓ, the real value at m = 0, (p[2m] + i p[2m+1])/√2 for m > 0 and (-1)^m times its conjugate for m < 0. One per output entry, so the host loop and the device kernel evaluate the same expression.

source
NUFSHT._pack_entry — Function
_pack_entry(g, t, lmax, b) -> real

Packed value t of column b under _pack_herm!, read from the full array g. With ℓ = isqrt(t-1) and r = t - 1 - ℓ²: the real part of g[ℓ,0] at r = 0, and for m = ⌈r/2⌉ the real (r odd) or imaginary (r even) part of (g[ℓ,m] ± (-1)^m g[ℓ,-m])/√2.

source
NUFSHT._pack_herm! — Function
_pack_herm!(p, g, lmax, B, β = nothing) -> p

The exact adjoint of _unpack_herm! under the real inner product Re⟨a,b⟩. With β given it also folds p ← U†g + β·p, the packed counterpart of FTB.colxpby!, in the same pass.

source
NUFSHT._unpack_herm! — Function
_unpack_herm!(sf, p, lmax, B) -> sf

Expand packed real coefficients into the full Hermitian array. Scaled by 1/√2 off m = 0 so the map is an isometry: ‖U p‖ = ‖p‖, so a minimum-norm solution is minimum-norm on both sides of it. _pack_herm! is its exact adjoint.

source
NUFSHT._ring_engine — Function
_ring_engine(θ, lmax, s, ntasks) -> _RingEngine

The ring S-step for a host plan over nodes θ, in their element type, its starting values in Float64 at least, with one workspace per task.

source