API Reference

Spectra

FlowFieldSpectra.calculate_spectrum — Function
calculate_spectrum(grid, field, ms::Tuple;
                   transform=AutoSpectralBackend(), execution=AutoBackend(), kwargs...)

Spectral coefficients and physical wavenumbers of field sampled on grid (a FlowGeometries grid), whose architecture and geometry define the coordinate system. The two backend axes compose freely:

  • transform::SpectralBackends.AbstractSpectralBackend — the spectral math (AutoSpectralBackend (default), FFTSpectralBackend, NUFFTSpectralBackend, FSHTSpectralBackend, NUFSHTSpectralBackend, DirectSumSpectralBackend).

    AutoSpectralBackend picks the fastest transform this grid admits among the extensions loaded, and only ever substitutes one computing the same coefficients: an FFT on a uniform Cartesian grid (asked for its own length per axis), the hybrid FFT/NUFFT composite where a grid is uniform in some directions and stretched in others, a NUFFT on a nonuniform or scattered Cartesian grid, the FastSphericalHarmonics analysis on its own Clenshaw–Curtis grid, and NUFSHT on any other spherical grid. With no fast transform loaded it warns once and runs the direct sum, an O(∏ms · N) / O(L³) correctness reference; name DirectSumSpectralBackend() explicitly to ask for it.

  • execution::ComputationalBackends.AbstractExecutionBackend — where/how it runs (SerialBackend, ThreadedBackend, GPUBackend, DistributedBackend, MPIBackend, AutoBackend (default)).

Data model

field is an AbstractArray shaped (spatial…, batch…): the first ndims(grid) dims are spatial (and must equal size(grid)); every trailing dim is a batch dim (components, levels, time, ensemble — any number), carried through and preserved. Structured grids take an (N_1,…,N_D, batch…) tensor (spherical: (nlon, nlat, batch…)); unstructured grids take (N, batch…). A Tuple of equal-shaped arrays stacks them along a new trailing batch axis.

ms is the spectral resolution: Cartesian (m_1,…,m_D); spherical (Nθ, Nφ) with lmax = Nθ-1. On a masked spherical grid inactive says how the inactive cells enter: ZeroFill (the default) or Exclude.

Preprocessing

preprocess::Preprocess detrends, tapers and zero-pads the field first (see preprocess_field); omitting it transforms the field as given, copying nothing. A taper is scaled to unit mean square, so Parseval holds on the returned coefficients with no correction applied afterwards. pad > 1 lengthens the grid's axes and scales ms by the same factor, so the wavenumber spacing narrows. On a host execution backend the call runs through a PreprocessedPlan, so a slice's non-finite values are invalid points, weighed out of its fit, its window's normalization and its quadrature.

Returns

(coeffs, ks_phys) — the coefficients and the physical wavenumber coordinates per spectral axis.

The field's element type picks the coefficient layout on both geometries. Cartesian: a complex field gives the full native cube (ms…, batch…). A real field gives the rfft-packed half (b_1÷2+1, b_2…, batch…) of its coefficient box b, which is ms with every even m_d whose axis tells +m_d/2 from -m_d/2 apart (a stretched axis, a point set, an axis transformed below its length) widened to m_d + 1 modes, -m_d/2 … m_d/2 in FFT order (Grids.mode_box). The box holds the transform's modes and their conjugate mirror, and zero at a mode in neither (+m_d/2 with -m_e/2 on two widened axes d, e ≥ 2). Both are complex-valued. Spherical: (Nθ, Nφ, batch…), real for a real field (the basis is the real spherical harmonics) and complex for a complex one; see sph_coeff_type.

source
FlowFieldSpectra.calculate_spectrum! — Function
calculate_spectrum!(coeffs, plan::HybridPlan, field) -> ks

Execute a prebuilt hybrid plan in place. field is (N_1…N_D, batch…); coeffs is the packed half of the coefficient box (Grids.mode_box) for a real field and the full native spectrum for a complex one, on the host or the plan's device. The uniform-axis FFT, the per-axis NUFFT plans and the working arrays are reused across calls.

source
calculate_spectrum!(coeffs, grid, field, ms; transform=AutoSpectralBackend(), execution=AutoBackend(), kwargs...)

