API Reference
Unified Entry Point
FlowInvariantTransfer.calculate_energy_transfer — Function
calculate_energy_transfer(method, velocity_data, coords_or_ks; kwargs...)Run the diagnostic method names and return its result container.
Arguments
method::AbstractEnergyTransferMethod: Which method to use:SpectralFluxMethod(binning)— spectral flux Π(K) →SpectralFluxResultShellToShellTransferMethod(binning)— shell-to-shell T(n,m) →ShellToShellResultModeToModeTransferMethod(; invariant)— mode-to-mode S(k|p) →ModeToModeTriadResultCoarseGrainingFluxMethod(filter, ℓ)— coarse-graining flux Π_ℓ(x) →CoarseGrainingFluxResultTriadicOrthogonalDecompositionMethod(; nfft, noverlap, nmode)— called ascalculate_energy_transfer(method, X; kwargs...)on snapshotsX→TriadicOrthogonalDecompositionResult
velocity_data: For spectral methods, a complex array of size(ms..., D)containing Fourier coefficients; for coarse-graining, a tuple of D real physical-space arrays.coords_or_ks: For spectral methods, a tuple of 1D wavenumber vectors; for coarse-graining, a tuple of 1D coordinate vectors.
Physical-space Cartesian data uses the 4-positional form calculate_energy_transfer(method, velocity_fields, coords, ms; transform, …), which routes on transform: a NUFFT library (FlowTransformBindings.NonuniformFFTsBackend() / FlowTransformBindings.FINUFFTBackend(), with Ls) reconstructs from scattered samples, while any other backend transforms uniform-grid data through FlowFieldSpectra (using FlowFieldSpectra; coords are the per-axis grid vectors). Coarse-graining has the same 4-positional scattered route. Spherical data uses calculate_energy_transfer(SphericalTransferMethod(), ζ, (θ, φ); lmax, …) (scattered, NUFSHT) or a regular colatitude–longitude grid (FastSphericalHarmonics).
Examples
using FlowInvariantTransfer, FlowFieldSpectra, FFTW
const FIT = FlowInvariantTransfer
# Spectral flux on a 32×32 periodic domain
N = 32; L = 2π
x = range(0.0, L; length=N+1)[1:N]
u = [cos(xi) * sin(yj) for xi in x, yj in x]
v = [-sin(xi) * cos(yj) + 0.3 * sin(2yj) for xi in x, yj in x]
û, ks = to_spectral((u, v), (x, x)) # real fields: the half layout
result = calculate_energy_transfer(FIT.Types.SpectralFluxMethod(FIT.Types.LinearBinning(2π/L)), û, ks)Physical → Spectral
The diagnostics take Fourier coefficients, so gridded physical data is transformed here once. A real field takes the half (rfft) layout: the non-redundant k₁ ≥ 0 coefficients, with ks[1] an rfftfreq axis. Complex input takes the full spectrum. Build the workspace once to reuse the plans and buffers across snapshots.
The domain is given either as per-axis ranges describing a uniform periodic box, or as a FlowGeometries grid. Passing a grid (using FlowFieldSpectra) selects the transform from the grid itself through FlowFieldSpectra.plan_spectrum — the tensor-product FFT on a uniform Cartesian grid, the FFT/NUFFT composite where some directions are stretched — and reads the period the grid declares.
FlowInvariantTransfer.to_spectral — Function
to_spectral(velocity_fields::Tuple, scatter_coords::Tuple, ms::Tuple; transform, Ls, tol = nothing,
weights = nothing, execution = AutoBackend()) -> (velocity_hat, ks)Scattered-Cartesian physical-space entry: reconstruct the Fourier coefficients velocity_hat on a uniform ms = (m₁,…,m_D) grid from velocity components sampled at scattered (non-uniform) points, through a NUFFT type-1 transform, and return them with the matching uniform wavenumber grid ks, the input of every Cartesian flux diagnostic. Real fields use the packed half of FlowTransformBindings' odd coefficient box: an even requested count is widened by one on that axis. Complex fields use the full ms box.
scatter_coords = (x, y[, z]) hold one coordinate per sample on each axis (each vector of length N, the number of samples); ms is the target uniform mode count per dimension. transform (required) names the NUFFT library: FlowTransformBindings.NonuniformFFTsBackend() (using NonuniformFFTs) or FlowTransformBindings.FINUFFTBackend() (using FINUFFT). For uniform-grid data use the 2-argument form with SpectralBackends.FFTSpectralBackend().
The coefficients are the quadrature û(k) = (1/∏L) Σⱼ wⱼ uⱼ e^{-ik·xⱼ}, with weights wⱼ the volume sample j stands for (Σw = ∏L). It is exact for a field band-limited to ms when the weights integrate every e^{iq·x} with |q_d| < m_d exactly. Without weights every sample stands for ∏L/N and û = type1(u)/N: exact for samples on the uniform L-grid (û = fft(u)/Nᵈ), and otherwise an estimate that weights each sample equally, so a region sampled densely counts for more than its volume.
tol sets the NUFFT accuracy (nothing: FlowTransformBindings.default_tolerance of the coordinates' float type). Ls (required) is the periodic domain size per dimension and fixes the wavenumbers k = 2πn/L: the samples live in [xₘᵢₙ, xₘᵢₙ+Lₐ) and under-span the period, so L cannot be inferred from them. execution = GPUBackend(dev) (dev a KernelAbstractions backend) builds the plan and buffers on the device, so the scattered → velocity_hat step runs there.
to_spectral(velocity_fields::Tuple, coords_vecs::Tuple; transform=SpectralBackends.AutoSpectralBackend()) -> (velocity_hat, ks)Forward-transform physical-space velocity components sampled on a uniform, periodic, tensor-product Cartesian grid into the Fourier-coefficient input (velocity_hat, ks) consumed by every Cartesian flux diagnostic (calculate_spectral_flux, calculate_shell_to_shell_transfer, calculate_mode_to_mode_transfer, calculate_band_to_band_transfer, calculate_partial_fluxes, calculate_compressible_flux). This is the physical-space entry point for gridded data: the diagnostics operate on coefficients, so a real field is transformed here once with the package's û = fft(u)/Nᵈ normalization (so E(k) = ½|û|²) and the FFTW fftfreq wavenumber convention — you do not build û/ks by hand.
coords_vecs are one-dimensional ranges (x, y[, z]), each holding nₐ periodic samples x₁, x₁ + Δ, …, x₁ + (nₐ−1)Δ of the period L = nₐΔ. Other coordinate arrays need a FlowGeometries grid with an explicit period. Scattered (non-uniform) Cartesian data takes the 3-argument form with a NUFFT library (transform = FlowTransformBindings.NonuniformFFTsBackend() or FlowTransformBindings.FINUFFTBackend()), and spherical data calculate_spherical_transfer.
Keyword Arguments
transform::SpectralBackends.AbstractSpectralBackend = SpectralBackends.AutoSpectralBackend(): the analysis transform.SpectralBackends.FFTSpectralBackend()needsusing FFTW(cuFFT is used automatically for device-array inputs);SpectralBackends.DirectSumSpectralBackend()is the dependency-freeO(N²ᴰ)reference (tiny grids only).
Returns
(velocity_hat, ks) — complex coefficients shaped (ms..., D) in the input array's backend and their wavenumber axes. Real input takes the packed half; complex input takes the full spectrum.
Example
using FlowInvariantTransfer, FlowFieldSpectra, FFTW
û, ks = to_spectral((u, v), (x, y))
result = calculate_spectral_flux(û, ks)Pass a scalar (density / pressure / passive scalar) as a 1-tuple: ρ̂, _ = to_spectral((ρ,), coords).
FlowInvariantTransfer.ToSpectralWorkspace — Type
ToSpectralWorkspace{TF, RA, CA, KS}Reusable transform + buffers for the uniform-grid to_spectral!: the analysis plans, the real (ns…, D) staging array the components are gathered into, and the (ms…, D) coefficient output the result aliases. Build once for a grid and reuse across snapshots — the plans and both buffers are then built once for the whole series.
FlowInvariantTransfer.from_spectral — Function
from_spectral(velocity_hat, ks; transform=AutoSpectralBackend()) -> velocity_fieldsSynthesise physical-space components from Fourier coefficients on a uniform periodic Cartesian grid — the inverse of to_spectral, and its normalization: u = Σ û e^{ik·x}. Accepts either spectral layout, reading which from ks, and returns real fields.
The components come back as a vector of views into one backing array. Build a ToSpectralWorkspace and call from_spectral! for the stacked array and plan reuse across snapshots.
FlowInvariantTransfer.from_spectral! — Function
from_spectral!(ws::ToSpectralWorkspace, velocity_hat) -> velocity_physIn-place synthesis u = Σ û e^{ik·x}, the inverse of to_spectral!, reusing ws. Returns the component-last (ns…, D) real array ws.field_phys, overwritten by a later call — the same stacked shape to_spectral! returns its coefficients in, and allocation-free on repeat.
Spectral Flux
FlowInvariantTransfer.SpectralFlux.calculate_spectral_flux — Function
calculate_spectral_flux(velocity_hat, ks; binning, dealiasing=OrszagTwoThirds(), invariant=KineticEnergy(),
decomposition=NoDecomposition(), transform=AutoSpectralBackend(), execution=AutoBackend(),
advecting_hat=velocity_hat, geometry=IsotropicShells()) -> SpectralFluxResultCompute the spectral energy transfer spectrum T(k) and the cumulative energy flux Π(K) from Fourier-space velocity data.
Arguments
velocity_hat: Complex array of size(ms..., D)— Fourier coefficients of the D velocity components on the spectral layoutksdescribes (ms = ns, or the half layout of a real field).ks: Tuple of 1D physical-wavenumber vectors (matching FFTW fftfreq convention).
Keyword Arguments
binning::AbstractShellBinning: Shell binning strategy; defaultLinearBinning(Δk)withΔkthe smallest nonzero|k|on any axis.dealiasing::AbstractDealiasing=OrszagTwoThirds(): Apply 2/3 dealiasing rule when computing (u·∇)u.invariant::AbstractInvariant=KineticEnergy(): the quadratic invariant whose transfer is binned.decomposition::AbstractFieldDecomposition=NoDecomposition(): with a splitting decomposition the result is aNamedTupleofSpectralFluxResults, one per component, each against the fullN̂.transform::SpectralBackends.AbstractSpectralBackend: transform backend —SpectralBackends.AutoSpectralBackend()(default;FFTSpectralBackend()when FFTW is loaded),SpectralBackends.FFTSpectralBackend(), orSpectralBackends.DirectSumSpectralBackend()(no dependencies).execution::ComputationalBackends.AbstractExecutionBackend=ComputationalBackends.AutoBackend(): how the transfer-density write and the mode→shell reduction are parallelised:ComputationalBackends.SerialBackend()— host scalar reduction.ComputationalBackends.ThreadedBackend()(requiresusing OhMyThreads) — the mode→shell scatter is split into chunks with per-chunk partial shell sums (race-free), anO(Nᴰ)parallel pass.ComputationalBackends.DistributedBackend(inner)— a field held on the calling process is computed there underinner;calculate_spectral_flux_batchdivides snapshots among the workers. A grid too large for one node takespencil_spectral_flux(PencilFFTs) on a field split over MPI ranks.ComputationalBackends.GPUBackend(dev)(requiresusing KernelAbstractions) — the transfer density is written by a device kernel and reduced per shell on-device, so a device-resident field stays on the GPU; host fields are copied todevonce per call.
advecting_hat=velocity_hat: the advecting velocity of(u·∇)f.geometry::AbstractShellGeometry=IsotropicShells(): the wavenumber coordinate the shells partition.form::AbstractNonlinearForm=Advective():Rotational()evaluatesω × uwith fewer transforms, the same fluxes for a divergence-free velocity advecting itself under the 2/3 rule; it takes kinetic energy, enstrophy or helicity and noadvecting_hat.
Returns
SpectralFluxResult with fields:
k_shells: Representative wavenumber per shell;shell_edges: the shell boundaries.transfer_spectrum: T(kn) = −dEn/dt from the nonlinear term, the energy shell n gives to the other shells per unit time — a sum over the shell's modes.flux: Π[n] — the energy shells 1…n pass to larger wavenumbers per unit time, the flux throughshell_edges[n+1].
Physics
T(kn) = Σ{|k| ∈ shelln} Re{ û*(k) · N̂(k) } Π[n] = Σ{m ≤ n} T(k_m)
Positive Π: forward (downscale) cascade; negative Π: inverse (upscale) cascade.
References
- Verma et al. (2002) [arXiv:nlin/0204027]
- Alexakis, Mininni & Pouquet (2005)
FlowInvariantTransfer.SpectralFlux.calculate_spectral_flux! — Function
calculate_spectral_flux!(result, ws, velocity_hat, ks, shell_idx;
dealiasing, invariant, transform, execution, advecting_hat, form)In-place version of calculate_spectral_flux. Writes into result using preallocated buffers from ws and a precomputed shell_idx array (from assign_shells). Zero heap allocations in the serial hot path. execution selects the mode→shell reduction backend and form the nonlinear term (see calculate_spectral_flux).
FlowInvariantTransfer.SpectralFlux.calculate_spectral_flux_batch — Function
calculate_spectral_flux_batch(velocity_hats, ks; binning, dealiasing, invariant, transform, geometry, execution,
form) -> Vector{SpectralFluxResult}Spectral flux for a batch of snapshots that share one grid (velocity_hats an iterable of (ms..., D) coefficient arrays). The shell structure is built once, and each worker reuses one SpectralFluxWorkspace (FFT plans + scratch) across its snapshots. execution = ThreadedBackend() (requires using OhMyThreads) splits the snapshots across threads, each running single-threaded transforms. Results are returned in input order and are bit-identical to calling calculate_spectral_flux per snapshot.
FlowInvariantTransfer.SpectralFlux.calculate_scalar_flux — Function
calculate_scalar_flux(velocity_hat, scalar_hat, ks; binning, dealiasing=OrszagTwoThirds(), transform,
execution=AutoBackend(), geometry=IsotropicShells()) -> SpectralFluxResultCompute the passive-scalar variance transfer spectrum T_θ(k) and flux Π_θ(K), for a scalar θ advected by the velocity u (∂_tθ + (u·∇)θ = κ∇²θ):
T_θ(k_n) = Σ_{|k|∈shell_n} Re{ θ̂*(k) N̂_θ(k) }, N̂_θ = FFT[(u·∇)θ], Π_θ(K) = Σ_{k≤K} T_θ(k).Scalar variance is conserved for incompressible u (Σ_k T_θ ≈ 0) and cascades forward in any dimension (Obukhov–Corrsin). Thin wrapper over calculate_spectral_flux with invariant = PassiveScalar() and advecting_hat = velocity_hat.
Arguments
velocity_hat: complex(ns..., D)velocity Fourier coefficients (the advecting field).scalar_hat: complex scalar field, either(ns...)or(ns..., 1).ks: tuple ofnd1D wavenumber vectors.
FlowInvariantTransfer.SpectralFlux.calculate_scalar_flux! — Function
calculate_scalar_flux!(result, ws, velocity_hat, scalar_hat, ks, shell_idx; kwargs...)In-place passive-scalar variance flux — thin wrapper over calculate_spectral_flux! (invariant = PassiveScalar(), scalar advected by velocity_hat), writing into the caller-provided result/ws (0 alloc beyond them; ws sized for the scalar field).
Shell-to-Shell Transfer
FlowInvariantTransfer.ShellToShellTransfer.calculate_shell_to_shell_transfer — Function
calculate_shell_to_shell_transfer(velocity_hat, ks;
binning, dealiasing=OrszagTwoThirds(), invariant=KineticEnergy(),
transform=SpectralBackends.AutoSpectralBackend(), execution=ComputationalBackends.SerialBackend(),
advecting_hat=velocity_hat, geometry=IsotropicShells())
-> ShellToShellResultCompute the directed shell-to-shell kinetic energy transfer matrix T(n,m).
Arguments
velocity_hat: Complex array of size(ms..., D)— Fourier coefficients of the D velocity components on a periodic uniform grid.ks: Tuple ofnd1D physical-wavenumber vectors.
Keyword Arguments
binning::AbstractShellBinning: Shell binning; defaultLinearBinning(Δk)withΔkthe smallest nonzero|k|on any axis.dealiasing::AbstractDealiasing=OrszagTwoThirds(): Apply 2/3 rule dealiasing.transform::SpectralBackends.AbstractSpectralBackend:SpectralBackends.AutoSpectralBackend()(default;FFTSpectralBackend()when FFTW is loaded),SpectralBackends.FFTSpectralBackend(), orSpectralBackends.DirectSumSpectralBackend().execution::ComputationalBackends.AbstractExecutionBackend: outer (mediator-loop) parallelism —ComputationalBackends.AutoBackend()(default),ComputationalBackends.ThreadedBackend()(OhMyThreads),ComputationalBackends.DistributedBackend(), orComputationalBackends.GPUBackend(dev), which copies host fields todevonce per call.invariant,advecting_hat,geometry: as forcalculate_spectral_flux.
Returns
ShellToShellResult with:
transfer_matrix[n,m]: the rate at which shell n gives energy to shell m.net_transfer[n]= Σm T(n,m) = −dEn/dt, the spectral transfer of shell n.
Algorithm (Alexakis–Mininni–Pouquet 2005 formulation)
For each pair of shells n and m: T(n,m) = Σ{k∈Sn} Re{ û*(k) · N̂m(k) } where N̂m(k) = FFT[(u · ∇)um], um = IFFT(û · χm): the full velocity advects the shell-m field. For a divergence-free u, ∫un·(u·∇)um = −∫um·(u·∇)u_n, so T(n,m) + T(m,n) = 0 exactly (antisymmetry).
Cost
One advection per mediator shell: O(Nshells · Nᴰ log N) with FFTW, O(Nshells · N²ᴰ) by direct sums.
References
- Verma et al. (2002), arXiv:nlin/0204027
- Alexakis, Mininni & Pouquet (2005)
FlowInvariantTransfer.ShellToShellTransfer.calculate_shell_to_shell_transfer! — Function
calculate_shell_to_shell_transfer!(result, ws, velocity_hat, ks; kwargs...)In-place calculate_shell_to_shell_transfer, writing result.transfer_matrix and result.net_transfer with the buffers of ws; zero heap allocations in the hot path.
FlowInvariantTransfer.ShellToShellTransfer.calculate_shell_to_shell_transfer_batch — Function
calculate_shell_to_shell_transfer_batch(velocity_hats, ks; binning, dealiasing,
invariant, transform, geometry, execution) -> Vector{ShellToShellResult}Shell-to-shell transfer for a batch of snapshots that share one grid (velocity_hats an iterable of (ms..., D) coefficient arrays). The shell structure is built once and each worker reuses one ShellToShellWorkspace across its snapshots; execution = ThreadedBackend() (requires using OhMyThreads) threads over snapshots, each with a serial inner transform. Results are in input order, bit-identical to calling calculate_shell_to_shell_transfer per snapshot (each snapshot self-advects).
FlowInvariantTransfer.ShellToShellTransfer.calculate_scalar_shell_to_shell_transfer — Function
calculate_scalar_shell_to_shell_transfer(velocity_hat, scalar_hat, ks; kwargs...) -> ShellToShellResultShell-to-shell transfer of passive-scalar variance T_θ(n,m): the rate at which scalar-shell n gives variance to scalar-shell m, mediated by the velocity:
T_θ(n,m) = Σ_{k∈S_n} Re{ θ̂*(k) · 𝒩̂_m(k) }, 𝒩̂_m = FFT[(u·∇)θ_m], θ_m = θ̂·χ_m.The scalar field is band-filtered and carried; the velocity advects it. Thin wrapper over calculate_shell_to_shell_transfer with invariant = PassiveScalar() and advecting_hat = velocity_hat. scalar_hat may be (ns...) or (ns..., 1). As with energy, T_θ(n,m) is antisymmetric for incompressible u and reduces to T_θ(k) over mediators.
FlowInvariantTransfer.ShellToShellTransfer.calculate_scalar_shell_to_shell_transfer! — Function
calculate_scalar_shell_to_shell_transfer!(result, ws, velocity_hat, scalar_hat, ks; kwargs...)In-place passive-scalar shell-to-shell variance transfer — thin wrapper over calculate_shell_to_shell_transfer! (invariant = PassiveScalar()), writing into the caller-provided result/ws (0 alloc beyond them; ws sized for the scalar field).
Mode-to-Mode Triad Transfer
FlowInvariantTransfer.ModeToModeTransfer.calculate_mode_to_mode_transfer — Function
calculate_mode_to_mode_transfer(velocity_hat, ks; invariant=KineticEnergy(), dealiasing=OrszagTwoThirds(),
transform=AutoSpectralBackend(), execution=AutoBackend(),
advecting_hat=velocity_hat)
-> ModeToModeTriadResultMode-resolved triad transfer S(k|p) between the stored coefficients ("slots") of the spectral layout — the rate at which slot k gives the chosen quadratic invariant to the slot field u_p(x) = w(p)·Re{û(p) e^{ip·x}} (mediated by q = k−p), the part of −dE(k)/dt that advection of u_p accounts for:
S(k|p) = Re{ û*(k) · [(u·∇)u_p]^(k) } (generalised per invariant via `transfer_density!`).w(p) is the number of full-spectrum modes slot p stands for (1 on a full layout; on a half layout 2 on the interior of the halved axis, where the slot also stands for its mirror −p), returned as result.weights; the slot fields sum to u. It is the finest object in the reduction hierarchy S(k|p) → T(K,Q) (shell-to-shell) → T(k), Π(K) (spectral flux):
- reduces:
Σ_p S(k|p) = T(k), the spectral transfer (calculate_spectral_flux); - antisymmetric (divergence-free, dealiased):
w(k)S(k|p) = −w(p)S(p|k), sincew(k)S(k|p) = ⟨u_k·(u·∇)u_p⟩and∫(u·∇)(u_k·u_p) = 0—S(k|p) = −S(p|k)on a full layout; - conserves:
Σ_k Σ_p w(k)S(k|p) = 0.
Cost & memory
One nonlinear-term evaluation per slot p: O(N_scales) evaluations, O(N_scales · Nᴰ log N) time with SpectralBackends.FFTSpectralBackend, and an O(N_scales²) result tensor, where N_scales = prod(ms) is the number of stored slots. The aggregates come cheaper from calculate_spectral_flux (T(k), Π) or calculate_shell_to_shell_transfer (T(n,m)).
Keyword arguments
invariant::AbstractInvariant: which quadratic invariant (defaultKineticEnergy()).dealiasing::AbstractDealiasing=OrszagTwoThirds(): dealiasing of the nonlinear term; underPaddedThreeHalves()each slot's term is formed on the padded grid.transform::SpectralBackends.AbstractSpectralBackend:AutoSpectralBackend()(default, the FFT when FFTW is loaded).execution::ComputationalBackends.AbstractExecutionBackend: parallelism over the slotsp(AutoBackend()default; threaded, distributed and GPU through their extensions). UnderGPUBackend(dev)host fields are copied todevonce per call, and the result arrays are ondev.advecting_hat=velocity_hat: the advecting velocity of(u·∇)u_p.
Returns
ModeToModeTriadResult with weights (w, shape ms), net_transfer (T(k), shape ms) and transfer (the resolved S(k|p), shape (ms..., ms...)).
FlowInvariantTransfer.ModeToModeTransfer.calculate_mode_to_mode_transfer! — Function
calculate_mode_to_mode_transfer!(result, ws, û_p, velocity_hat, ks; kwargs...) -> resultIn-place mode-to-mode transfer: writes S(k|p) and the net into the caller-provided result::ModeToModeTriadResult (its weights from mode_weights), reusing the ws::NonlinearTermWorkspace (built for the same dealiasing) and the slot scratch û_p (same shape as velocity_hat). Allocation-free beyond those buffers.
FlowInvariantTransfer.ModeToModeTransfer.calculate_scalar_mode_to_mode_transfer — Function
calculate_scalar_mode_to_mode_transfer(velocity_hat, scalar_hat, ks; kwargs...) -> ModeToModeTriadResultFully mode-resolved passive-scalar variance transfer S_θ(k|p) — the rate at which scalar mode k gives variance to scalar mode p (mediated by the velocity, q = k−p). Thin wrapper over calculate_mode_to_mode_transfer with invariant = PassiveScalar() and advecting_hat = velocity_hat; the scalar may be (ns...) or (ns..., 1).
FlowInvariantTransfer.ModeToModeTransfer.calculate_scalar_mode_to_mode_transfer! — Function
calculate_scalar_mode_to_mode_transfer!(result, ws, û_p, velocity_hat, scalar_hat, ks; kwargs...)In-place passive-scalar mode-to-mode variance transfer — thin wrapper over calculate_mode_to_mode_transfer! (invariant = PassiveScalar()), writing into the caller-provided result/ws/û_p (0 alloc beyond those). ws/û_p are sized for the scalar field.
FlowInvariantTransfer.ModeToModeTransfer.mode_weights — Function
mode_weights(proto, FT, ks) -> AbstractArray{FT}The fold weight w(k) of every stored coefficient of the layout ks (FlowTransformBindings.mode_fold), shape spectral_size(ks), in proto's array type: the weights of a ModeToModeTriadResult.
Smooth Band-to-Band Transfer
FlowInvariantTransfer.BandTransfer.calculate_band_to_band_transfer — Function
calculate_band_to_band_transfer(velocity_hat, ks; bands::SmoothBands, dealiasing=OrszagTwoThirds(),
invariant=KineticEnergy(), transform=SpectralBackends.AutoSpectralBackend(), execution=AutoBackend(),
advecting_hat=velocity_hat, geometry=IsotropicShells())
-> (centers, transfer_matrix, net_transfer)Smooth band-to-band transfer T(n,m) of a quadratic invariant between the graded spectral bands (Eyink & Aluie 2009) — the smooth-filter analogue of calculate_shell_to_shell_transfer. For incompressible flow T is antisymmetric (T(n,m) = −T(m,n)), conserves (Σ T = 0), and Σ_m T(n,m) is the band-summed transfer spectrum. Accepts an advecting_hat (primary field can be a passive scalar advected by the velocity) and an anisotropic geometry. Under execution = GPUBackend(dev) host fields are copied to dev once per call. See calculate_band_to_band_transfer! for the in-place, workspace-reusing variant.
FlowInvariantTransfer.BandTransfer.calculate_band_to_band_transfer! — Function
calculate_band_to_band_transfer!(T, net, bws::BandTransferWorkspace, velocity_hat, ks; kwargs...)In-place smooth band-to-band transfer: writes the nb×nb matrix T and the nb-vector net, reusing bws (0 alloc beyond those). Returns the same (centers, transfer_matrix, net_transfer) named tuple as the allocating version.
FlowInvariantTransfer.BandTransfer.calculate_band_to_band_transfer_batch — Function
calculate_band_to_band_transfer_batch(velocity_hats, ks; bands, dealiasing, invariant, transform,
geometry, execution) -> VectorBand-to-band transfer for a batch of snapshots sharing one grid (velocity_hats an iterable of (ms..., D) coefficient arrays). The band weights are built once and each worker reuses one BandTransferWorkspace across its snapshots; execution = ThreadedBackend() (requires using OhMyThreads) threads over snapshots, each with a serial inner transform. Results (the same NamedTuple as the single-snapshot form) are in input order, bit-identical to calling calculate_band_to_band_transfer per snapshot.
Partial Fluxes (decomposition-resolved)
FlowInvariantTransfer.SpectralFlux.calculate_partial_fluxes — Function
calculate_partial_fluxes(velocity_hat, ks; decomposition=HelicalDecomposition(), binning,
dealiasing=OrszagTwoThirds(), transform=AutoSpectralBackend(), execution=AutoBackend(),
geometry=IsotropicShells())
-> (channels::Dict{NTuple{3,Symbol},SpectralFluxResult}, total::SpectralFluxResult, k_shells)Decompose the kinetic-energy flux into per-component partial fluxes Π^{s_k s_p s_q}(K), where each of the three fields in a triad interaction is one component of a velocity decomposition u = Σ_s u_s; channels is keyed by the component-name triple (s_k, s_p, s_q) and total is their sum. The channel term depends on the decomposition:
HelicalDecomposition(3-D) — the rotational form of Alexakis (2017, Eq. 17),Π^{s₁s₂s₃}(K) = −⟨u^{s₁}_{K<}·(u^{s₂} × ω^{s₃})⟩:T^{s_k s_p s_q}(k) = Re{ û_{s_k}*(k) · [ω_{s_q} × u_{s_p}]^(k) }, ω_s = ∇ × u_s.s_kis the component whose energy the term changes,s_pthe velocity of the cross product ands_qthe field whose vorticity it carries. The helical components are solenoidal, so the channels sum to the flux of the solenoidal part ofu.every other decomposition — the advective form
T^{s_k s_p s_q}(k) = Re{ û_{s_k}*(k) · [(u_{s_p}·∇) u_{s_q}](k) },whose channels sum to the full flux. For
HelmholtzDecompositionthe off-diagonal channels are the rotational↔divergent cross-flux, zero for incompressible flow.
Π = Σ_{k≤K} T in each channel. The decomposition and the channel terms run on every transform, execution and dealiasing the nonlinear term does; under execution = GPUBackend(dev) a host field is copied to dev once per call.
FlowInvariantTransfer.SpectralFlux.calculate_partial_fluxes! — Function
calculate_partial_fluxes!(ws::SpectralFluxWorkspace, velocity_hat, ks; kwargs...)The partial fluxes of calculate_partial_fluxes, reusing the caller's ws for every decomposition-channel pair and its fixed shell tables. Build ws with the desired binning and geometry; the channel SpectralFluxResults and their total are allocated per call.
FlowInvariantTransfer.SpectralFlux.calculate_partial_fluxes_batch — Function
calculate_partial_fluxes_batch(velocity_hats, ks; execution, kwargs...) -> VectorDecomposition-channel fluxes (calculate_partial_fluxes) for a batch of snapshots sharing one grid. One nonlinear-term workspace is reused across each worker's snapshots. execution = ThreadedBackend() (requires using OhMyThreads) threads over snapshots with a serial inner transform. Results are in input order.
FlowInvariantTransfer.SpectralFlux.calculate_helical_partial_fluxes — Function
calculate_helical_partial_fluxes(velocity_hat, ks; kwargs...)The eight helical partial energy fluxes Π^{s_k s_p s_q}(K), s ∈ {positive, negative}, in the rotational form of Alexakis (2017, Eq. 17) — calculate_partial_fluxes with decomposition = HelicalDecomposition() (3D only). Keys are (s_k, s_p, s_q) with s the symbols :positive/:negative: s_k is the component whose energy the term changes, s_p the velocity and s_q the vorticity of u × ω.
FlowInvariantTransfer.SpectralFlux.calculate_helical_partial_fluxes! — Function
calculate_helical_partial_fluxes!(ws::SpectralFluxWorkspace, velocity_hat, ks; kwargs...)In-place helical partial fluxes — calculate_partial_fluxes! with decomposition = HelicalDecomposition(), reusing the caller's ws.
Compressible Energy Transfer
FlowInvariantTransfer.Compressible.calculate_compressible_flux — Function
calculate_compressible_flux(velocity_hat, density_hat, ks; transform=SpectralBackends.AutoSpectralBackend(),
binning, geometry=IsotropicShells(), execution=AutoBackend(), pressure_hat=nothing,
decomposition=HelmholtzDecomposition(),
dealiasing=OrszagTwoThirds()) -> CompressibleFluxResultCompressible kinetic-energy spectral transfer T_u(k) and cumulative flux Π(K) (Singh–Tiwari– Sharma–Verma 2025): momentum v = ρu, E_u(k) = ½Re[v·u*]; the nonlinear transfer conserves total KE (Σ_k T_u ≈ 0), and the KE↔internal-energy pressure-dilatation is returned separately when pressure_hat is supplied. decomposition=HelmholtzDecomposition() also returns the rotational/compressive flux channels. T_u(k) = −dE_u(k)/dt from the nonlinear terms (positive when shell k gives energy to other shells) and Π(K) = Σ_{k≤K} T_u(k); in the incompressible limit T_u reduces to ρ × the incompressible transfer spectrum. This allocates a CompressibleWorkspace and delegates to calculate_compressible_flux!; build the workspace once and use the in-place form to loop over snapshots allocation-free. Under execution = GPUBackend(dev) the transfer runs in dev's memory, host inputs copied there once per call, and the per-shell results come back as host vectors. Under execution = DistributedBackend(inner) the field is computed on the calling process under inner; calculate_compressible_flux_batch divides snapshots among the workers.
FlowInvariantTransfer.Compressible.calculate_compressible_flux! — Function
calculate_compressible_flux!(ws::CompressibleWorkspace, velocity_hat, density_hat, ks;
pressure_hat=nothing, dealiasing=ws.dealiasing, decomposition=ws.decomposition)In-place momentum-weighted compressible transfer reusing ws (FFT plans + all field scratch). Returns a fresh CompressibleFluxResult whose arrays are the small per-shell vectors; the O(field) intermediates live in ws and are reused across calls (build the workspace once, loop over snapshots). On a workspace in device memory, host inputs are copied into its staging buffers and the per-shell vectors are host vectors.
FlowInvariantTransfer.Compressible.calculate_compressible_flux_batch — Function
calculate_compressible_flux_batch(velocity_hats, density_hats, ks; pressure_hats=nothing,
transform, binning, geometry, dealiasing, decomposition, execution) -> VectorCompressible transfer for a batch of snapshots sharing one grid (velocity_hats/density_hats iterables of coefficient arrays). One CompressibleWorkspace is built per worker and reused across its snapshots. execution = ThreadedBackend() (requires using OhMyThreads) threads over snapshots with a serial inner pipeline. Results are in input order and equal the per-snapshot calculate_compressible_flux.
Coarse-Graining Flux
FlowInvariantTransfer.CoarseGrainingFlux.calculate_coarse_graining_flux — Function
calculate_coarse_graining_flux(velocity_fields, coords_vecs, ℓ, filter;
decomposition=NoDecomposition(), diagnostics=nothing, kwargs...)
-> CoarseGrainingFluxResultCompute the pointwise cross-scale kinetic energy flux Πℓ(x) = −τ̄ᵢⱼ S̄ᵢⱼ at filter scale ℓ. Delegates entirely to CoarseGrainingEnergyFluxes.jl (`computeΠ!,filter_field!`).
Requires CoarseGrainingEnergyFluxes to be loaded:
using FlowInvariantTransfer, CoarseGrainingEnergyFluxes
result = calculate_coarse_graining_flux((u, v), (x, y), ℓ, FlowInvariantTransfer.Types.GaussianFilter())Arguments
velocity_fields: Tuple of D real arrays(u, v[, w])— velocity components.coords_vecs: Tuple of D coordinate vectors(x, y[, z]).ℓ::Real: Filter length scale (same units as coordinates).filter::AbstractFilter:GaussianFilter(),SharpSpectralFilter(), orTopHatFilter().
Keyword Arguments
decomposition::AbstractFieldDecomposition:NoDecomposition()(default),HelmholtzDecomposition(),RotationalDecomposition(), orDivergentDecomposition().decomposition_kwargs::NamedTuple = (;): keywords of the decomposition (for the Helmholtz familysolverandboundary; for the helical and toroidal/poloidal splitstransformandexecution).diagnostics = nothing:Types.StressStrain()also returns the τ̄ᵢⱼ and S̄ᵢⱼ fields.mask::Union{Nothing,AbstractMatrix{Bool}}=nothing: boolean point mask (true= point included in the computation,false= excluded). Ifnothing, all points are included.execution::AbstractExecutionBackend = AutoBackend(): the backend the filter runs on, passed toCoarseGrainingEnergyFluxes.Filtering.plan_filter, which resolvesAutoBackend. UnderGPUBackend(dev)the flux is computed indev's memory: host fields are copied there once per call,flux_fieldand the diagnostics are ondev, andmean_fluxis a host scalar.mask_strategy = ZeroFill(): CGEF's treatment of the masked points in the filter;radius: with coordinate vectors(lon, lat), the radius of the sphere they lie on.vector_filter = nothing: CGEF's filter of vectors and tensors (CGEF.Filtering.GeneralizedConvolution()orCartesianComponents()),nothingfor the oneCGEF.Filtering.resolve_vector_filterresolves for the grid andmask_strategy. On the surface of a sphere underZeroFillthat is the generalized convolution, whose spin-weighted transforms run through NUFSHT when it is loaded (FastSphericalHarmonics on its own grids) and through CGEF's direct sum otherwise.
Coordinate vectors, a longitude among them, build a FlowGeometries grid with no periodic direction (CoarseGrainingEnergyFluxes takes the exterior of a bounded grid as zero velocity); pass a grid that declares its periodic directions (topology, or a PeriodicUniformAxis longitude) for a periodic domain.
Returns
CoarseGrainingFluxResult; with a decomposition a NamedTuple of them, one per component, alongside the Helmholtz family's solve.
FlowInvariantTransfer.CoarseGrainingFlux.calculate_coarse_graining_flux_batch — Function
calculate_coarse_graining_flux_batch(velocity_fields_batch, coords_vecs, ℓ, filter; execution, kwargs...)
-> Vector{CoarseGrainingFluxResult}Coarse-graining flux Πℓ(x) for a batch of snapshots on the same grid (`velocityfields_batchan iterable of velocity-component tuples(u, v[, w])). OneCoarseGrainingFluxWorkspace(grid + CGEF plans, fixed for(ℓ, filter)`) is built per process and reused across its snapshots; each further thread of a threaded batch runs on a copy sharing its grid and CGEF tables, with buffers of its own.
execution runs the batch axis, and each snapshot's filter runs on the backend it implies: on SerialBackend(), ThreadedBackend() (requires using OhMyThreads, threads over snapshots), DistributedBackend(inner) and MPIBackend(inner) every snapshot is filtered serially (or on the device of an inner = GPUBackend(dev)), and on GPUBackend(dev) every snapshot is filtered on dev. Each result owns an independent copy of its flux field. Only NoDecomposition is supported; kwargs (mask, diagnostics, radius, …) are forwarded to the workspace. Requires CoarseGrainingEnergyFluxes to be loaded.
FlowInvariantTransfer.CoarseGrainingFlux.calculate_coarse_graining_flux! — Function
calculate_coarse_graining_flux!(ws::CoarseGrainingFluxWorkspace, velocity_fields)
-> CoarseGrainingFluxResultIn-place coarse-graining flux reusing the preallocated ws, allocation-free. The filter, scale, mask, execution backend and diagnostics are fixed by CoarseGrainingFluxWorkspace; call this per snapshot on the same grid.
The returned result wraps the reused ws.Π_out buffer (a subsequent call overwrites it); copy result.flux_field if the field must persist across calls. A decomposition is applied upstream, by passing the component fields.
Requires CoarseGrainingEnergyFluxes to be loaded.
FlowInvariantTransfer.CoarseGrainingFlux.CoarseGrainingFluxWorkspace — Type
CoarseGrainingFluxWorkspace(velocity_fields, coords_vecs, ℓ, filter;
mask=nothing, diagnostics=nothing, mask_strategy=…, vector_filter=nothing,
execution=…)Preallocated, reusable resources for calculate_coarse_graining_flux!, built for a fixed (filter, scale ℓ, mask, execution) configuration: the grid, its CGEF ΠWorkspace (filtered fields and stress/strain scratch), the Π_ℓ(x) output buffer, the derivative plan, the filter plan, and — when diagnostics = StressStrain() — the τ̄/S̄ diagnostic buffers. Build once, then apply to snapshots on the same grid with calculate_coarse_graining_flux!(ws, velocity_fields). A different scale, filter, mask or execution backend needs a new workspace.
Every buffer lives in the memory of the filter plan's backend, a device's under GPUBackend(dev). A workspace on a device built from host fields holds in stage the device buffers its host fields are copied into once per call.
Requires CoarseGrainingEnergyFluxes to be loaded.
FlowInvariantTransfer.CoarseGrainingFlux.calculate_enstrophy_flux — Function
calculate_enstrophy_flux(velocity_fields, geometry, ℓ, filter; kwargs...)Pointwise cross-scale enstrophy flux at filter scale ℓ — the vorticity carried through the tracer-variance flux, the enstrophy counterpart of calculate_coarse_graining_flux. geometry is the coordinate vectors or a FlowGeometries grid. Under execution = GPUBackend(dev) host fields are copied to dev and the flux is on dev. vector_filter is CGEF's filter of the vector u ω on a sphere, as for calculate_coarse_graining_flux. Requires CoarseGrainingEnergyFluxes to be loaded.
FlowInvariantTransfer.nufft_coarse_graining_flux — Function
nufft_coarse_graining_flux(velocity_fields, scatter_coords, ℓ, filter, ms; transform, Ls,
tol = nothing, weights = nothing, diagnostics = nothing,
execution = AutoBackend())
-> CoarseGrainingFluxResultCoarse-graining energy flux Π_ℓ(x) at scattered Cartesian points, by CoarseGrainingEnergyFluxes' nonuniform-FFT filter over the points as a FlowGeometries node set. Requires using CoarseGrainingEnergyFluxes.
velocity_fields and scatter_coords are D-tuples of length-N vectors, D 2 or 3: the velocity components and the point coordinates. Each field is analyzed on the ms modes of the periodic box, û = (1/∏L) Σⱼ wⱼ uⱼ e^{-ik·xⱼ}, multiplied by the transfer function of filter's CoarseGrainingEnergyFluxes kernel and synthesized at the points; S̄ᵢⱼ is the derivative of that filtered series and Π_ℓ = -τ̄ᵢⱼ S̄ᵢⱼ. weights wⱼ are the volumes the samples stand for (Σw = ∏L); without them every sample stands for ∏L/N, which is exact for samples on the uniform grid and an estimate weighted toward where the samples cluster otherwise. The domain mean is the same quadrature of Π. An even count m in ms holds the modes |n| ≤ m/2, the two at ±m/2 at half weight.
transform (required) names the NUFFT library: FlowTransformBindings.NonuniformFFTsBackend() (using NonuniformFFTs) or FlowTransformBindings.FINUFFTBackend() (using FINUFFT). Ls (required) is the periodic domain size per dimension. It sets the wavenumber grid k = 2πn/L, and hence the filter's transfer function and the strain: points in [xₘᵢₙ, xₘᵢₙ+Lₐ) under-span the period, so L is never inferred from them.
tol is the transforms' relative accuracy (nothing: FlowTransformBindings.default_tolerance of the coordinates' float type); diagnostics = Types.StressStrain() also returns τ̄ᵢⱼ and S̄ᵢⱼ at the points, each (N, D, D). execution places the workspace: AutoBackend() threads each transform where OhMyThreads is loaded and Julia has more than one thread, and GPUBackend(dev) holds it on dev. For a filter-scale sweep or a time series on one point set, build an NUFFTCoarseGrainingWorkspace and call nufft_coarse_graining_flux!.
FlowInvariantTransfer.nufft_coarse_graining_flux_batch — Function
nufft_coarse_graining_flux_batch(velocity_fields_batch, scatter_coords, ℓ, filter, ms;
transform, Ls, execution, kwargs...) -> VectorScattered coarse-graining flux for a batch of snapshots on one point set. The NUFFT plans and every buffer are built once for the whole batch. execution = ThreadedBackend() (requires using OhMyThreads) threads over snapshots, each further chunk on a copy of the workspace sharing its point set and weights, with library plans and buffers of its own; GPUBackend(dev) runs every snapshot on one workspace on dev. Results are in input order and each owns its flux field.
Scattered-Cartesian NUFFT
The scattered NUFFTs run through FlowTransformBindings' plans, on the library the required transform keyword names: FlowTransformBindings.NonuniformFFTsBackend() (using NonuniformFFTs) or FlowTransformBindings.FINUFFTBackend() (using FINUFFT, and using CUDA for cuFINUFFT on device points). They drive the scattered coarse-graining flux and the scattered→uniform to_spectral reconstruction; the workspace forms hold the plans and buffers for reuse, and close! releases the plans.
For real scattered input, every even requested mode count is widened by one and the result is the packed half of that odd box. Complex input keeps the requested full box.
FlowInvariantTransfer.NUFFTCoarseGrainingWorkspace — Type
NUFFTCoarseGrainingWorkspaceReusable resources for nufft_coarse_graining_flux!: the points as a FlowGeometries node set, CoarseGrainingEnergyFluxes' nonuniform-FFT filter plan over them (its transforms serve every scale and filter, its transfer function refilled per call), the flux workspace, the spectra of the velocity and its products, the Π output and, when built for them, the (N, D, D) stress and strain. A repeat call re-plans nothing; its result wraps the reused Π.
The plans hold library resources that close! releases; the allocating entries close theirs before returning. One task at a time may use a workspace. Requires using CoarseGrainingEnergyFluxes.
FlowInvariantTransfer.nufft_coarse_graining_flux! — Function
nufft_coarse_graining_flux!(ws::NUFFTCoarseGrainingWorkspace, velocity_fields, ℓ, filter, ms)
-> CoarseGrainingFluxResult or CoarseGrainingFluxResultWithDiagnosticsIn-place scattered coarse-graining flux reusing ws: every transform runs through its plan and every intermediate is a workspace buffer. The workspace's diagnostics fixes the result type. The result wraps ws.Π_out, and a later call overwrites it.
FlowInvariantTransfer.NUFFTToSpectralWorkspace — Type
NUFFTToSpectralWorkspaceReusable resources for the in-place scattered → uniform reconstruction to_spectral!: the type-1 plan over the points, the uniform wavenumber grid ks, and every working buffer (the (ms…, D) coefficient array û plus the transform's input and output), so a repeat to_spectral! re-plans nothing. The buffers live where execution puts them, on the device for a GPUBackend.
The plan holds library resources that close! releases; the allocating to_spectral closes its own before returning. One task at a time may use a workspace.
FlowInvariantTransfer.to_spectral! — Function
to_spectral!(ws::NUFFTToSpectralWorkspace, velocity_fields) -> (velocity_hat, ks)In-place scattered → uniform reconstruction reusing ws: û = (1/∏L) Σⱼ wⱼ uⱼ e^{-ik·xⱼ} (type1(u)/N without weights) in FFTW mode order, returned with the uniform wavenumber grid ks. The returned velocity_hat aliases ws.û, and a later call overwrites it.
to_spectral!(ws::ToSpectralWorkspace, velocity_fields) -> (velocity_hat, ks)In-place uniform-grid analysis reusing ws — no plan rebuild, no per-call buffers. The returned velocity_hat aliases ws.û and a later call overwrites it.
FlowInvariantTransfer.close! — Function
close!(ws::NUFFTToSpectralWorkspace) -> wsRelease the workspace's NUFFT resources.
Spherical Spectral Transfer
FlowInvariantTransfer.Spherical.calculate_spherical_transfer — Function
calculate_spherical_transfer(...)Extension entry point for the spherical spectral transfer. Implemented in the FastSphericalHarmonics (regular grid) and NUFSHT (scattered) extensions; loading one of those packages provides the method. Prefer the unified calculate_energy_transfer(SphericalTransferMethod(), …).
FlowInvariantTransfer.Spherical.calculate_spherical_transfer! — Function
calculate_spherical_transfer!(ws::SphericalTransferWorkspace, vorticity; kwargs...) -> SphericalTransferResultIn-place spherical spectral transfer reusing ws. Implemented in the FastSphericalHarmonics / NUFSHT extensions. Reuses the workspace's spectral work arrays, per-mode reduction buffers, and the result vectors, so a repeat call on the same grid allocates only inside the transform library (FastSphericalHarmonics has no in-place transform API). Build the workspace once with SphericalTransferWorkspace.
FlowInvariantTransfer.Spherical.calculate_divergent_spherical_transfer — Function
calculate_divergent_spherical_transfer(...)Extension entry point for the divergent horizontal-KE spherical spectral transfer. Implemented in the FastSphericalHarmonics (regular grid) and NUFSHT (scattered) extensions; loading one provides the method. Prefer the unified calculate_energy_transfer(DivergentSphericalTransferMethod(), …).
FlowInvariantTransfer.Spherical.calculate_divergent_spherical_transfer! — Function
calculate_divergent_spherical_transfer!(ws, u_θ, u_φ; kwargs...) -> DivergentSphericalTransferResultIn-place divergent spherical KE transfer reusing ws. Implemented in the FastSphericalHarmonics / NUFSHT extensions. Build the workspace once with DivergentSphericalTransferWorkspace (regular grid) or ScatteredDivergentSphericalTransferWorkspace (scattered points).
The spherical transfer on a masked FlowGeometries grid takes one of these as inactive.
FlowInvariantTransfer.Types.AbstractInactiveCells — Type
AbstractInactiveCellsHow the spherical transfer on a masked FlowGeometries grid reads the grid's inactive cells, passed as inactive: ZeroFill or Exclude. What an inactive cell holds, NaN included, never enters the transfer.
FlowInvariantTransfer.Types.ZeroFill — Type
ZeroFill <: AbstractInactiveCellsInactive cells count as zero: the transfer is that of the field extended by zero over the sphere, computed on every node of the grid. The default.
FlowInvariantTransfer.Types.Exclude — Type
Exclude <: AbstractInactiveCellsInactive cells are left out: the field's coefficients are the least-squares fit to the active cells alone, and the transfer is that of the band-limited field the fit defines, computed on every node of the grid.
Distributed (MPI)
FlowInvariantTransfer.mpi_batch_map — Function
mpi_batch_map(f, items; comm=MPI.COMM_WORLD, reduce=:gather, root=0)Distribute an embarrassingly-parallel batch of independent inputs across MPI ranks: each rank applies f to a round-robin subset of items (e.g. snapshots of a time series), then the per-item outputs are combined. With reduce=:gather (default) the results are collated into one Vector in the original order of items, returned on every rank; reduce=:sum/:mean returns the element-wise reduction (the outputs of f must support +, and / for :mean); a callable reduce is applied as a binary combiner. For one grid split across ranks, see pencil_spectral_flux.
Requires using MPI to load the extension.
FlowInvariantTransfer.pencil_spectral_flux — Function
pencil_spectral_flux(u_phys, plan, ks; comm=MPI.COMM_WORLD, binning, dealiasing, invariant, geometry, execution)
pencil_spectral_flux(fields; binning, dealiasing, invariant, geometry, execution)
-> SpectralFluxResultDistributed spectral transfer/flux for a single grid split across MPI ranks along the pencil axis: u_phys is the physical-space velocity as an NTuple{D, PencilArray} (one component per entry; each rank owns a pencil of the global grid) and plan is a distributed FFT plan from build_pencil_plan. The pseudospectral nonlinear term is evaluated with a transpose-based distributed FFT (PencilFFTs), the transfer density is shell-binned locally, and the per-shell spectrum is MPI.Allreduced to a global result identical on every rank (matching the serial calculate_spectral_flux on the same field). For many independent snapshots, see mpi_batch_map.
fields may be a tuple of FlowGeometries rank fields on one split grid. Its ownership defines the pencil layout. Requires using MPI, PencilFFTs, PencilArrays, FlowGeometries.
FlowInvariantTransfer.pencil_spectral_flux! — Function
pencil_spectral_flux!(ws::PencilWorkspace, u_phys; invariant=ws.invariant)
-> SpectralFluxResultIn-place distributed pencil spectral flux reusing ws and its result arrays. u_phys holds pencil arrays or FlowGeometries rank fields. invariant must match the workspace's. Requires using MPI, PencilFFTs, PencilArrays, FlowGeometries.
FlowInvariantTransfer.PencilWorkspace — Function
PencilWorkspace(plan, ks, comm=MPI.COMM_WORLD; binning, dealiasing=OrszagTwoThirds(),
geometry=IsotropicShells(), invariant=KineticEnergy(), execution=AutoBackend())
PencilWorkspace(fields; binning, kwargs...)
-> PencilWorkspaceReusable workspace for pencil_spectral_flux!: the (geometry/dealiasing/binning-fixed) wavenumber grids + shell structure and every per-snapshot scratch field, so a repeated distributed flux reuses the buffers and result. fields is a tuple of FlowGeometries rank fields on one split. Requires using MPI, PencilFFTs, PencilArrays, FlowGeometries.
execution composes an inner local backend with the MPI (pencil) axis, e.g. execution=MPIBackend(GPUBackend(dev)) for a per-rank device pencil (multi-GPU) — the local shell reduction then runs as an on-device scatter-add.
FlowInvariantTransfer.build_pencil_plan — Function
build_pencil_plan(T, ns, comm=MPI.COMM_WORLD) -> PencilFFTPlan
build_pencil_plan(T, split::FlowGeometries.Decomposition.AbstractRankSplit) -> PencilFFTPlanConvenience constructor for the distributed FFT plan used by pencil_spectral_flux, with an auto-balanced MPI process grid. The velocity is real, so axis 1 is a real-to-complex transform and each rank's spectral pencil holds the non-redundant k₁ ≥ 0 half: pass the matching wavenumber tuple, Utils.wavenumber_grid(T, ns, Ls) with the real element type T (default Float64). A split grid supplies its layout and communicator. Requires using MPI, PencilFFTs, PencilArrays, FlowGeometries.
Triadic Orthogonal Decomposition
FlowInvariantTransfer.TriadicOrthogonalDecomposition.triadic_orthogonal_decomposition — Function
triadic_orthogonal_decomposition(X; kwargs...)
-> TriadicOrthogonalDecompositionResultCompute the Triadic Orthogonal Decomposition of data array X.
TOD decomposes triadic (three-wave) nonlinear interactions in time-series data, identifying coherent flow structures that optimally capture spectral momentum transfer. It produces a mode bispectrum (singular values quantifying coupling strength per frequency triad), convective/recipient modes, and a modal energy budget.
Arguments
X::AbstractArray: Data of size(nt, nvar, spatial_dims...). First dimension is time, second is variable indices, remaining are spatial.
Keyword Arguments
window: Temporal window. Vector → used directly. Integer → Hamming of that length.nothing→ auto Hamming (length = 2^floor(log2(nt/5)), capped at 256).weight: Spatial inner-product weight (same spatial dims as X).nothing→ uniform.noverlap: Block overlap in snapshots.nothing→ 50% of window length.dt: Time step between snapshots.nothing→ 1/nDFT (frequency index output).Q: Quadratic nonlinearity(q1, q2) -> productof two(nVar, nx, nBlks)realizations,q1atf_k = f_n − f_landq2atf_l, returning(nx, nState, nBlks). Default: the elementwise product,Q(q1, q2)[ix, iv, b] = q1[iv, ix, b]·q2[iv, ix, b], which takes no derivative.LHS: Left-hand side operatorq -> Lq. Default:identity.nmode: Modes per triad to store.nothing→ nBlks.nfreq: Restrict to|l|, |k|, |n| ≤ nfreq.nothing→ all.isreal_data: Whether data is real (restricts bispectrum to fn ≥ 0).nothing→ auto.mean:ZeroMean()(default),BlockMean(), or an array containing the mean to subtract.output:ModesOnly()(default),WithCoefficients(), orWithAuxiliaryModes().transform::SpectralBackends.AbstractSpectralBackend=SpectralBackends.AutoSpectralBackend(): temporal-DFT transform, resolving toFFTSpectralBackend()when FFTW is loaded and to theO(nDFT²)DirectSumSpectralBackend()reference otherwise.execution::ComputationalBackends.AbstractExecutionBackend=ComputationalBackends.AutoBackend(): triad-loop parallelism.ComputationalBackends.ThreadedBackend()parallelises the triad loop (requires OhMyThreads).
Returns
TriadicOrthogonalDecompositionResult containing:
frequencies: Frequency vector.mode_bispectrum: Singular values per triad per mode.modes: Dict of convective/recipient mode pairs.modal_energy_budget:λ_m Re⟨φ_m, W ψ_m⟩per triad per mode,φ_mthe recipient andψ_mthe convective mode. It is the modal energy transfer of Yeung, Chu & Schmidt whenQis the quadratic term of the flow's evolution equation (for velocity data, its advective term with the sign it carries there); with the defaultQit is that same projection of the elementwise product. Summed over every mode it isRe⟨q̂_n, W·Q(q̂_k, q̂_l)⟩averaged over the blocks, and withQ(q₁, q₂) = −(q₁·∇)q₂on a divergence-free periodic field the sums at(f_l, f_n)and(f_n, f_l)cancel (their Eq. 38).expansion_coefficients: Expansion coefficients (ornothing).auxiliary_modes: Donor/catalyst modes (ornothing).
References
- Yeung, Chu & Schmidt (2026), J. Fluid Mech. 1031, A34. DOI 10.1017/jfm.2026.11183
FlowInvariantTransfer.TriadicOrthogonalDecomposition.triadic_orthogonal_decomposition! — Function
triadic_orthogonal_decomposition!(ws::TODWorkspace, X; output=ModesOnly(), execution=AutoBackend())
-> TriadicOrthogonalDecompositionResultIn-place Triadic Orthogonal Decomposition reusing the preallocated ws (its Q_hat, DFT plan/scratch, weights, SVD scratch, and L/T_budget buffers). X must match the workspace dimensions. Repeated calls on same-shaped snapshots re-plan nothing and allocate only the per-triad output modes; the returned result wraps the reused L/T_budget (a later call overwrites them — copy if persisting). The analysis parameters (window/weight/LHS/Q/…) are fixed at workspace construction.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.TODWorkspace — Type
TODWorkspace(X; window, weight, noverlap, dt, Q, LHS, nmode, nfreq, isreal_data, mean, transform)Preallocated, reusable state for triadic_orthogonal_decomposition!: the temporal-DFT output Q_hat, (nVar, nx, nBlks, nFreq) so that a frequency's realizations are contiguous, one block's transform Q_blk (nDFT, nx) before it is stored there, the DFT plan + per-column scratch, the spatial weights and their √/1-over-√, the per-triad SVD scratch and permute buffer, and the L/T_budget output arrays. Sized from X's dimensions and the analysis parameters, all fixed at construction; reused across snapshots of the same shape, a repeat decomposition allocates only the per-triad output modes.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.hamming_window — Function
hamming_window(N, ::Type{T} = Float64) -> Vector{T}Standard Hamming window of length N: w[n] = 0.54 − 0.46·cos(2πn/(N−1)), in element type T.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.hann_window — Function
hann_window(N, ::Type{T} = Float64) -> Vector{T}Hann (raised-cosine) window of length N: w[n] = ½(1 − cos(2πn/(N−1))), in element type T. Tapers to zero at both ends — lower spectral leakage than Hamming. Pass to triadic_orthogonal_decomposition via window.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.tukey_window — Function
tukey_window(N, ::Type{T} = Float64; α=0.5) -> Vector{T}Tukey (tapered-cosine) window of length N in element type T: a flat middle with cosine tapers over a fraction α of the length at each end. α = 0 is rectangular (no taper), α = 1 is the Hann window; intermediate α trades main-lobe width against leakage.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.ModesOnly — Type
Return the bispectrum, modes and modal energy budget.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.WithCoefficients — Type
Include the modes' expansion coefficients.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.WithAuxiliaryModes — Type
Include expansion coefficients and donor/catalyst modes.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.ZeroMean — Type
Analyse the field with zero temporal mean.
FlowInvariantTransfer.TriadicOrthogonalDecomposition.BlockMean — Type
Subtract each block's mean and restore its uncentred DC coefficient.
Nonlinear Term
FlowInvariantTransfer.NonlinearTerm.compute_nonlinear_term — Function
compute_nonlinear_term(advected_hat, ks; dealiasing=OrszagTwoThirds(),
transform=SpectralBackends.AutoSpectralBackend(), advecting_hat=advected_hat)Compute the pseudospectral nonlinear term 𝒩̂ᵢ(k) = F̂[(uⱼ ∂fᵢ/∂xⱼ)] — the advection of an M-component field f (advected_hat) by a velocity u (advecting_hat). For the momentum self-advection term pass the velocity as both (the default), giving N̂ᵢ = F̂[(u·∇)uᵢ].
Arguments
advected_hat: Array of size(ms..., M)— Fourier coefficients of the advected fieldf(M = Dfor momentum,M = 1for a passive scalar / vector potential).ks: Tuple of 1D wavenumber vectors (lengthnd), one per spatial dimension.
Keyword Arguments
dealiasing::AbstractDealiasing=OrszagTwoThirds(): dealiasing strategy (NoDealiasing / OrszagTwoThirds / PaddedThreeHalves).transform::SpectralBackends.AbstractSpectralBackend:SpectralBackends.AutoSpectralBackend()(default: FFT when FFTW is loaded, else the direct sum),SpectralBackends.DirectSumSpectralBackend()(no dependencies) orSpectralBackends.FFTSpectralBackend()(requires the FFTW extension).advecting_hat: the advecting velocityu(shape(ms..., D),D ≥ nd); defaults toadvected_hat(self-advection). Only thendspatial components participate in(u·∇).
Returns
Array of size (ms..., M) containing 𝒩̂ᵢ(k).
FlowInvariantTransfer.NonlinearTerm.compute_nonlinear_term! — Function
compute_nonlinear_term!(ws, advected_hat, ks; dealiasing=OrszagTwoThirds(),
transform=SpectralBackends.AutoSpectralBackend(), advecting_hat=advected_hat) -> ws.N̂In-place version of compute_nonlinear_term, writing into ws.N̂. ws is a NonlinearTermWorkspace sized for advected_hat.
FlowInvariantTransfer.NonlinearTerm.synthesize_advecting! — Function
synthesize_advecting!(ws, advecting_hat, ks; dealiasing=OrszagTwoThirds(),
transform=AutoSpectralBackend()) -> wsThe advecting velocity of compute_nonlinear_term!, synthesized into ws (on the padded grid under PaddedThreeHalves). A driver that advects several fields by one velocity calls this once and compute_advection! per field.
FlowInvariantTransfer.NonlinearTerm.compute_advection! — Function
compute_advection!(ws, advected_hat, ks; dealiasing=OrszagTwoThirds(),
transform=AutoSpectralBackend()) -> ws.N̂compute_nonlinear_term! of advected_hat by the velocity synthesize_advecting! left in ws, with the same dealiasing and transform.
FlowInvariantTransfer.NonlinearTerm.compute_rotational_term! — Function
compute_rotational_term!(ws, velocity_hat, vortex_hat, ks; dealiasing=OrszagTwoThirds(),
transform=AutoSpectralBackend()) -> ws.N̂𝒩̂ = FFT[ω × u], written into ws.N̂: u is synthesised from velocity_hat and ω = ∇ × v from vortex_hat, both (ms..., D) coefficient arrays in D = 2 or 3 dimensions (in 2-D ω is the scalar ∂₁v₂ − ∂₂v₁ and the product ω ẑ × u), with the normalization, input truncation and output zeroing of compute_nonlinear_term!.
(u·∇)u = ω × u + ∇(½|u|²), and the gradient has no projection on a divergence-free û, so Re{û*·𝒩̂} is the kinetic-energy transfer density of (u·∇)u when v = u is solenoidal.
Invariant Transfer Density
FlowInvariantTransfer.Invariants.transfer_density — Function
transfer_density(invariant, velocity_hat, N̂, ks) -> ArrayAllocating version of transfer_density!: returns a real array of shape ns with the per-mode transfer density.
FlowInvariantTransfer.Invariants.transfer_density! — Function
transfer_density!(t, invariant, velocity_hat, N̂, ks) -> tWrite the real per-mode transfer density for invariant into t (shape ns), given Fourier-space velocity velocity_hat and nonlinear term N̂ (both shape (ns..., D)) and wavenumber vectors ks (length D). No allocations.
FlowInvariantTransfer.Invariants.transfer_density_scatter! — Function
transfer_density_scatter!(T_spec, invariant, carrier_hat, N̂, ks, shell_idx) -> T_specShell sums of the transfer density, without materialising the density. T_spec[n] accumulates w(I)·t[I] over the modes I with shell_idx[I] == n, for the same per-mode density t as transfer_density! and the Hermitian weight w of the spectral layout (FlowTransformBindings.mode_fold) — 1 throughout on a full spectrum, and on a half spectrum the factor by which each stored mode accounts for the ones it stands in for. Callers that need the per-mode density itself use transfer_density!.
Field Decomposition
decompose_field splits a field on either side of the transform. Given coefficients it returns coefficients; given physical fields and a FlowGeometries grid it returns physical fields — the Helmholtz family by solving on the grid, and the per-mode splits (helical, toroidal/poloidal) by analysing, projecting and synthesising each component back. The Helmholtz family also takes coordinate ranges, the periodic box of period N·Δ along each.
FlowInvariantTransfer.Decomposition.decompose_field — Function
decompose_field(decomp::AbstractFieldDecomposition, fields::Tuple, domain; kwargs...)Decompose a physical-space velocity field fields (e.g. (u, v)) with the given strategy on the FlowGeometries grid domain. The solver is selected from the grid's geometry, sampling, mask and topology: the Helmholtz family through the HelmholtzDecomposition extension, the helical and toroidal/poloidal splits through the FlowFieldSpectra extension. The Helmholtz family also takes a tuple of ranges (x, y[, z]) as domain: the unmasked periodic Cartesian box of N samples Δ apart along each, period N·Δ, as Utils.domain_size_from_coords reads them.
Returns a NamedTuple of component tuples keyed by the decomposition's names (rotational, divergent; positive, negative; toroidal, poloidal). The Helmholtz family solves for potentials and adds solve, the FlowTransformBindings.SolverResult of the least converged of its solves that iterate, nothing where each is an exact transform; RotationalDecomposition/DivergentDecomposition return that one component. NoDecomposition returns the components untouched and also accepts coordinate vectors.
decompose_field(decomp::AbstractFieldDecomposition, velocity_hat::AbstractArray{<:Complex}, ks)Decompose a spectral-space velocity field velocity_hat along the wavenumbers ks. Each returned array has the shape of velocity_hat.
HelicalDecomposition(3D) returns(positive = u₊, negative = u₋), the positive/negative-helicity vector components; for an incompressible fieldpositive .+ negative ≈ velocity_hat.ToroidalPoloidalDecomposition(3D) returns(toroidal = u_tor, poloidal = u_pol)in the Craya–Herring frame; both are divergence-free and sum to the solenoidal part ofvelocity_hat.NoDecompositionreturnsvelocity_hat.
FlowInvariantTransfer.Decomposition.decompose_field! — Function
decompose_field!(out::NamedTuple, decomp, velocity_hat, ks) -> outSpectral decomposition into the caller-provided component buffers of out ((positive, negative) or (toroidal, poloidal)), allocation-free and device-generic.
Both components are Hermitian for a real field, so either spectral layout represents them: under k ↦ −k the frame obeys e1 ↦ −e1 and e2 ↦ e2, which carries u_±(−k) = conj(u_±(k)). The frame is built from the derivative wavenumbers the package's curl and divergence use, zero along an even axis at its Nyquist slot, so a mode there has the frame of its own mirror and is split as those operators see it.
FlowInvariantTransfer.Decomposition.helmholtz_project_spectral! — Function
helmholtz_project_spectral!(û_rot, û_div, û_harm, velocity_hat, ks)In-place spectral Helmholtz–Hodge projection of velocity_hat into its rotational, divergent, and harmonic (k = 0 / constant) parts (û_rot + û_div + û_harm == velocity_hat), writing into the three caller-provided buffers — allocation-free. Provided by the HelmholtzDecomposition.jl extension; this core stub errors until it is loaded.
Band Energies
The content of an invariant in each band, E(n) = Σ_k w_n(k)·e(k). The band definition supplies the weight w_n and nothing else: an AbstractShellBinning gives the sharp indicator of a shell, and SmoothBands the graded partition of unity calculate_band_to_band_transfer moves energy between, so passing the same bands to both describes one partition. A separate method takes physical fields, a domain and a filter, where the weight is the filter's own transfer function and the sum runs in real space (so it also serves masked and bounded domains).
FlowInvariantTransfer.CoarseGrainingFlux.calculate_band_energies — Function
calculate_band_energies(velocity_fields, geometry, filter, scales; kwargs...)Scale-band kinetic energies: the energy in each band between successive entries of scales, from the filtered field at each scale. geometry is the coordinate vectors or a FlowGeometries grid, as for calculate_coarse_graining_flux. Pass maps = CoarseGrainingEnergyFluxes.Diagnostics.BandMaps() for the per-point band fields alongside the integrals. Under execution = GPUBackend(dev) host fields are copied to dev and the maps are on dev. vector_filter is CGEF's filter of the velocity on a sphere, as for calculate_coarse_graining_flux. Requires CoarseGrainingEnergyFluxes to be loaded.
calculate_band_energies(velocity_hat, ks; bands, invariant, geometry) -> (; centers, energies)Content of invariant in each band of bands, E(n) = Σ_k w_n(k)·e(k).
bands fixes the weight w_n: an AbstractShellBinning gives the indicator of shell n, SmoothBands the graded partition of unity of calculate_band_to_band_transfer, so the same bands passed to both describe one partition. e is the invariant's quadratic spectral density (½Σ_c|û_c|² for kinetic energy, ½|ω̂|² for enstrophy, Re{conj(û)·ω̂} for helicity), with the Hermitian weight on a half spectrum so the total matches the full-spectrum sum.
Wavenumber Utilities
The wavenumber axes, their fold weights and the dealiasing cutoffs are the packed layout of FlowTransformBindings (documented there): FlowTransformBindings.RFFTAxis, FlowTransformBindings.FFTAxis, FlowTransformBindings.mode_fold, FlowTransformBindings.dealias_cutoff.
FlowInvariantTransfer.Utils.wavenumber_grid — Function
wavenumber_grid([T,] ns, Ls) -> NTuple{D, AbstractWavenumberAxis}The physical wavenumber axes of an ns-point periodic grid of side lengths Ls, k = 2πm/L, in the FFTW fftfreq order (m = 0, 1, …, ⌊(N−1)/2⌋, −⌊N/2⌋, …, −1), for a spectrum of a field of element type T. For a real T the first axis is the rfftfreq half m = 0…N₁÷2 — the layout of a real field's rfft — and the remaining axes stay fftfreq; without T, every axis is fftfreq. The axes are FlowTransformBindings.RFFTAxis / FlowTransformBindings.FFTAxis: no wavenumber array is stored, and they carry the field's spectral layout for every diagnostic.
FlowInvariantTransfer.Utils.wavenumber_magnitude_grid — Function
wavenumber_magnitude_grid(ks) -> Array{T, D}The isotropic wavenumber magnitude |k| at every stored mode of the layout ks.
Arguments
ks::NTuple{D, AbstractVector}: Tuple of 1D wavenumber vectors (e.g., fromwavenumber_grid).
Returns
D-dimensional array of the coefficient shape of ks (the halved first axis included), with entry [i₁,…,i_D] = sqrt(ks[1][i₁]² + … + ks[D][i_D]²) and element type T, the promotion of the axes' element types.
FlowInvariantTransfer.Utils.as_component_field — Function
as_component_field(f, nd) -> array of rank nd+1Normalize a field to the package's (ns..., M) component-axis convention: a rank-nd array (ns...) (e.g. a scalar) is reshaped to (ns..., 1); a rank-nd+1 array is returned unchanged.
FlowInvariantTransfer.Utils.validate_velocity_input — Function
validate_velocity_input(velocity_components, dims)Check that all velocity components have the same size and that it is consistent with dims dimensions.
Throws DimensionMismatch with a descriptive message on failure.
FlowInvariantTransfer.Utils.validate_uniform_grid — Function
validate_uniform_grid(coords_vecs) -> NTuple{D}Return the spacing of each range. Coordinate vectors require a FlowGeometries grid that declares their sampling and period.
FlowInvariantTransfer.Utils.domain_size_from_coords — Function
domain_size_from_coords(coords_vecs) -> NTuple{D}The period L = NΔ of each coordinate vector read as N periodic samples x_1, x_1 + Δ, …, x_1 + (N−1)Δ, the last one step short of x_1 + L, in the coordinates' float type. A vector that ends at x_1 + L repeats the first sample and does not meet this contract. A vector of fewer than two points has period 1.
Shell Binning & Geometry
FlowInvariantTransfer.ShellBinning.assign_shells — Function
assign_shells(k_mag, edges) -> Array{Int}Return an integer array (same shape as k_mag) where [I] = n if edges[n] <= k_mag[I] < edges[n+1], or n = N_sh if k_mag[I] == edges[end], and 0 if the mode falls outside all shells.
FlowInvariantTransfer.ShellBinning.shell_edges — Function
shell_edges(binning, k_max) -> AbstractVectorReturn the monotonically increasing shell boundary vector for binning up to k_max, in the float type of k_max (a CustomBinning returns its own edges).
The resulting vector has length n_shells(binning, k_max) + 1; shell n covers wavenumbers in [edges[n], edges[n+1]), and the last shell includes edges[end]. The built-in binnings start at 0 and end at k_max, so every mode lies in a shell.
FlowInvariantTransfer.ShellBinning.shell_centers — Function
shell_centers(binning, k_max) -> AbstractVectorReturn the midpoint of each shell. For logarithmic binnings, this is the geometric mean of the edge pair, and half the upper edge for the [0, k₀) shell; for linear binnings, the arithmetic mean.
FlowInvariantTransfer.ShellBinning.n_shells — Function
n_shells(binning, k_max) -> IntReturn the number of shells for binning up to k_max.
FlowInvariantTransfer.ShellBinning.shell_coordinate — Function
shell_coordinate(geometry, ks) -> ArrayReturn an array (shape ns) giving the wavenumber coordinate each mode is binned by under geometry. For ShellMagnitude this is √(Σ_{d∈dims} k_d²) — |k| when dims covers all dimensions (isotropic), k_⊥/k_∥ for an anisotropic projection.
FlowInvariantTransfer.ShellBinning.max_shell_coordinate — Function
max_shell_coordinate(geometry, ks) -> Realmaximum(shell_coordinate(geometry, ks)) in O(nd): over a tensor grid the maximum of √(Σ_d k_d²) is √(Σ_d max_d k_d²). Equal on the full and half layouts, so shell edges built from it do not depend on how the field is stored.
FlowInvariantTransfer.ShellBinning.default_binning — Function
default_binning(ks) -> LinearBinningLinearBinning(Δk) with Δk the smallest nonzero |k| on any axis, in the float type the axes promote to; Δk = 1 when no axis has a nonzero wavenumber.
Binning Types
FlowInvariantTransfer.Types.AbstractShellBinning — Type
AbstractShellBinningSupertype for shell spacing strategies (how wavenumber space is partitioned into shells): LinearBinning, LogarithmicBinning, DyadicBinning, CustomBinning. Orthogonal to the shell coordinate (AbstractShellGeometry).
FlowInvariantTransfer.Types.LinearBinning — Type
LinearBinning(Δk) <: AbstractShellBinningShells of width Δk: edges 0, Δk, 2Δk, … up to the largest wavenumber coordinate, shell n covering [(n−1)Δk, nΔk) around its centre (n−½)Δk, and the last shell closed; the flux Π[n] is the flux through nΔk. With Δk the fundamental wavenumber, shell 1 holds the mean mode alone and |k| = nΔk falls in shell n + 1.
Fields
Δk: Shell width in physical wavenumber units.
FlowInvariantTransfer.Types.LogarithmicBinning — Type
LogarithmicBinning(k₀, λ) <: AbstractShellBinningGeometrically-spaced shells: edges 0, k₀, k₀λ, k₀λ², …, the first shell [0, k₀).
Fields
k₀: Lower edge of the first geometric shell (> 0).λ: Ratio between consecutive shell edges (> 1); λ = 2 gives dyadic.
FlowInvariantTransfer.Types.DyadicBinning — Type
DyadicBinning(k₀) <: AbstractShellBinningDyadic (octave) shells: edges 0, k₀, 2k₀, 4k₀, …. Equivalent to LogarithmicBinning(k₀, 2.0).
Fields
k₀: Lower edge of the first octave shell (> 0).
FlowInvariantTransfer.Types.CustomBinning — Type
CustomBinning(edges) <: AbstractShellBinningUser-specified shell edges. Shell n covers wavenumbers in [edges[n], edges[n+1]), and the last shell includes edges[end]; modes outside [edges[1], edges[end]] belong to no shell.
Fields
edges: Monotonically increasing edge values (length = N_shells + 1).
FlowInvariantTransfer.Types.SmoothBands — Type
SmoothBands(centers; logwidth=0.6)Graded (smooth) spectral bands for band-to-band transfer T(K,Q) (Eyink & Aluie 2009), as an alternative to the sharp shells of AbstractShellBinning. Each band n weights a mode at coordinate κ by a log-Gaussian exp(−(ln(κ/centers[n]))² / (2·logwidth²)), renormalized across bands to a partition of unity (Σ_n w_n(κ) = 1) so the smooth bands conserve and reduce to the band-summed transfer spectrum. Smaller logwidth → sharper, more shell-like bands.
Fields
centers: band-center wavenumbers (monotonically increasing, all > 0).logwidth: Gaussian width inln κ(dimensionless); default0.6(≈ one octave overlap).
Shell Geometry
FlowInvariantTransfer.Types.AbstractShellGeometry — Type
AbstractShellGeometryAbstract supertype selecting the wavenumber coordinate the shells partition (isotropic |k|, or an anisotropic projection like k_⊥/k_∥). Orthogonal to the binning spacing (AbstractShellBinning); the geometry changes only the scalar each mode is binned by. The anisotropic fluxes Π(k_⊥), Π(k_∥) of rotating/stratified flow follow Alexakis & Biferale (2018, §IV).
FlowInvariantTransfer.Types.ShellMagnitude — Type
ShellMagnitude(dims) <: AbstractShellGeometryBin modes by the Euclidean magnitude of the wavenumber components in dims: κ(k) = √(Σ_{d∈dims} k_d²). dims === nothing uses all spatial dimensions (isotropic |k|).
Use the constructors IsotropicShells, PerpendicularShells, ParallelShells for the common cases.
FlowInvariantTransfer.Types.IsotropicShells — Function
IsotropicShells() -> ShellMagnitudeIsotropic shells over |k| (all dimensions) — the default geometry.
FlowInvariantTransfer.Types.PerpendicularShells — Function
PerpendicularShells(dims=(1, 2)) -> ShellMagnitudeCylindrical shells over k_⊥ = √(Σ_{d∈dims} k_d²) (the horizontal plane by default), giving the anisotropic perpendicular flux Π(k_⊥) for rotating/stratified flows.
FlowInvariantTransfer.Types.ParallelShells — Function
ParallelShells(dims=(3,)) -> ShellMagnitudePlane shells over k_∥ = √(Σ_{d∈dims} k_d²) (the vertical axis by default), giving the anisotropic parallel flux Π(k_∥).
Spectral (Transform) Backends
The transform-algorithm tags are provided by the shared SpectralBackends package (documented there). FIT selects the transform by the tag's geometry; the concrete types are SpectralBackends.DirectSumSpectralBackend, SpectralBackends.FFTSpectralBackend, SpectralBackends.FSHTSpectralBackend, and SpectralBackends.NUFSHTSpectralBackend, all <: SpectralBackends.AbstractSpectralBackend. The scattered-Cartesian NUFFT libraries' tags come from FlowTransformBindings, as subtypes of SpectralBackends.AbstractNonUniformFastFourierTransformSpectralBackend: FlowTransformBindings.FINUFFTBackend (using FINUFFT) and FlowTransformBindings.NonuniformFFTsBackend (using NonuniformFFTs). The transform keyword's default, SpectralBackends.AutoSpectralBackend, resolves through FIT's own FlowInvariantTransfer.Types.resolve_transform (the FFT when the FFTW extension is loaded, else the direct sum).
Execution (Parallelism) Backends
The execution tags are provided by the shared ComputationalBackends package (documented there): ComputationalBackends.SerialBackend, ThreadedBackend, DistributedBackend, MPIBackend, GPUBackend, and AutoBackend, all <: ComputationalBackends.AbstractExecutionBackend. FIT resolves ComputationalBackends.AutoBackend through its own FlowInvariantTransfer.Types.resolve_execution (threaded when the OhMyThreads extension is loaded and Threads.nthreads() > 1, else serial). AutoBackend() is the execution default; a device-array input selects its device backend.
Filters
FlowInvariantTransfer.Types.AbstractFilter — Type
AbstractFilterSupertype for spectral filter kernels used by coarse-graining: SharpSpectralFilter, GaussianFilter, TopHatFilter.
FlowInvariantTransfer.Types.SharpSpectralFilter — Type
SharpSpectralFilter <: AbstractFilterIdeal low-pass (brick-wall) filter in spectral space: Ĝ(k, ℓ) = 1 if |k| < π/ℓ, else 0.
Provides exact scale separation but produces Gibbs ringing in physical space.
FlowInvariantTransfer.Types.GaussianFilter — Type
GaussianFilter <: AbstractFilterGaussian filter in spectral space: Ĝ(k, ℓ) = exp(−k² ℓ² / 24).
Excellent physical-space locality; widely used in LES and coarse-graining studies. The normalisation factor 24 follows the convention of Aluie et al. (2018).
FlowInvariantTransfer.Types.TopHatFilter — Type
TopHatFilter <: AbstractFilterTop-hat (box) filter in physical space; sinc response in spectral space: Ĝ(k, ℓ) = sinc(k ℓ / (2π)).
Compact support in physical space; standard in LES.
FlowInvariantTransfer.Filters.filter_response — Function
filter_response(filter, k, ℓ) -> RealEvaluate the spectral transfer function Ĝ(k, ℓ) of filter at wavenumber magnitude k and filter scale ℓ.
The filter scale ℓ is defined so that the filter retains scales larger than ℓ.
FlowInvariantTransfer.Filters.apply_filter_spectral — Function
apply_filter_spectral(û_in, k_mag, filter, ℓ) -> ArrayNon-mutating version of apply_filter_spectral!.
FlowInvariantTransfer.Filters.apply_filter_spectral! — Function
apply_filter_spectral!(û_out, û_in, k_mag, filter, ℓ)Apply filter at scale ℓ in spectral space by pointwise multiplication: ûout[I] = Ĝ(|k[I]|, ℓ) * ûin[I].
Arguments
û_out: Output spectral array (same shape asû_in).û_in: Input spectral array (complex or real).k_mag: Array of wavenumber magnitudes (same shape asû_in).filter::AbstractFilter: Filter kernel.ℓ::Real: Filter scale.
Modifies û_out in-place and returns it.
Plotting
FlowInvariantTransfer.plot_energy_transfer — Function
plot_energy_transfer(result; kwargs...)Plot an energy transfer result. Requires CairoMakie to be loaded.