In-place calculate_spectrum: write the coefficients into the preallocated coeffs, shaped as calculate_spectrum returns them, and return ks_phys. transform resolves as calculate_spectrum resolves it. The direct sum on SerialBackend/ThreadedBackend writes into coeffs directly; every other transform runs through a plan built for this call and released after it, an FFT planned without measurement as calculate_spectrum plans it. A repeated caller holds one, built with plan_spectrum and run with calculate_spectrum!(coeffs, plan, field).

source
calculate_spectrum!(coeffs, plan::DirectSumSphericalPlan, field) -> ks

Fill preallocated coeffs (Nθ, Nφ, batch…) with the spherical spectrum of field (spatial…, batch…), reusing plan's nodes / ring table / quadrature / Legendre tables.

source
calculate_spectrum!(coeffs, plan::DirectSumCartesianPlan, field) -> ks

Fill preallocated coeffs (the packed half of the coefficient box for a real field, full native for a complex one) with the Cartesian spectrum of field (spatial…, batch…), reusing plan's DFT matrices and working arrays.

source
calculate_spectrum!(coeffs, plan::NUFFTPointPlan, field) -> ks_phys

Execute a point-set NUFFT plan in place. field is (N, batch…); coeffs is the packed half of the coefficient box (Grids.mode_box) for a real field and the full spectrum for a complex one.

source
calculate_spectrum!(coeffs, plan::NUFFTSeparablePlan, field) -> ks_phys

Execute a separable structured plan in place. field is (N₁…N_D, batch…); coeffs is the packed half of the coefficient box (Grids.mode_box) for a real field and the full spectrum for a complex one.

source
calculate_spectrum!(coeffs, plan::PreprocessedPlan, field[, valid]) -> ks_phys

Preprocess each batch slice of field into the plan's staging under that slice's valid points, those valid (shaped like field) marks or else those whose value is finite, and transform the result with the inner plan. A slice with no valid point raises.

source
FlowFieldSpectra.synthesize — Function
synthesize([T,] grid, coeffs, ms::Tuple; transform=AutoSpectralBackend(), execution=AutoBackend(),
           iflag=1)

The series with coefficients coeffs evaluated at the grid points, a field of element type T (positional, as for zeros(T, …); real(eltype(coeffs)) when omitted): f_j = Σ_k C_k e^{+iflag·ik·(x_j − x₀)} on a Cartesian grid, with x₀ each direction's smallest coordinate, and f_j = Σ_{l,m} C_lm Y_lm(x_j) on a sphere. A real T consumes the packed half a real Cartesian field transforms to, over the coefficient box of an ms-mode transform on grid (see calculate_spectrum), and writes a real array directly: the sum runs over the whole box, each stored mode k₁ > 0 with its conjugate partner. A complex T consumes the full native spectrum (ms…, batch…). Spherical coefficients are (Nθ, Nφ, batch…) either way, a real T taking the real part of a complex series. Returns an array (spatial…, batch…) shaped as the forward's input.

synthesize is the adjoint of calculate_spectrum under the grid's quadrature: Σ_k conj(C_k)·F(f)_k = Σ_j w_j conj(S(C)_j) f_j, with w the weights the forward integrates with (w_j/Σw of the grid measure on a Cartesian grid, the spherical weights totalling 4π on a sphere). It inverts calculate_spectrum where that quadrature is exact on the series: a uniform periodic grid with ms == size(grid), and FastSphericalHarmonics on its own grid. On a stretched or scattered grid the composition is not the identity; recovering the coefficients a field was synthesized from is a least-squares fit (analysis = LeastSquares() with NUFSHTSpectralBackend).

transform selects the synthesis the same way calculate_spectrum selects the forward, and AutoSpectralBackend resolves it by the same rules; the direct sum serves any grid.

source
FlowFieldSpectra.Plans.plan_spectrum — Function
plan_spectrum(grid, ::Type{T}, ms; transform=AutoSpectralBackend(), execution=AutoBackend(), batch=(), kwargs...)
plan_spectrum(transform, execution, grid, ::Type{T}, ms; batch=(), kwargs...)

Construct a reusable AbstractSpectralPlan for the transform×execution backend pair on grid at spectral resolution ms, transforming a field with trailing batch shape batch of element type T in one batched execution. The keyword form resolves execution and forwards to the canonical positional form implemented by the backend extensions. Requires the transform's extension to be loaded.

Execute a plan with calculate_spectrum!(coeffs, plan, fields).

source
FlowFieldSpectra.Plans.AbstractSpectralPlan — Type
AbstractSpectralPlan

Supertype for reusable transform plans, tied to the grid, the spectral resolution ms, the trailing batch shape and the element type. Build one with plan_spectrum and execute it on many fields with calculate_spectrum!.

A plan holds working buffers that each execution overwrites, so one task at a time may execute it; tasks running concurrently each build their own plan.

source
FlowFieldSpectra.sph_coeff_type — Function
sph_coeff_type(::Type{T}, ::Type{FT}) -> Type

Element type of a spherical coefficient array for a field of element type T on a grid of element type FT: FT for a real field and Complex{FT} for a complex one. The basis is the real spherical harmonics, so a real field's coefficients are real.

source

Every transform has a reusable plan, the direct sum included: plan_spectrum holds what a grid fixes — the FFT plan, a NUFFT's point sorting, the direct sum's per-axis DFT matrices and working arrays, a spherical grid's nodes and quadrature, FastTransforms' plans — so calculate_spectrum!(coeffs, plan, field) in a time loop allocates nothing of its own on SerialBackend. A plan runs on the execution backend it was built for: under ThreadedBackend the direct sum's threaded loops and the libraries' threads, and under GPUBackend device plans for every transform, the hybrid FFT/NUFFT composite and the direct sum included. Under DistributedBackend and MPIBackend every worker or rank holds the plan of its share, the points of a point set or the batch columns, as calculate_spectrum divides the work. A plan holds working buffers, so one task at a time executes it.

A plan reports the shape and element type of its output:

FlowFieldSpectra.Plans.coefficient_size — Function
coefficient_size(plan) -> Dims

Shape of the coefficient array calculate_spectrum!(coeffs, plan, field) fills, batch axes included.

A real Cartesian field's is the packed half (box[1]÷2+1, box[2:D]…, batch…) of its coefficient box (Grids.mode_box) and a complex one's the full native (ms…, batch…); a spherical plan's is (lmax+1, 2lmax+1, batch…).

source
FlowFieldSpectra.Plans.wavenumbers — Function
wavenumbers(plan) -> Tuple

The physical wavenumber axes the matching calculate_spectrum returns as its second value, in the same packed native order as the coefficients: rfftfreq-like on a halved axis, fftfreq on a full one, and (0:lmax, -lmax:lmax) for a spherical plan.

source
FlowFieldSpectra.Plans.close! — Function
close!(plan) -> nothing

Release the library resources plan holds; idempotent. A plan over FINUFFT holds C memory that only this frees. A plan over a Julia-only transform holds none, and this does nothing.

source
p = plan_spectrum(grid, Float64, ms; transform = FFTSpectralBackend(), batch = (nz,))
coeffs = allocate_coefficients(p)          # right shape and element type, from the plan alone
for t in times
    ks = calculate_spectrum!(coeffs, p, field_at(t))
end

The element type is not implied by the size: a Cartesian plan's coefficients are complex, while a spherical plan's follow the field and are real for a real one.

Synthesis, the series evaluated at the grid's points, has the same pair, so a round trip on one grid reuses both directions. It inverts calculate_spectrum on a uniform periodic grid and is its adjoint under the grid's quadrature on any grid:

FlowFieldSpectra.Plans.AbstractSynthesisPlan — Type
AbstractSynthesisPlan

Supertype for reusable synthesis plans, the counterpart to AbstractSpectralPlan, tied to the grid, the spectral resolution ms, the trailing batch shape and the element type. Build one with plan_synthesis and execute it on many coefficient sets with synthesize!.

A plan holds working buffers that each execution overwrites, so one task at a time may execute it; tasks running concurrently each build their own plan.

source
FlowFieldSpectra.Plans.plan_synthesis — Function
plan_synthesis(grid, ::Type{T}, ms; transform=AutoSpectralBackend(), execution=AutoBackend(),
               batch=(), iflag=1, kwargs...)
plan_synthesis(transform, execution, grid, ::Type{T}, ms; batch=(), kwargs...)

Construct a reusable AbstractSynthesisPlan evaluating an ms-resolution series at the points of grid, a field with trailing batch shape batch: what synthesize computes, the adjoint of the forward transform under the grid's quadrature and its inverse only where that quadrature is exact. T is the field's element type, which fixes both the coefficient layout the plan consumes (the packed half for a real field, the full native cube for a complex one) and the output it writes.

Execute with synthesize!(out, plan, coeffs).

source
FlowFieldSpectra.Plans.field_size — Function
field_size(plan::AbstractSynthesisPlan) -> Dims

Shape of the field synthesize! writes: the grid's own spatial shape followed by the batch axes, so a round trip returns the shape the forward transform consumed.

source
FlowFieldSpectra.Plans.field_type — Function
field_type(plan::AbstractSynthesisPlan) -> Type

Element type of that field — real when the plan was built for a real field, complex otherwise.

source
fwd = plan_spectrum(grid, Float64, ms; transform = FFTSpectralBackend(), batch = (nz,))
inv = plan_synthesis(grid, Float64, ms; transform = FFTSpectralBackend(), batch = (nz,))
coeffs = allocate_coefficients(fwd)
field  = allocate_field(inv)
for t in times
    calculate_spectrum!(coeffs, fwd, snapshot(t))
    filter!(coeffs)
    synthesize!(field, inv, coeffs)
end

The packed layout

A real Cartesian field transforms to the rfft-packed half (b_1÷2+1, b_2…, batch…) of its coefficient box b, the complete Hermitian representation of its spectrum, over the wavenumber axes FlowTransformBindings.RFFTAxis (axis 1) and FlowTransformBindings.FFTAxis. The box is ms, except on an axis whose samples tell +m_d/2 from -m_d/2 apart (a stretched axis, a point set, an axis transformed below its own length), where an even m_d widens to the m_d + 1 modes -m_d/2 … m_d/2. With two such axes d, e ≥ 2 the modes at +m_d/2 with -m_e/2 lie outside the computed modes and their mirror, and hold zero. FlowTransformBindings.unpacked(coeffs, b) expands the half to the full FFT-order box, and the reductions and the synthesis sum over the whole of it.

Grids

The grid type defines the coordinate system, so construct the grid that matches your data. Grids come from FlowGeometries.jl: a Cartesian grid is a FG.Grids.StructuredGrid / FG.Grids.UnstructuredGrid over a FG.Geometry.CartesianGeometry, and a spherical grid the same over a FG.Geometry.SphericalGeometry. Structured vs. scattered is the grid architecture, and uniform vs. stretched is each direction's type, read by FG.Grids.spacing_trait (a bounded direction on a range and a periodic direction on a FG.Axes.PeriodicUniformAxis are uniform, a Vector stretched); FlowFieldSpectra defines no grid types of its own. Spherical sampling schemes (Fejer1Sampling, GaussLegendreSampling, DriscollHealySampling, …) live in FG.SphericalSampling; build a structured spherical grid with FG.Connectivity.structured_grid. FlowFieldSpectra reads every grid through FlowGeometries' own accessors (size, ndims, length, coordinates, isuniform, period, …). See the FlowGeometries documentation for construction.

Reductions

Every reduction, the cross-spectra and averages below included, takes execution. On ThreadedBackend it splits its rows (the degrees of a spherical spectrum) over tasks; on SerialBackend it runs on one thread, and the in-place forms allocate nothing. A process backend reduces on the calling process, where the coefficients are, and coefficients on a device are reduced on their device.

FlowFieldSpectra.Reductions.isotropic_spectrum — Function
isotropic_spectrum(ks_phys::Tuple, coeffs; num_bins=0, dims=(), cutoff=true,
                   convention=SpectralConvention(), execution=AutoBackend())

1D radially-integrated (isotropic) energy spectrum of coeffs (ms…, batch…), binning over the D = length(ks_phys) spectral dims and preserving all batch dims → (k_bins, E) with E of shape (num_bins, batch…). dims (absolute batch-dim index/indices > D) folds those axes into the energy (e.g. dims=D+1 sums a vector-component axis into a single kinetic-energy spectrum). A bin collects ½|C|² over its modes of the coefficient box, a packed half standing for both signs of k₁.

cutoff = true bins the modes with |k| ≤ k_max = min_d max|k_d|, the shells the mode box holds whole. cutoff = false bins every mode, the bins continuing at the same width to the corner of the mode box; under ShellSum the bins then hold ½ Σ |C|² over the whole coefficient box, ½⟨|f|²⟩ for a transform on a uniform grid at its own length. num_bins = 0 takes half the shortest axis's full mode count up to k_max.

convention.estimator takes the bin's sum (ShellSum(), the default) or its mode average times a whole shell's mode count (ModeAverage()); convention.scaling divides by the bin width (DensityScaling(), the default) or not (PowerScaling()). A radial bin covers every direction, so its sum already includes each mode's −k partner and convention.sided is fixed at OneSided() here; see Normalization.SpectralConvention.

execution splits the binning over threads on ThreadedBackend (with using OhMyThreads) and runs it on one on SerialBackend; AutoBackend resolves as the transforms resolve it, and a process backend to the calling process's own. Coefficients on a device are reduced on their device.

source
FlowFieldSpectra.Reductions.isotropic_spectrum! — Function
isotropic_spectrum!(E, k_bins, ks_phys, coeffs; num_bins=0, cutoff=true, convention=SpectralConvention(),
                    execution=AutoBackend())

In-place isotropic spectrum that preserves all batch dims (no folding): fills preallocated E (shape (nb, batch…)) and k_bins (length nb), allocating nothing on SerialBackend. With the cutoff nb bins span [0, k_max]; with cutoff = false, num_bins of them span [0, k_max] (0: the default count) and nb is the total that reaches the corner of the mode box, the length isotropic_spectrum returns. cutoff, convention and execution are read as in isotropic_spectrum.

source
FlowFieldSpectra.Reductions.transect_spectrum — Function
transect_spectrum(ks_phys::Tuple, coeffs, dims::Tuple; execution=AutoBackend())

Integrate the spectral energy density ½|C|² along the spectral dimensions dims (1-indexed, ⊆ 1:D), scaling by their wavenumber spacing. Returns (ks_reduced, E_reduced) where E_reduced has the kept spectral dims followed by the batch dims. execution is read as in isotropic_spectrum.

Σ E_reduced / ∏dk over the kept axes is the field's folded Parseval total over the coefficient box, whichever axes are kept: a kept full axis carries both signs of its wavenumber outright, and a kept halved axis reports |k₁| with the −k₁ energy folded in. So a kept full axis's entries at ±k are equal for a real field's spectrum and differ for a complex field's, where the sign carries the propagation direction.

source
FlowFieldSpectra.Reductions.spherical_energy_spectrum — Function
spherical_energy_spectrum(coeffs; lmax=size(coeffs,1)-1, execution=AutoBackend())

Degree energy spectrum E(ℓ, batch…) = ½ Σ_{m=-ℓ}^{ℓ} |C_ℓ^m|² of spherical-harmonic coefficients (Nθ, Nφ, batch…). Returns (0:lmax, E_l), E_l of shape (lmax+1, batch…) and real element type, from real or complex coefficients. execution is read as in isotropic_spectrum.

source
FlowFieldSpectra.Reductions.anisotropic_spectrum — Function
anisotropic_spectrum(ks_phys::Tuple, coeffs; num_k_bins=0, num_θ_bins=16, dims=(),
                     convention=SpectralConvention(), execution=AutoBackend())

Anisotropy-resolved 2D energy spectrum E(k, θ, batch…) for a 2D field: bin ½|C|² by wavenumber magnitude up to k_max and polar angle, preserving batch. The k = 0 mode has no angle and is spread evenly over the θ bins of the first k bin, so integrating over θ recovers the isotropic spectrum in every bin. Under ModeAverage() a bin's mean is scaled by the mode count of its whole annular sector, (dθ/2)(k₊² − k₋²)/(Δk₁Δk₂); DensityScaling() divides by dk·dθ. execution is read as in isotropic_spectrum.

source

Cross-spectra

FlowFieldSpectra.Reductions.cross_spectrum — Function
cross_spectrum(ks_phys::Tuple, coeffs_f, coeffs_g; num_bins=0, dims=(), convention=SpectralConvention(),
               execution=AutoBackend())

Radially-binned cross-spectrum S_fg(k, batch…), a bin collecting ½ f̂ conj(ĝ) over its modes up to k_max; coeffs_f, coeffs_g share shape (ms…, batch…). convention and execution are read as in isotropic_spectrum. Real part → co-spectrum, negative imag part → quad spectrum.

source

Averaging (variance reduction, coherence & phase)

FlowFieldSpectra.Averaging.welch_power_spectrum — Function
welch_power_spectrum(ks_phys::Tuple, coeffs; num_bins=0, cutoff=true, convention=SpectralConvention(),
                     execution=AutoBackend())

Variance-reduced (Welch / ensemble-averaged) isotropic power spectrum. The trailing batch dims of coeffs (ms…, realization…) index independent segments/realizations whose periodograms are averaged before radial binning. cutoff, convention and execution are read as in isotropic_spectrum. Returns (k_bins, E_k).

source
FlowFieldSpectra.Averaging.coherence_spectrum — Function
coherence_spectrum(ks_phys::Tuple, cf, cg; num_bins=0, execution=AutoBackend()) -> (k_bins, coherence², phase)

Magnitude-squared coherence $\gamma^2(k) = |S_{fg}|^2 / (S_{ff} S_{gg})$ and phase between two fields whose coefficients cf, cg share (ms…, realization…). Cross/auto spectra are averaged over the realization batch and over the modes in each radial bin before the ratio is formed; a bin's normalization cancels in the ratio, so the estimator of isotropic_spectrum does not enter. execution is read as in isotropic_spectrum.

source
FlowFieldSpectra.LombScargle.lomb_scargle — Function
lomb_scargle(t, y, freqs; center=true) -> Vector

Lomb–Scargle periodogram of an irregularly-sampled 1D series y at sample times/locations t, evaluated at the (strictly positive) frequencies freqs. This is the standard estimator for gappy / non-uniformly sampled records (moorings, drifters, satellite tracks, astronomical time series) where an FFT cannot be applied directly.

With center=true (default) the sample mean is removed first. The classic time-shift τ is chosen per frequency to make the cosine and sine bases orthogonal, giving a periodogram that is invariant to time translation:

\[P(f) = \tfrac12\left[ \frac{(\sum_j y_j\cos\omega(t_j-\tau))^2}{\sum_j\cos^2\omega(t_j-\tau)} + \frac{(\sum_j y_j\sin\omega(t_j-\tau))^2}{\sum_j\sin^2\omega(t_j-\tau)} \right], \quad \omega = 2\pi f .\]

This is the direct $O(N\,M)$ reference implementation (N samples, M frequencies); it needs no FFT. freqs must be positive (the f=0 term is undefined).

source

Derived quantities & post-processing

FlowFieldSpectra.Operators.spectral_divergence — Function
spectral_divergence(ks_phys::Tuple, coeffs) -> AbstractArray

Spectral divergence $\widehat{\nabla\cdot u} = i\sum_d k_d \hat u_d$ of a D-component vector field with coefficients (ms…, D, extra…). Returns (ms…, 1, extra…) where the coefficients live.

source
FlowFieldSpectra.Operators.spectral_vorticity — Function
spectral_vorticity(ks_phys::Tuple, coeffs) -> AbstractArray

Spectral vorticity $\hat\omega = i\,k \times \hat u$ of a vector field with coefficients (ms…, D, extra…): D = 2 → scalar out-of-plane vorticity (ms…, 1, extra…); D = 3 → 3-component vorticity (ms…, 3, extra…), where the coefficients live.

source
FlowFieldSpectra.Operators.compensate — Function
compensate(k_bins, E_k, p) -> AbstractArray

Compensated spectrum $k^p E(k)$ (e.g. p = 5/3 Kolmogorov plateau, p = 2 for Z(k)=k²E(k)). E_k may be (num_bins,) or (num_bins, batch…); k_bins broadcasts along the wavenumber axis.

source
FlowFieldSpectra.Operators.band_energy — Function
band_energy(k_bins, E_k, k1, k2) -> Real

Energy integrated over the wavenumber band $[k_1, k_2]$ via the trapezoidal rule over the bins whose centers fall in the band. E_k is a 1D spectrum (num_bins,).

source

Analysis on a scattered sphere

analysis on a NUFSHT transform chooses how coefficients are taken from scattered values: the quadrature projection under the grid's weights, or the least-squares fit of the band-limited series, bounded by maxiter and rtol. Every other transform takes Quadrature() and raises on LeastSquares(). A plan reports the outcome of its last call:

FlowFieldSpectra.Grids.Quadrature — Type
Quadrature <: AbstractAnalysis

The coefficients as the quadrature C_k = Σ_j w_j f_j conj(φ_k(x_j)) of the field f against each basis function φ_k under the grid's weights w: one adjoint transform. Every backend computes this, and it is the default.

source
FlowFieldSpectra.Grids.LeastSquares — Type
LeastSquares <: AbstractAnalysis

The coefficients minimizing Σ_j w_j |(A C − f)_j|² over the field's samples under the grid's weights w (_analysis_weights), A the synthesis, by LSMR: on samples of a field synthesized from coefficients of the transform's resolution, those coefficients. NUFSHTSpectralBackend computes this; the plan reports the fit's outcome through analysis_status.

source
FlowFieldSpectra.Plans.analysis_status — Function
analysis_status(plan) -> FlowTransformBindings.SolverResult

The outcome of the least-squares fit (analysis = LeastSquares()) of the plan's last calculate_spectrum!: the fitting library's report over the whole batch (NUFSHT's nusht_solve! returns it per call), converged for every field, the most LSMR iterations, and the largest relative residual ‖A†r‖/‖A†f‖. A fit that stops short still writes its coefficients and is reported here. A plan whose analysis is a quadrature or an exact transform fits nothing and has no method.

source

Masked spherical grids

inactive on a spherical transform says how a masked grid's inactive cells enter, the quadrature and the LeastSquares() fit alike, on every execution backend:

FlowFieldSpectra.Grids.ZeroFill — Type
ZeroFill <: AbstractInactiveCells

Inactive cells count as zero: the transform of the field extended by zero over the whole grid. The quadrature reads the grid's own weights, the inactive cells' contributing nothing, and the least-squares fit (LeastSquares) runs over every node, an inactive one reading zero.

source
FlowFieldSpectra.Grids.Exclude — Type
Exclude <: AbstractInactiveCells

Inactive cells are left out: the quadrature or the fit over the active cells as their own point set. The quadrature reads the active cells' weights rescaled to the whole grid's total (_inactive_scale), as a grid of the active cells alone weighs them, and the least-squares fit (LeastSquares) runs over the active nodes.

source

Preprocessing & normalization conventions

preprocess::Preprocess on calculate_spectrum detrends, tapers and zero-pads the field before transforming. On plan_spectrum it gives a PreprocessedPlan, which preprocesses each batch slice under that slice's valid points (a valid mask, or the finite values) on every calculate_spectrum!. preprocess_field applies the same spec explicitly, for multitaper (one plan, K tapered copies as a batch).

FlowFieldSpectra.PreprocessedPlan — Type
PreprocessedPlan

A spectral plan that preprocesses every batch slice of a field before its inner plan transforms it, built by plan_spectrum(…; preprocess). A slice's invalid points (valid false, or a non-finite value where no valid is given) weigh zero in its detrend fit, in its window's normalization and in the quadrature, which normalizes by the measure of the slice's valid points: a slice's coefficients are those of the transform over its valid points alone. The field itself is never written. The slices are preprocessed on the plan's host execution, one task per slice range on ThreadedBackend.

Holds the inner plan, the Preprocess spec, the execution, the grid's per-point quadrature weights and their total, the detrend basis past the constant (the centred trend coordinates for LinearDetrend, none for Demean, nothing for NoDetrend), the window at the points (nothing for NoWindow), the staging slices, each slice's normal-equation buffers, and the padding: the padded staging an all-uniform grid embeds its slices in, the factor 1/pad^D a point grid scales them by, or none.

source
FlowFieldSpectra.preprocess_field — Function
preprocess_field(grid, field, spec::Preprocess; sampling=nothing, weights=nothing)
    -> (grid′, field′, ms_scale)

field detrended, tapered and zero-padded per spec, with the grid and mode-count scale the padding implies; (grid, field, 1) for an identity spec. The caller's array is never mutated.

Both detrends are least-squares fits under the transform's weights: the cell measure on a Cartesian grid, the spherical quadrature sampling / weights on a sphere. Demean zeroes the k = 0 coefficient; LinearDetrend fits a + b·x in the point coordinates, which on a sphere are the unit vector's components, so it zeroes every degree l ≤ 1. spec.window multiplies each point by the window at its fractional position across each Cartesian direction (Preprocessing.point_window). spec.pad > 1 lengthens a Cartesian domain pad times with zeros: as samples on an all-uniform grid, and otherwise as a node grid over the same points with the field scaled by 1/pad^D. A window or padding on a sphere raises.

source
FlowFieldSpectra.Preprocessing.Preprocess — Type
Preprocess(; detrend=Demean(), window=NoWindow(), pad=1.0)

Preprocessing applied to a field before transforming.

  • detrend::AbstractDetrend: Demean() (default), NoDetrend(), or LinearDetrend().
  • window::AbstractWindow: NoWindow() (default), Hann(), Hamming(), Blackman(), Tukey(α).
  • pad::Float64: zero-padding factor (≥ 1); 1.0 means none.

A window is scaled to unit mean square under the grid's measure (point_window), so the windowed field keeps the variance of the original.

source
FlowFieldSpectra.Preprocessing.AbstractWindow — Type
AbstractWindow

Supertype for apodization windows applied before transforming. Concrete windows dispatch window_value, the window at a fractional position t ∈ [0, 1] across the domain's extent in one direction; a field is multiplied by the product over directions at each point's position (point_window). Reduces spectral leakage for non-periodic data.

source
FlowFieldSpectra.Preprocessing.dpss — Function
dpss([T = Float64,] N::Integer, NW::Real, K::Integer = max(1, floor(Int, 2NW) - 1)) -> Matrix{T}

Discrete prolate spheroidal sequences (Slepian tapers): the K length-N sequences with maximal spectral concentration in the half-bandwidth W = NW/N, returned as an N×K matrix whose column k is the order-(k-1) taper. The columns are orthogonal with unit mean square (V'V = N·I), the scaling axis_taper gives a window, so a tapered copy's periodogram has the untapered level. NW is the time–bandwidth product (typical 2.5–4); K ≈ 2·NW − 1 tapers are usefully concentrated.

The tapers are the eigenvectors of a symmetric tridiagonal matrix (Percival & Walden). A multitaper estimate transforms the K tapered copies as a batch and averages their periodograms with welch_power_spectrum.

source
FlowFieldSpectra.Normalization.ShellSum — Type

ShellSum() — the sum of ½|C|² over the bin's modes, so the bins add up to the energy they hold. A shell the mode box holds only in part (radius beyond k_max = min_d max|k_d|) sums fewer modes than a whole one.

source
FlowFieldSpectra.Normalization.ModeAverage — Type

ModeAverage() — the mean of ½|C|² over the bin's modes times the number of modes a whole shell of that width holds, V_D (k₊ᴰ − k₋ᴰ) / ∏_d Δk_d with V_D the unit-ball volume. For an isotropic field a shell the mode box holds in part then estimates the whole shell, and the scatter of the lattice's mode count per shell at low k averages out; the bins add up to the energy only approximately. A bin holding no mode is NaN.

source

Transform backends (which spectral math)

The two backend axes are orthogonal and compose: pass one transform= and one execution=. See Backends and Extensions for the selection matrix and profiles.

The transform= keyword takes a marker tag from SpectralBackends.jl: AutoSpectralBackend (the default), DirectSumSpectralBackend, FFTSpectralBackend, NUFFTSpectralBackend, FSHTSpectralBackend, NUFSHTSpectralBackend (all <: SpectralBackends.AbstractSpectralBackend). Transform options such as eps, tol, iflag, analysis and batch_chunk are calculate_spectrum and plan_spectrum keyword arguments.

A NUFFT names its library with a tag from FlowTransformBindings.jl: FlowTransformBindings.NonuniformFFTsBackend() (using NonuniformFFTs) or FlowTransformBindings.FINUFFTBackend() (using FINUFFT), both <: SpectralBackends.AbstractNUFFTSpectralBackend. SpectralBackends.NUFFTSpectralBackend names no library and raises.

Execution backends (where/how it runs)

The execution= keyword takes a tag from ComputationalBackends.jl: SerialBackend, ThreadedBackend, GPUBackend, DistributedBackend, MPIBackend, and AutoBackend (the default: ThreadedBackend once OhMyThreads is loaded and Julia has more than one thread, SerialBackend otherwise), all <: ComputationalBackends.AbstractExecutionBackend.

Plotting & analysis

These require CairoMakie to be loaded.

FlowFieldSpectra.plot_spectrum — Function
plot_spectrum(k_ranges::Tuple, coeffs; title="Power Spectrum", u_idx=1, kwargs...)

Plot the coefficient magnitude of batch slice u_idx, as a line in 1D and a heatmap in 2D. Requires using CairoMakie.

source
FlowFieldSpectra.compare_spectra — Function
compare_spectra(results; u_idx=1, title="Spectral Analysis Comparison", kwargs...)

Plot several spectra side by side, results an iterable of label => (coeffs, k_ranges). Requires using CairoMakie.

source