diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd0846..9fcb4e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,17 +2,107 @@ All notable changes to this project will be documented in this file. -## [Unreleased] +## [0.4.0] - 2026-09-11 + +### Names and namespace + +- The vocabulary is the domain's: several quantities at one set of points are **fields**, not + "channels". `Fields` now lives in the `MultiFields` submodule, with `FieldIncrement`, + `n_vector_fields`, `n_scalar_fields` and `field_dimension`. +- The package exports only its own names — the bin-edge types, the tapers and `HarmonicNodes`, the + result types, `KHM` and `midpoints`. Everything else is reached through the submodule that owns it: + `Calculations` for the entries, `StructureFunctionTypes` for the operators, `HelperFunctions` for + the geometry, `MultiFields` for `Fields`. + +### Input shapes and geometry + +- Arrays `(D, N)` for point lists and `(D, N, auxiliary...)` for batches over trailing axes are the + input contract; tuple-of-vector inputs are refused by name. +- Spherical geometry: `SphericalDistance(R)`, `Distances.Haversine` and `Distances.SphericalAngle` + metrics transport every pair into its geodesic frame; a point is located by `(lon, lat)` while the + velocity may carry a radial component. Degenerate (coincident, antipodal) pairs are skipped. +- Multi-fields `Fields(vectors = (u, …), scalars = (θ, …))` with the operators `ScalarSFType{P}`, + `MixedSFType{NL,NT,P}`, `VectorDotSFType(a, b)`, `ScalarDotSFType(a, b)`; a field of scalars alone + is located by its coordinates; odd scalar moments read every pair canonically, independent of the + input order. +- Pair weights: `weights` (one per point or cell) on the point entries, the gridded sweeps, the + transforms and the device engine; `cell_measure(grid)` gives a grid's cell areas. +- The transverse convention is a field of the projected operator: + `ProjectedStructureFunctionType{NL, NT}(basis)` with `CanonicalTransverseBasis()` (the right-hand rule + about `ẑ`, continued about `x̂` where `r̂ ∥ ẑ`) or `ReferenceAxisTransverseBasis(a)`; every rule's + first vector is odd under `r̂ ↦ −r̂`. The GPU batch kernel's transverse sign, which negated `T3` and + `L2T1`, is fixed. + +### Grids + +- `FlowGeometries` grids route by their axis types to `UniformLagSchedule`, `RectilinearLagSchedule` + (any number of uniform axes beside enumerated ones), `ZonalLagSchedule` (lat-lon, the pair frame per + lag, pole-invariant) or `ScatteredPairs`; every route is exact and the direct sweep is one + implementation for all separable schedules, with culling and threading. +- The transform engine (`FastFourierTransformSpectralBackend`) computes **every polynomial operator at + any order** on every separable schedule as cross-correlations of masked monomials: exact with missing + cells at every order, bounded directions zero-padded to `n + h_max`, multi-fields, weights, the + directional histogram over the separation angle, and the increment moment tensors + (`calculate_structure_function_tensor` on grids and the joint tensor over angle; + `StructureFunctionTensor2DSumsAndCounts`). `AutoSpectralBackend()` costs both algorithms. +- The same engine on a device (`GPUBackend`): monomial transforms through the device's `AbstractFFTs` + and one lag kernel for the binning, on every schedule. +- The harmonic route on a sphere: `HarmonicNodes` kernel-binned statistics for scalars at any order and + vectors through the spin-weighted expansion, `harmonic_spectra`, the NUFSHT extension and a direct-sum + reference; results carry floating-point kernel-weighted counts. +- A soft-binned route for scattered points by non-uniform FFT (`ScatteredModesSchedule`) with two + providers, each named by its own tag: `NonuniformFFTsSpectralBackend` (NonuniformFFTs, CPU and CUDA) + and `FINUFFTSpectralBackend` (FINUFFT, CPU and cuFINUFFT); results carry `ModeBinEdges` and are + documented as not exact. +- An exact sorted route for one-dimensional point lists (prefix sums of monomials), taken automatically + by the CPU backends for polynomial operators. +- Tensors on point lists at any order, joint in separation and angle. + +### Spectra and fluxes + +- `isotropic_spectrum` in one, two and three dimensions with verified constants; `gridded_spectrum` + from the whole lag space, exact on a complete periodic grid and an unbiased estimate with missing + cells, with the Blackman–Tukey estimate on bounded directions, tapers (`NoTaper`, `Bartlett`, + `GaussianTaper`) and missing-lag policies; `shell_average`, `shell_spectrum`. +- `helmholtz_spectra(L2, T2, k)` by `J₀`/`J₂`; on a sphere `isotropic_spectrum(sf, geometry, lmax)` and + `helmholtz_spectra(L2, T2, geometry, lmax; variance)` by Legendre and Wigner-d orthogonality. +- Third-order flux companions with their boundary terms: `spectral_flux` on `S3SFType`, `L3SFType` + (with `S3`) and `MixedSFType{1,0,2}`, and `enstrophy_flux` from the velocity's advective structure + function; the `J₁` route on cross-field moments. +- `covariance`, `covariance_matrix` with a positive-definiteness check. +- Regularised fits (issue #37): `SpectrumForwardModel`, `HelmholtzForwardModel`, `FluxForwardModel`; + `RegularizedLeastSquares(prior)` with a posterior covariance, `NonNegativeLeastSquares()`, + `SegmentedPowerLaw(S)` through the LsqFit extension; `fit_spectrum`, `fit_helmholtz_spectra`, + `fit_flux`, `tradeoff_curve`, `select_segments`, `independent_pair_variance`. + +### Exact laws + +- `KHM`: the four-fifths, four-thirds and Yaglom inversions and residuals, each on the moment it is + stated for, and the planar transverse incompressibility residual. ### Performance -- **ThreadedBackend / OhMyThreadsExt**: outer-loop chunks for O(N²) pair kernels now use - `OMT.RoundRobin()` instead of the default contiguous split. Fixes ~2× load imbalance - when `work(i) ∝ (N - i)` (structure-function and single-pass 2D paths). No API change. -- **AbstractBinEdges (O(1) Binning)**: Added high-performance bin edge wrappers (`LinearBinEdges`, `LogBinEdges`, `InfPaddedBinEdges`) to resolve $O(\log B)$ search bottlenecks in `digitize`. - - `LinearBinEdges` utilizes Fused Multiply-Add (FMA) CPU instructions and local ULP corrections to achieve 15x+ speedup on uniform grids. - - `LogBinEdges` extracts the binary floating-point exponent (IEEE 754 bitwise manipulation) and uses a precomputed lookup table to restrict the search range, bypassing the highly latent `log(x)` CPU instruction for a 5x+ speedup on logarithmic grids. - - `InfPaddedBinEdges` provides virtual infinity padding without array copying or memory allocation. +- `LinearBinEdges`, `LogBinEdges`, `InfPaddedBinEdges`: `O(1)` digitizing by fused multiply-add and + exponent lookup; squared-distance digitize plans on every pair loop. +- Cell culling (`AutoCulling`, `AlwaysCulling`, `NoCulling`) with blocked pair sweeps; the answer never + moves, the cost falls with the cutoff. +- Round-robin outer chunks on the threaded pair loops; SIMD compute/scatter split in the point kernels. +- The direct lag sweep and the transform's lag loop allocate nothing per pair or per lag. +- The device transform builds each monomial for every slab in one broadcast and transforms the slabs + in one batch, and writes the spectra in the order the binning stage reads them, so assembling its + input is a reshape. On an A100 the 720×360 lat-lon `L2` transform runs 28× the 8-thread CPU and a + stretched 256×128 grid 3.6×. +- The device binning kernel launches each slab pair over its own lag box, which a schedule reports + through `uniform_lag_box`. On a sphere the box over all row pairs does not narrow with the largest + bin edge while each row pair's does, so the kernel speeds up as the sweep narrows: 2× at a quarter + of the sphere's radius, 3× at an eighth. + +### Removed + +- The empty CairoMakie extension. The `UnsafeUserTransverseBasis`/`UserTransverseBasis` closure + wrappers and `CoordinateGaugeTransverseBasis` (an even rule, ill-defined on unordered pairs); a + custom convention is a subtype of `AbstractTransverseBasisConvention` with one `transverse_basis` + method. ## [0.3.0] - 2026-03-18 diff --git a/Project.toml b/Project.toml index a64e4eb..eba8fc4 100644 --- a/Project.toml +++ b/Project.toml @@ -12,53 +12,66 @@ Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca" +SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" [weakdeps] AbstractFFTs = "621f4979-c628-5d54-868e-fcf4e3e8185c" Bessels = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" -CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" +FINUFFT = "d8beea63-0952-562e-9c6a-8e8ef7364055" FlowGeometries = "0ccd6995-f618-4175-b01e-f437d0cb4974" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +LsqFit = "2fda8390-95c7-5789-9bda-21331edee243" MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" +NUFSHT = "e99b67a3-9706-455a-90e2-85b195a33206" +NonuniformFFTs = "cd96f58b-6017-4a02-bb9e-f4d81626177f" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" -SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" [extensions] StructureFunctionsCUDAExt = ["KernelAbstractions", "CUDA"] StructureFunctionsBesselsExt = ["Bessels"] -StructureFunctionsFFTExt = ["AbstractFFTs", "SpectralBackends"] -StructureFunctionsSpectralBackendsExt = ["SpectralBackends"] +StructureFunctionsLsqFitExt = ["LsqFit"] +StructureFunctionsAbstractFFTsExt = ["AbstractFFTs"] StructureFunctionsFlowGeometriesExt = ["FlowGeometries"] -StructureFunctionsCairoMakieExt = ["CairoMakie"] StructureFunctionsKernelAbstractionsExt = ["KernelAbstractions"] StructureFunctionsOhMyThreadsExt = ["OhMyThreads"] StructureFunctionsDistributedExt = ["Distributed"] StructureFunctionsMPIExt = ["MPI"] +StructureFunctionsNUFSHTExt = ["NUFSHT"] +StructureFunctionsAbstractFFTsKernelAbstractionsExt = ["AbstractFFTs", "KernelAbstractions"] +StructureFunctionsNonuniformFFTsExt = ["NonuniformFFTs"] +StructureFunctionsNonuniformFFTsKernelAbstractionsExt = ["NonuniformFFTs", "KernelAbstractions"] +StructureFunctionsFINUFFTExt = ["FINUFFT"] +StructureFunctionsFINUFFTKernelAbstractionsExt = ["FINUFFT", "KernelAbstractions"] + [extras] FlowGeometries = "0ccd6995-f618-4175-b01e-f437d0cb4974" -SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" +NUFSHT = "e99b67a3-9706-455a-90e2-85b195a33206" [sources] ComputationalBackends = { url = "https://github.com/jbphyswx/ComputationalBackends.jl" } FlowGeometries = { url = "https://github.com/jbphyswx/FlowGeometries.jl" } +NUFSHT = { url = "https://github.com/jbphyswx/NUFSHT.jl" } SpectralBackends = { url = "https://github.com/jbphyswx/SpectralBackends.jl" } [compat] AbstractFFTs = "1" Bessels = "0.2" CUDA = "5, 6" -CairoMakie = "0.15" ComputationalBackends = "0.1" Distances = "0.10" Distributed = "1.11" +FINUFFT = "3.5" FlowGeometries = "0.1" KernelAbstractions = "0.9" LinearAlgebra = "1.11" +LsqFit = "0.15, 0.16" MPI = "0.20" +NUFSHT = "0.1" +NonuniformFFTs = "0.9" OhMyThreads = "0.8" PrecompileTools = "1.3.3" ProgressMeter = "1.9" diff --git a/README.md b/README.md index 29be43b..d7b8401 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# StructureFunctions.jl v0.4.0 +# StructureFunctions.jl [![Docs (stable)][docs-stable-img]][docs-stable-url] [![Docs (dev)][docs-dev-img]][docs-dev-url] [![DOI][zenodo-img]][zenodo-latest-url] @@ -9,674 +9,284 @@ [zenodo-img]: https://zenodo.org/badge/734119226.svg [zenodo-latest-url]: https://doi.org/10.5281/zenodo.14945669 -**High-performance structure function calculations for turbulence and spatial correlation analysis.** +**Structure functions of turbulent and spatially varying fields, on point lists, multi-fields, grids +and the sphere, with the spectra, fluxes and fits derived from them.** -StructureFunctions.jl computes structure functions (SFs) from scattered data, characterizing spatial correlations and scaling properties of turbulent/spatially-varying fields. Optimized for multi-dimensional data with typed backends supporting serial, threaded, distributed, and GPU execution. +A structure function is the pair average of a polynomial in the increment `δu = u(x + r) − u(x)`, +binned in the separation `|r|`. This package computes them at any order, for longitudinal and +transverse projections, scalars, mixed and cross-field moments, and the moment tensor. -## Table of Contents +- [Documentation](https://jbphyswx.github.io/StructureFunctions.jl/dev/) — theory, walkthrough, + architecture, backends, GPU, extensions, validation, API. +- Julia 1.12 or later. -- [Features](#features) -- [Quick Start](#quick-start) -- [Architecture](#architecture) -- [Backends](#backends) -- [API Reference](#api-reference) -- [Theory & References](#theory--references) -- [Performance](#performance) -- [Extensions](#extensions) -- [Migration from v0.2](#migration-from-v02) -- [Examples](#examples) - -## Features - -- **Structure Functions**: 1st, 2nd, 3rd order; longitudinal & transverse projections in 1D, 2D, 3D -- **In-place Mutating API**: Pre-allocated mutating functions (`calculate_structure_function!`) for zero-allocation loops (O(n_threads) multi-threaded chunked allocations) -- **2D Joint-Probability Binning**: Natively accumulates both exact sums and contribution counts across distance and structure function value increment bins (`StructureFunction2DSumsAndCounts`) -- **Typed Backend System**: Serial, Threaded, Distributed, GPU, Auto — choose your parallelization strategy -- **Type-Stable Dispatch**: No runtime overhead from symbolic dispatch; all paths validated with JET -- **Extensible Architecture**: Optional extensions for parallelization and GPU acceleration -- **Production Ready**: Comprehensive test coverage, numerical validation, performance benchmarking -- **Modern Julia**: Julia 1.12+ with qualified imports and explicit type annotations - -## Quick Start - -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -# 2D data: 3 points -x = ([0.0, 1.0, 2.0], [0.0, 0.0, 0.0]) -u = ([1.0, 1.1, 1.2], [0.0, 0.05, 0.1]) - -# Distance bins (physical units) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] - -# Calculate 2nd-order longitudinal SF -sf_type = SFT.LongitudinalSecondOrderStructureFunctionType() -result = SFC.calculate_structure_function(sf_type, x, u, bins) - -# result.values contains the SF values for each bin -println("SF values: ", result.values) - -# Speed it up with threading (if available) -using Base.Threads -if nthreads() > 1 - result_threaded = SFC.calculate_structure_function( - sf_type, x, u, bins; - backend=CB.ThreadedBackend() - ) -end -``` - -### Pre-allocated In-place Calculation - -For high-performance loops (e.g. over timesteps), you can pre-allocate memory buffers and run mutating calculations with zero heap allocation: - -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -x = ([0.0, 1.0, 2.0], [0.0, 0.0, 0.0]) -u = ([1.0, 1.1, 1.2], [0.0, 0.05, 0.1]) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] -sf_type = SFT.L2SFType() - -# Pre-allocate output arrays -n_bins = length(bins) -sums = zeros(Float64, n_bins) -counts = zeros(Float64, n_bins) - -# Compute in-place (accumulates into provided buffers) -SFC.calculate_structure_function!(sums, counts, sf_type, x, u, bins; backend=CB.ThreadedBackend()) - -# Obtain structure function values via division -sf_values = sums ./ counts -``` - - -## Architecture - -### Operator Types ✕ Result Container Pattern - -The v0.3.0 API separates **operators** (structure function definitions) from **result containers** (computed outcomes): - -``` -AbstractStructureFunctionType (operators) - ├── LongitudinalSecondOrderStructureFunctionType - ├── TransverseSecondOrderStructureFunctionType - ├── LongitudinalThirdOrderStructureFunctionType - └── ... (3+ other variants) - -StructureFunction (result container) - ├── operator::AbstractStructureFunctionType - ├── distance_bins::AbstractVector - ├── values::AbstractVector - └── order::Int -``` - -This split ensures: -- Clear semantics: operators are **inputs**, containers are **outputs** -- Type stability: dispatch happens at compilation time -- Extensibility: custom operators and containers are easy to add - -### Backend Dispatch System - -``` -calculate_structure_function(sf_type, x, u, bins; backend=AutoBackend()) - ↓ -_dispatch_execution_backend(backend, ...) - ├── SerialBackend → serial_calculate_structure_function - ├── ThreadedBackend → threaded_calculate_structure_function (from OhMyThreadsExt) - ├── DistributedBackend → parallel_calculate_structure_function (from DistributedExt) - ├── GPUBackend(b) → gpu_calculate_structure_function (from GPUExt) - └── AutoBackend → (tries distributed → threaded → serial) -``` - -All code paths produce **numerically identical results** (validated by intensive test suite). - -## Backends - -### SerialBackend (Default Reference) - -Single-threaded CPU execution. Use when: -- Debugging or validating calculations -- Data is small -- Deterministic execution is required - -```julia -result = SFC.calculate_structure_function(sf_type, x, u, bins) # Defaults to Serial -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.SerialBackend()) -``` - -**Performance**: O(N²) pairwise distance/SF evaluations. -**Memory**: O(N + B) where N = points, B = distance bins. - -### ThreadedBackend (Multi-CPU) - -Multi-threaded execution using [OhMyThreads.jl](https://github.com/JuliaFolds2/OhMyThreads.jl). - -```julia -using Base.Threads - -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.ThreadedBackend()) -``` - -- **Prerequisites**: `Threads.nthreads() > 1`, OhMyThreads.jl loaded (extension auto-loads) -- **Thread-local reductions**: No locks or atomic operations; no `threadid()` buffer indexing -- **Outer-loop scheduling**: Round-robin partition of index `i` for O(N²) pair loops (balanced - when inner work per `i` is `(N - i)`; contiguous chunks would skew load ~× number of threads) -- **Speedup**: Near-linear at low thread count for large N; memory bandwidth limits scaling beyond - -### DistributedBackend (Multi-Process/Cluster) - -Multi-worker execution using [Distributed.jl](https://docs.julialang.org/en/v1/stdlib/Distributed/). - -```julia -using Distributed: addprocs - -addprocs(4) # Or specify SSH workers, etc. - -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.DistributedBackend()) -``` - -- **Prerequisites**: Workers launched via `addprocs()` or similar -- **Communication overhead**: One `@distributed` reduction loop -- **Ideal for**: Large datasets, compute clusters - -### GPUBackend (GPU Acceleration) - -GPU execution via [KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl). - -```julia -using KernelAbstractions as KA - -# NVIDIA GPU (after loading CUDA.jl) -using CUDA -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.GPUBackend(CUDA.CUDABackend())) - -# AMD GPU (after loading AMDGPU.jl) -using AMDGPU -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.GPUBackend(AMDGPU.ROCBackend())) - -# CPU backend for testing (no GPU required) -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.GPUBackend(KA.CPU())) -``` - -- **Ideal for**: Large datasets (few×10³+ points) where GPU memory is sufficient -- **Docs**: [`docs/src/gpu.md`](docs/src/gpu.md) — workspace, batch driver, testing tiers - -### AutoBackend (Recommended Default) - -Automatic selection based on environment: - -```julia -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=CB.AutoBackend()) - -# Selection order: -# 1. Distributed (if nworkers() > 1) -# 2. Threaded (if nthreads() > 1) -# 3. Serial (fallback) -``` - -## API Reference - -### Main Entry Points - -**1. Standard Allocating API:** - -```julia -calculate_structure_function(sf_type::AbstractStructureFunctionType, - x::Union{Tuple, Matrix}, - u::Union{Tuple, Matrix}, - distance_bins::AbstractVector{<:Tuple}; - backend=SerialBackend(), - output_type=StructureFunction, # or StructureFunctionSumsAndCounts for raw - distance_metric=Euclidean(), - verbose=true, - show_progress=true) → StructureFunction # (or StructureFunctionSumsAndCounts) -``` - -**2. 2D Joint-Probability Allocating API:** - -```julia -calculate_structure_function(sf_type::AbstractStructureFunctionType, - x::Union{Tuple, Matrix}, - u::Union{Tuple, Matrix}, - distance_bins::AbstractVector{<:Tuple}, - value_bins::AbstractVector; - backend=SerialBackend(), - distance_metric=Euclidean(), - verbose=true, - show_progress=true) → StructureFunction2DSumsAndCounts -``` - -**3. In-place Mutating API (Zero-Allocation):** - -```julia -calculate_structure_function!(sums::AbstractVector, - counts::AbstractVector, - sf_type::AbstractStructureFunctionType, - x::Union{Tuple, Matrix}, - u::Union{Tuple, Matrix}, - distance_bins::AbstractVector; - backend=SerialBackend(), - distance_metric=Euclidean(), - verbose=true, - show_progress=true) → Nothing -``` - -**4. 2D Joint-Probability Mutating API (Zero-Allocation):** - -```julia -calculate_structure_function!(sums_2d::AbstractMatrix, - counts_2d::AbstractMatrix, - sf_type::AbstractStructureFunctionType, - x::Union{Tuple, Matrix}, - u::Union{Tuple, Matrix}, - distance_bins::AbstractVector, - value_bins::AbstractVector; - backend=SerialBackend(), - distance_metric=Euclidean(), - verbose=true, - show_progress=true) → Nothing -``` - -*Note: The mutating APIs accumulate (`+=` and `.+=`) directly into the provided output buffers. The caller is responsible for pre-zeroing the arrays.* - -### Operator Types - -All inherit from `AbstractStructureFunctionType`. Instantiate with `()` or use shorthands: - -```julia -SFT.LongitudinalSecondOrderStructureFunctionType() # 2nd order, longitudinal -SFT.TransverseSecondOrderStructureFunctionType() # 2nd order, transverse -SFT.LongitudinalThirdOrderStructureFunctionType() # 3rd order, longitudinal -# ... shorthands: L2SFType, T2SFType, L3SFType, T3SFType, S2SFType, S3SFType -``` - -Each operator is **callable** (functors): -```julia -sf_op = SFT.L2SFType() -sf_op(du, rhat) # Computes L2SF increment value -``` - -### Result Containers - -**1. 1D Structure Function Container (`StructureFunction`):** +## Quick start ```julia -struct StructureFunction{FT, OT, BT, VT} <: AbstractStructureFunction - operator::OT # AbstractStructureFunctionType - distance_bins::BT # AbstractVector of (r_min, r_max) - values::VT # AbstractVector{FT} — computed SF - order::Int # 1, 2, 3, ... -end -``` +using Pkg; Pkg.add(url = "https://github.com/jbphyswx/StructureFunctions.jl.git") -**2. 2D Joint-Probability Container (`StructureFunction2DSumsAndCounts`):** +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, LogBinEdges +using ComputationalBackends: ComputationalBackends as CB -```julia -struct StructureFunction2DSumsAndCounts{FT, OT, BT, VT, MT, CT} <: AbstractStructureFunction - operator::OT # AbstractStructureFunctionType - distance_bins::BT # AbstractVector of distance bin edges - value_bins::VT # AbstractVector of value bin edges - sums::MT # AbstractMatrix{FT} (distance x value) - counts::CT # AbstractMatrix (distance x value) -end -``` +x = rand(2, 4096) .* 1.0e4 # (D, N) coordinates +u = randn(2, 4096) # (D, N) velocity components +bins = LogBinEdges(collect(exp10.(range(log10(50.0), log10(5.0e3); length = 41)))) -**Access results**: -```julia -# 1D -result.values # SF values, one per bin -result.distance_bins # Original input bins +sf = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins) # ⟨δu_L²⟩ per bin, AutoBackend +sf.values # NaN where a bin holds no pair +raw = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; output_type = SFC.StructureFunctionObjects.StructureFunctionSumsAndCounts) +raw.sums, raw.counts # the accumulator, adds across processes and time -# 2D -result_2d.sums # Sum of SF values in each 2D cell -result_2d.counts # Count of point pairs in each 2D cell +res = SFC.calculate_structure_functions_single_pass(x, u, bins) # S2, L2, T2, S3, L3, L1T2 and the Helmholtz split in one pass +joint = SFC.calculate_structure_function(SFT.L3SFType(), x, u, bins, range(-3.0, 3.0; length = 61)) # distance × value histogram ``` -### Fast Bin Edges (`AbstractBinEdges`) - -For large datasets ($N \ge 2000$), looking up the correct distance bin for each of the $O(N^2)$ point pairs can become a major CPU bottleneck (occupying over 50% of total runtime with standard arrays/ranges due to binary search overhead and cache misses). - -StructureFunctions.jl provides optimized, zero-allocation custom collections subtyping `AbstractBinEdges{T}` to bypass binary search and achieve $O(1)$-like lookup speeds: - -* **`LinearBinEdges(edges::AbstractRange)`**: Wraps uniformly-spaced ranges. Bypasses the Twice-Precision calculations in standard ranges, performing searches in **~3 ns** (a **15x+ speedup**) using Fused Multiply-Add (FMA) instructions and ULP corrections. -* **`LogBinEdges(edges::AbstractVector)`**: Wraps log-spaced (geometric) ranges. Bypasses hardware `log(x)` latency by extracting the binary float exponent to perform octal Lookup Table (LUT) queries in **~5-8 ns** (a **5x+ speedup**). -* **`InfPaddedBinEdges(edges::AbstractBinEdges)`**: Wraps any custom bin edges collection to implicitly prepend $-\infty$ (or `typemin(T)`) and append $+\infty$ (or `typemax(T)`). -* **`BinEdges(edges::AbstractVector)`**: General fallback wrapper that automatically routes to `LinearBinEdges` for ranges or wraps vectors. - -#### Usage Example - -To enable O(1) binning in single-pass calculations, wrap your raw bin vector before calling the calculation: +Threads: start Julia with `-t N` and `using OhMyThreads`. A GPU: `using KernelAbstractions, CUDA` and +`backend = CB.GPUBackend(CUDA.CUDABackend())`. A grid: `using FlowGeometries, FFTW` and pass the grid +and a spectral tag (below). The optional routes live in package extensions, listed under +[Extensions](#extensions). + +## What it computes + +**Operators.** Each is callable on a pair as `sf(δu, r̂)` and is accumulated by every route: + +| operator | value on a pair | shorthand | +|---|---|---| +| `SecondOrderStructureFunctionType` | `‖δu‖²` | `S2SFType` | +| `ProjectedStructureFunctionType{NL, NT}(basis)` | `δu_L^NL · δu_T^NT` — `δu_L = δu·r̂`; `NT = 2` the transverse energy `‖δu‖² − δu_L²`, any other `NT` the signed component along the convention's transverse direction | `L2SFType` `{2,0}`, `T2SFType` `{0,2}`, `L3SFType` `{3,0}`, `L1T2SFType` `{1,2}`, `L2T1SFType` `{2,1}`, `T3SFType` `{0,3}` | +| `ThirdOrderStructureFunctionType` | `δu_L ‖δu‖²` | `S3SFType` | +| `FullVectorStructureFunctionType{NF}` | `‖δu‖^NF` | | +| `ScalarStructureFunctionType{P}(field)` | `(δθ)^P` | `ScalarSFType` | +| `MixedStructureFunctionType{NL, NT, P}` | `δu_L^NL ‖δu_T‖^NT (δθ)^P` — `{1,0,2}` is Yaglom's moment | `MixedSFType` | +| `VectorDotStructureFunctionType(a, b)`, `ScalarDotStructureFunctionType(a, b)` | `δu⁽ᵃ⁾·δu⁽ᵇ⁾`, `δθ⁽ᵃ⁾ δθ⁽ᵇ⁾` — the advective moments the flux relations take | `VectorDotSFType`, `ScalarDotSFType` | +| `MomentTensorOperator{P}` | the tensor `δu_{i₁} ⋯ δu_{i_P}` | | + +The transverse convention travels with the operator (`CanonicalTransverseBasis()` by default, +`ReferenceAxisTransverseBasis(a)` about an axis), and operators odd in a scalar increment read every +pair in its canonical orientation, so nothing depends on the order of the input. + +**Inputs** + +- Point lists `x::(D, N)`, `u::(D, N)`; batches `u::(D, N, aux...)` with shared or varying positions. +- Multi-fields `MultiFields.Fields(vectors = (u, 𝓐u), scalars = (θ,))`, swept together in one pass. +- Grids from [FlowGeometries.jl](https://github.com/jbphyswx/FlowGeometries.jl): uniform, stretched + (any number of uniform axes) and lat-lon grids, with masks (`NaN`s or a `Bool` mask) at every order. +- The sphere: `SphericalDistance(R)` (or `Distances.Haversine`, `Distances.SphericalAngle`) puts each + pair in its geodesic frame; `x` is `(lon, lat)` and `u` may carry a radial component. +- Pair weights, one per point or cell (`cell_measure(grid)` for areas). + +**Routes** + +| data | route | exact? | +|---|---|---| +| point list, any geometry | blocked pair loop with cell culling, on every backend | yes | +| one-dimensional point list | sorted route, prefix sums of monomials, `O(N log N + N n_bins)` | yes | +| grid with ≥ 1 uniform axis | direct lag sweep, or the transform engine: each polynomial operator at each lag as cross-correlations of masked monomials, on the CPU or a device | yes | +| lat-lon grid | the same, with the geodesic frame per lag (pole-invariant) | yes | +| sphere, any point set | the harmonic route: pseudo-spectral series with Legendre / Wigner-d kernels (`HarmonicNodes`) | kernel-binned, exact for a band-limited field on a quadrature grid | +| scattered points, large | non-uniform FFT onto a mode grid (`ScatteredModesSchedule`) | no: soft-binned, converges with the mode count | + +**Outputs beyond the histogram** + +- Joint histograms in (distance × value) and (distance × angle); moment tensors of any rank on points + and grids; the six isotropic invariants and the Helmholtz rotational/divergent split in one pass. +- Spectra: `isotropic_spectrum` in 1-, 2- and 3-D; `gridded_spectrum` exactly through the lag space + (and an unbiased estimate with cells missing); `helmholtz_spectra` (`E`/`B`) by `J₀`/`J₂`; on the + sphere `C_l`, `C^E_l`, `C^B_l`. +- Fluxes: `spectral_flux` from the advective moment (`J₁`) and from `S3`, `L3` with their boundary + terms; `enstrophy_flux`. +- Fits (issue #37): `fit_spectrum`, `fit_helmholtz_spectra`, `fit_flux` through + `SpectrumForwardModel`, `HelmholtzForwardModel`, `FluxForwardModel` with `RegularizedLeastSquares` + (posterior covariance), `NonNegativeLeastSquares` or a `SegmentedPowerLaw`; `tradeoff_curve`, + `select_segments`, `independent_pair_variance`. +- Exact laws: `KHM.epsilon_from_four_fifths`, `epsilon_from_four_thirds`, `epsilon_theta_from_yaglom`. + +## A grid, by transform ```julia -using StructureFunctions: Calculations as SFC -using StructureFunctions: LogBinEdges - -# Generate log-spaced boundaries -log_bins_raw = collect(exp.(range(log(0.01), log(10.0), length=51))) - -# Wrap them in LogBinEdges to activate O(1) Exponent LUT Hybrid Search -distance_bins = LogBinEdges(log_bins_raw) - -# Run calculation (bypasses standard binary search bottleneck completely). -# Returns a NamedTuple keyed by invariant: results.S2, results.L2, results.T2, -# results.S3, results.L3, results.L1T2 (+ results.helmholtz for point-field input). -# Each entry is a StructureFunction (pass output_type=StructureFunctionSumsAndCounts for raw). -results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.SerialBackend()) +using FlowGeometries: FlowGeometries as FG +using SpectralBackends: SpectralBackends as SB +using FFTW + +n_lon, n_lat = 1440, 720 +grid = FG.Grids.StructuredGrid(FG.Geometry.SphericalGeometry(6.371e6), + range(0.0, step = 2π / n_lon, length = n_lon), + range(-π / 2 + π / (2n_lat), π / 2 - π / (2n_lat); length = n_lat)) +u = randn(2, n_lon, n_lat) # (east, north) at every cell +bins = 6.371e6 .* collect(range(0.0, π; length = 41)) # metres, like the radius + +sf = calculate_structure_function(SFT.L3SFType(), grid, u, bins, UInt64, + SB.FastFourierTransformSpectralBackend(); backend = CB.ThreadedBackend()) ``` -## Theory & References - -Structure functions quantify spatial correlations of a field **u** at separation distance **r**: - -$$S_p(r) = \langle |u(\mathbf{x} + \mathbf{r}) - u(\mathbf{x})|^p \rangle$$ - -where $\langle \cdot \rangle$ is ensemble/spatial average over all displacement vectors $\mathbf{r}$. - -### Dimensional Variants - -- **1D**: Single coordinate axis (e.g., time series) -- **2D**: Horizontal plane (e.g., satellite imagery) -- **3D**: Full spatial field (e.g., atmospheric snapshots) - -### Order Variants - -- **1st order** ($p=1$): Absolute increment -- **2nd order** ($p=2$): Energy-like; related to kinetic energy spectrum by Wiener-Khinchin -- **3rd order** ($p=3$): Skewness; tests Kolmogorov refined similarity hypotheses - -### References - -1. **Kolmogorov (1941)**: _The Local Structure of Turbulence in Incompressible Viscous Fluid for Very Large Reynolds Numbers_ - - Foundational theory; predicts $S_2(r) \sim r^{2/3}$ in inertial range +That bins `5.4 × 10¹¹` pairs in about ten seconds on eight cores; the direct sweep of the same grid +takes 60× longer and returns the same counts. The same call with `backend = CB.GPUBackend(...)` runs +the engine on a device. -2. **Balwada et al. (2016)**: _Scale-aware analysis of satellite sea surface temperature variability_ - - Applied SF analysis to geophysical gridded data; demonstrates multi-scale recovery - -3. **Wikipedia**: [Turbulence](https://en.wikipedia.org/wiki/Turbulence#Kolmogorov's_theory_of_1941) - - Accessible overview of Kolmogorov theory +## Extensions -**See also**: [`docs/src/theory.md`](docs/src/theory.md) for detailed mathematical formulations and dimensional projections. +| load | adds | +|---|---| +| `OhMyThreads` | `ThreadedBackend()` | +| `Distributed`, `MPI` | `DistributedBackend()`, the MPI backend | +| `KernelAbstractions` (+ `CUDA`) | `GPUBackend(device)` on every device route | +| an `AbstractFFTs` package (`FFTW`) | the transform engine; + `KernelAbstractions` for the device engine | +| `FlowGeometries` | the grid entries and `cell_measure` | +| `Bessels` | the 2-D kernel, the flux relations, the Helmholtz spectra and forward models | +| `NUFSHT` | the fast harmonic route on the sphere | +| `NonuniformFFTs`, `FINUFFT` | the soft-binned scattered-points route, one provider tag each (`NonuniformFFTsSpectralBackend`, `FINUFFTSpectralBackend`) | +| `LsqFit` | the segmented power-law fit | -## Example Figures +The algorithm tags (`AutoSpectralBackend()`, `FastFourierTransformSpectralBackend()`, …) come from +`SpectralBackends`, a dependency. -### 2nd-Order Structure Function — Kolmogorov Scaling +## Figures ![Structure Function S2](docs/src/assets/sf_kolmogorov.png) -*2nd-order longitudinal structure function on a 2D turbulent field. Dashed line: K41 prediction S₂(r) ~ r^(2/3).* - -### Longitudinal vs Transverse Structure Functions +*2nd-order longitudinal structure function on a 2-D turbulent field; dashed: K41 `S₂ ~ r^(2/3)`.* ![Longitudinal vs Transverse](docs/src/assets/sf_long_vs_trans.png) -*Comparison of longitudinal (L2SF) and transverse (T2SF) 2nd-order structure functions on the same field.* - -### Single-Pass Invariants + Helmholtz Decomposition +*Longitudinal (`L2SF`) and transverse (`T2SF`) second-order structure functions of one field.* ![Single-pass invariants and Helmholtz](docs/src/assets/sf_single_pass.png) -*All six isotropic invariants (S2, L2, T2, S3, L3, L1T2) plus the rotational/divergent Helmholtz decomposition — computed in **one** O(N²) pair pass via `calculate_structure_functions_single_pass`.* - -### 2D Joint-Probability Binning — all invariants, with vs without a cascade +*The six isotropic invariants and the Helmholtz decomposition, from one pair pass.* ![2D joint-probability binning](docs/src/assets/sf_2d_binning.png) -*Conditional PDFs `P(value | r)` for all six single-pass invariants (one `calculate_structure_functions_single_pass_2d` call per field), comparing a symmetric random field (top) with a shock/forward-cascade field (bottom). 2nd-order PDFs broaden with separation in both; the **signed 3rd-order** panels (zero line + orange conditional-mean `⟨value|r⟩`) are symmetric for the random field but **skew negative for the cascade field** — the 4/5-law / energy-flux sign. White = low, gray = empty bins.* - -### Backend Parity Validation +*Conditional PDFs `P(value | r)` of the six invariants, for a symmetric random field (top) and a +forward-cascade field (bottom). The signed third-order panels skew negative only for the cascade.* ![Backend Parity](docs/src/assets/sf_backend_parity.png) -*Serial vs Threaded backend results on identical data — differences are at floating-point rounding level.* - -### Canonical Spectra — from a structure function to E(k) +*Serial against threaded on identical data: differences at floating-point rounding.* ![Spectra from structure functions](docs/src/assets/sf_spectra.png) -*Left: a field built with a prescribed `E(k) ~ k^(-5/3)` spectrum, binned into `S₂` and transformed back with `gridded_spectrum` + `shell_average` — the recovered spectrum carries the slope it was built with across 1.5 decades. Right: the isotropic transform against a closed form. A Gaussian correlation has an analytic spectral density in every dimension, and the transform reproduces it to `6.6e-05`, `2.3e-09` and `9.9e-14` in 1-D, 2-D and 3-D — one comparison that pins the kernel, the solid angle, the `(2π)^D` normalisation and the sign together. The rise at large `k` is the quadrature noise floor, ten or more orders below the peak.* - -### Spectra Survive Missing Data — the reason to go through a structure function +*Left: a field built with `E(k) ~ k^(-5/3)`, binned into `S₂` and transformed back with +`gridded_spectrum` + `shell_average`. Right: the isotropic transform against a closed-form Gaussian +density in 1-, 2- and 3-D, to `6.6e-05`, `2.3e-09` and `9.9e-14`.* ![Spectrum with missing data](docs/src/assets/sf_missing_data.png) -*With cells absent, a field's own transform is meaningless while the structure function is still an unbiased average over surviving pairs. At **half the grid missing**, the spectrum recovered through `S₂` is within a few percent of the complete-field answer; zero-filling the gaps and transforming directly is off by ~80%.* - -### Directional Output — S(r, θ) +*With half the grid missing, the spectrum recovered through `S₂` is within a few percent of the +complete-field answer. Zero-filling the gaps and transforming directly is off by about 80 %.* ![Directional structure functions](docs/src/assets/sf_directional.png) -*The second histogram axis can bin the angle between the separation and a reference direction instead of the operator's value, turning `S(r)` into `S(r, θ)` through the same kernel family. Here a field varying along `x` only: separations perpendicular to the variation carry an identically zero increment, and the angular profile touches zero at exactly `θ = π/2`.* - -### Helmholtz Split, in Separation and in Wavenumber +*The second histogram axis can bin the angle to a reference direction: `S(r, θ)` from the same kernel.* ![Helmholtz spectra](docs/src/assets/sf_helmholtz_spectra.png) -*Left: the rotational/divergent decomposition of a solenoidal field, whose divergent part is zero by construction. Right: the same components transformed to `E_rot(k)` and `E_div(k)` via `helmholtz_spectra`, for a solenoidal and an irrotational field. Because `D_rot + D_div = D_LL + D_TT` exactly and the transform is linear, the two spectra sum to the spectrum of the trace whatever the field is.* - -### Scalars and Multi-Channel Fields - -![Scalar and mixed structure functions](docs/src/assets/sf_channels.png) +*The rotational and divergent split, in separation and in wavenumber. The two spectra sum to the +trace's exactly, because `D_rot + D_div = D_LL + D_TT` and the transform is linear.* -*A `Fields(vectors = (u,), scalars = (θ,))` bundle computes velocity, tracer and mixed moments in one pair pass. Right: `⟨δu_L (δθ)²⟩`, the mixed moment Yaglom's law inverts for the scalar-variance dissipation.* +![Scalar and mixed structure functions](docs/src/assets/sf_fields.png) -### Gridded Fast Paths — the transform against the lag sweep +*A `Fields(vectors = (u,), scalars = (θ,))` multi-field: velocity, tracer and mixed moments in one pass; +right, Yaglom's `⟨δu_L (δθ)²⟩`.* ![Transform vs lag sweep](docs/src/assets/sf_gridded_algorithms.png) -*Two exact algorithms for one definition. Left: they agree to double-precision round-off on the same data — the lag sweep visits each lag and reduces over cells, while the transform never forms a lag until after the inverse transform, so a defect in either shows up immediately. Right: what each costs. The sweep is `O(n_lags · cells)` and the transform `O(cells log cells)` however many lags are wanted, so the gap widens with grid size; `AutoSpectralBackend()` costs both and picks the cheaper, which at small cutoffs is the sweep.* - -### Advective Structure Functions and Spectral Flux (Bessel methods) +*Two exact algorithms for one definition agree to round-off. The transform's cost does not grow with +the number of lags.* ![Advective structure function and flux](docs/src/assets/sf_advective_flux.png) -*Left: `⟨δu · δ𝓐ᵤ⟩` for a 2-D field, with the spectral flux `Π(K) = −(K/2)∫ SF_A J₁(Kr) dr` overlaid — the relation holds **without assuming isotropy**, which is what these estimators are for. Right: the flux kernel against a closed form. Since `∫₀^R J₁(Kr)dr = (1 − J₀(KR))/K`, a constant advective structure function must give exactly `−(c/2)(1 − J₀(KR))`, settling on `−c/2`. That pins the kernel and the prefactor with nothing fitted — which matters, because a flux wrong by a constant or a sign still looks like a cascade.* - -### The Third-Order Exact Laws +*`⟨δu · δ𝓐ᵤ⟩` with the flux `Π(K) = −(K/2)∫ SF_A J₁(Kr) dr`, and the kernel against its closed form: +a constant advective structure function gives exactly `−(c/2)(1 − J₀(KR))`.* ![Exact laws](docs/src/assets/sf_exact_laws.png) -*Left: each law inverts the moment it is stated for — 4/5 from `⟨δu_L³⟩`, 4/3 from `⟨δu_L‖δu‖²⟩`, Yaglom from `⟨δu_L(δθ)²⟩` — each recovering its prescribed constant flat in `r`. The red line is the trap the API guards against: applying the four-fifths law to the scalar moment is wrong by exactly 5/3. Right: third-order moments carry the cascade's sign. A random-phase field has vanishing odd moments; a ramp-cliff (shock) field is strongly negatively skewed at small separations — the forward-cascade sign the 4/5 law encodes.* - -### Spherical Geometry — parallel transport, and the lat-lon fast path +*Left: each law recovers the constant it prescribes, flat in `r`, from the moment it is stated for. +The red line applies the four-fifths law to `S3SF`, which overstates `ε` by 5/3. Right: a +random-phase field has vanishing odd moments, a ramp-cliff field is negatively skewed at small +separations.* ![Spherical geometry](docs/src/assets/sf_spherical.png) -*Left: solid-body rotation on a sphere has an identically zero longitudinal increment at every separation and latitude. Computed in the geodesic frame the ratio sits at machine zero (floored at 1e-30 for the log axis); treating lon/lat as a plane instead puts ~90 % of the energy into a quantity whose true value is zero — a **30-order** separation, and the reason the package transports increments rather than differencing raw coordinates. Right: on a lat-lon grid the geodesic frame is zonally invariant, so the geometry is computed once per (latitude pair, longitude offset) instead of once per pair — **147× faster** than the unstructured pair loop here, with **pair counts exactly equal**.* - -### Culling — cost falls with the cutoff, the answer never moves +*Solid-body rotation has no strain, so the geodesic frame gives `D_LL` at machine zero while a flat +lon/lat frame puts most of the energy into it. Right: the zonal route on a lat-lon grid.* ![Culling](docs/src/assets/sf_culling.png) -*When the largest bin edge bounds the separations of interest, pairs beyond it need never be enumerated. Speedups from 1.4× to **55×** as `r_max` tightens, at N = 20 000 — and the pair counts are **identical to the uncalled sweep at every cutoff**, because culling changes which pairs are visited, not which pairs count. `AutoCulling()` is the default and declines where it cannot be exact.* - -### Covariance from a Structure Function +*The cost falls with the cutoff; the pair counts are identical at every cutoff.* ![Covariance](docs/src/assets/sf_covariance.png) -*Left: a structure function is twice a variogram, so `C(r) = C(0) − D(r)/2` recovers the covariance exactly — given the variance, which `D(r)` is blind to and which must be supplied. Right: a covariance matrix must be positive semi-definite, and **interpolating a positive-definite kernel does not preserve that**. The error falls as the square of the sampling spacing, so an under-resolved covariance cannot support a valid matrix; `covariance_matrix` checks rather than assumes, and its message distinguishes "sampled too coarsely" from "not a kernel at all".* +*`C(r) = C(0) − D(r)/2` given the variance. The covariance matrix is tested for positive +semi-definiteness; an under-resolved sampling cannot support a valid one.* -*Regenerate the eleven figures above: `julia --project=docs/generate_assets docs/generate_assets/generate_feature_figures.jl`.* +![Pair weights](docs/src/assets/sf_weights.png) ---- +*A lat-lon cell shrinks toward the poles, so `weights = cell_measure(grid)` turns the pair average +into an area average; every lag route and point entry takes the keyword.* -## Performance +![Exact sorted route on a line](docs/src/assets/sf_sorted_line.png) -### Scaling Characteristics +*One-dimensional point lists take an exact route built on prefix sums of the monomials, so the cost +stops scaling with the pair count. It returns the pair loop's answer. A norm power is not a +polynomial and keeps the loop.* -| Dimension | Metric | Value | -|-----------|--------|-------| -| N points | Algorithm | O(N²) | -| B bins | Space | O(N + B) | -| D dim's | CPU ops | ~D² per pair | -| Threads | Speedup | ~0.8–0.9× per thread (dims ≤ 3) | +![Moment tensors](docs/src/assets/sf_tensor.png) -### Benchmark Figures (v0.3.0, Julia 1.12) +*The transform already forms each lag's symmetric moment store, so the tensor costs no more than the +scalar. Its components hold the anisotropy the trace averages away, and that trace is the scalar +second-order entry.* -> **Hardware:** 2× Intel Xeon Gold 6426Y (16 cores / 32 threads each, 64 logical CPUs total). -> Benchmarks were run on this machine. Results on other hardware will differ. -> To regenerate with your own hardware, see [`benchmark/benchmark_scaling.jl`](benchmark/benchmark_scaling.jl). -> Output figures land in `benchmark/benchmark_results/` (gitignored). +![Scattered points through a non-uniform FFT](docs/src/assets/sf_scattered_modes.png) -#### CPU strong scaling — fixed N, increasing threads +*`ScatteredModesSchedule` puts scattered points on a mode grid, so the pair statistic comes back with +the truncated kernel in place of a hard bin. The result carries `ModeBinEdges`. It is not exact at any +finite mode count and converges as the mode count grows; it is selected only by passing the tag.* -![CPU strong scaling](docs/src/assets/strong_scaling.png) +![Fitting instead of inverting](docs/src/assets/sf_fits.png) -*Fixed problem size (N = 4000 points, 3D, longitudinal 2nd-order SF). Speedup approaches linear up to ~4 threads; NUMA effects reduce efficiency beyond 8 threads on a dual-socket system. Generated by [`benchmark/benchmark_scaling.jl`](benchmark/benchmark_scaling.jl).* +*A spectrum from `S₂` by a bounded segmented power law, and a spectral flux from `S₃`. These are +estimators with stated priors, beside the exact transforms they approximate: without a prior the +inversion is singular below `π/r_max`, which is what the regularisation is for.* -#### CPU weak scaling — N ∝ √p, constant work per thread +*Regenerate the sixteen feature figures with `julia --project=docs/generate_assets +docs/generate_assets/generate_feature_figures.jl`, and the six above them with +`generate_assets.jl` in the same environment.* -![CPU weak scaling](docs/src/assets/weak_scaling.png) - -*Problem size grows as N = N_base × √p so each thread has constant O(N²/p) pair work. Ideal wall-clock time is flat; observed rise reflects inter-socket memory traffic.* - -#### GPU problem-size scaling — 1 GPU vs CPU (vary N) +### Scaling +![CPU strong scaling](docs/src/assets/strong_scaling.png) +![CPU weak scaling](docs/src/assets/weak_scaling.png) ![GPU problem-size scaling](docs/src/assets/gpu_problem_size_scaling.png) - -*Fixed hardware (**1 GPU + serial CPU**, always 1 worker), sweep N. **Not** HPC strong/weak scaling. CPU threading is in the strong/weak figures above. Regenerate: [`gpu/collect_benchmark_assets.jl`](gpu/collect_benchmark_assets.jl), then [`generate_gpu_figures.jl`](docs/generate_assets/generate_gpu_figures.jl).* - -#### GPU batch scaling — fixed N, vary T (time slices) - ![GPU batch scaling](docs/src/assets/gpu_slice_batch_scaling.png) - -*Fixed `N_SLICE` (default 1000), sweep T. CPU per-slice loop vs GPU naive loop vs GPU batch driver (`*_batch!`) on **1 GPU**. Not HPC weak scaling.* - -#### GPU kernel parity (KA.CPU vs serial) - ![GPU Parity](docs/src/assets/sf_gpu_parity.png) -*Serial CPU reference vs `gpu_calculate_structure_function` on `KA.CPU()` — proves kernel logic in default CI; does not test CUDA.* - -### Optimization Tips - -1. **Use AutoBackend** for deployment (automatic tuning) -2. **Prefer larger datasets** for threading overhead to amortize -3. **Pre-sort bins** by distance to improve cache locality -4. **Use Float32** if precision allows (faster GPU transfers) -5. **Batch multiple SFs** by reusing distance calculations - -## Extensions - -Optional packages extend StructureFunctions with additional functionality: - -### OhMyThreadsExt (ThreadedBackend) - -Loaded automatically when `OhMyThreads.jl` is in `Project.toml`: - -```toml -[extras] -OhMyThreads = "67456a42-ebe4-4781-8ad1-67f7eda8d8f7" - -[extensions] -StructureFunctionsOhMyThreadsExt = "OhMyThreads" -``` - -### DistributedExt (DistributedBackend) - -Requires `Distributed.jl` (stdlib): - -```julia -using Distributed: addprocs -addprocs(4) -backend = StructureFunctions.DistributedBackend() -``` - -### GPUExt (GPUBackend) - -Requires `KernelAbstractions.jl` + GPU package (CUDA.jl, AMDGPU.jl, etc.): +*Strong and weak scaling of the threaded point kernel (`benchmark/benchmark_scaling.jl`); one GPU +against the serial CPU over the problem size and over the slice count (`gpu/collect_benchmark_assets.jl`); +and the device kernel on `KernelAbstractions.CPU()` against the serial reference.* -```toml -[extras] -KernelAbstractions = "63c18a36-062a-441e-b365-b594b6ce51b1" +## Validation -[extensions] -StructureFunctionsKernelAbstractionsExt = "KernelAbstractions" -``` - -## Migration from v0.2 - -### Breaking Changes - -| v0.2 | v0.3 | -|------|------| -| Symbol-based backend selection | Typed backend objects | -| `backend=:serial` | `backend=SerialBackend()` | -| `backend=:threaded` | `backend=ThreadedBackend()` | -| `backend=:distributed` | `backend=DistributedBackend()` | -| No GPU support | `backend=GPUBackend(...)` | - -### Recommended Updates - -```julia -# OLD (v0.2) -result = calculate_structure_function(sf, x, u, bins; backend=:threaded) - -# NEW (v0.3) -result = calculate_structure_function(sf, x, u, bins; backend=ThreadedBackend()) - -# Or use AutoBackend for automatic selection: -result = calculate_structure_function(sf, x, u, bins) # Defaults to AutoBackend() -``` - -### Compatibility - -- v0.3 is **not** backward-compatible with v0.2 scripts -- Update scripts by replacing symbol backends with typed backends -- See `CHANGELOG.md` for full change log - -## Examples - -Detailed worked examples are in `examples/` directory: - -- `simple_2d.jl`: Basic 2D structure function calculation -- `threaded_calculation.jl`: Multi-threaded execution -- `gpu_acceleration.jl`: GPU acceleration with KernelAbstractions -- `distributed_parallel.jl`: Multi-process execution -- `custom_operator.jl`: Defining custom SF operators - -Clone and run: +Routes are cross-checked against independent references: closed-form Fourier modes, the transform +against the direct sweep and the pair loop, analytic spectra and fluxes, the rotation average on the +sphere, and the backends against each other, CUDA included. The +[validation page](https://jbphyswx.github.io/StructureFunctions.jl/dev/validation/) lists the oracles +and the tolerance policy. ```bash -cd examples/ -julia simple_2d.jl -julia threaded_calculation.jl +julia --project=test test/runtests.jl # the suite (Aqua and JET included) +julia --project=gpu gpu/runtests.jl # every CUDA suite, on a GPU node +julia --project=docs docs/make.jl # the documentation, with every export checked ``` -## Contributing - -Contributions welcome! Please: - -1. Fork and create a feature branch -2. Add tests for new functionality -3. Ensure full test suite passes: `julia test/runtests.jl` -4. Document changes in docstrings and `CHANGELOG.md` - -## License - -See `LICENSE` file. - ## Citation -If you use StructureFunctions.jl in research, please cite: - ```bibtex -@software{structurefunctions_jl_2024, - author = {Benjamin, Jordan and Contributors}, - title = {StructureFunctions.jl: High-performance structure function calculations}, - year = {2024}, - doi = {10.5281/zenodo.14945669}, - url = {https://zenodo.org/records/14945669} +@software{structurefunctions_jl, + author = {Benjamin, Jordan}, + title = {StructureFunctions.jl: structure functions, spectra and fluxes of turbulent fields}, + doi = {10.5281/zenodo.14945669}, + url = {https://github.com/jbphyswx/StructureFunctions.jl} } ``` ---- - -**Last Updated**: March 2026 | **Version**: 0.3.0 | **Julia**: 1.12+ +See `CHANGELOG.md` for what each version added and `LICENSE` for the terms. diff --git a/benchmark/benchmark_scaling.jl b/benchmark/benchmark_scaling.jl index f444ab5..1bc851d 100644 --- a/benchmark/benchmark_scaling.jl +++ b/benchmark/benchmark_scaling.jl @@ -76,7 +76,12 @@ function run_worker(n_threads::Int, n_points::Int) julia_bin = joinpath(Sys.BINDIR, "julia") project_dir = joinpath(@__DIR__, "..") - cmd = `$julia_bin --project=$project_dir/benchmark -t $n_threads $worker_script $n_points` + # `JULIA_EXCLUSIVE=1` pins the worker's threads one per core. Without it the OS is free to put + # two threads on the two hyperthreads of one core, which reads as a scaling cliff: an unpinned + # 16-thread run measured 0.325 s or 0.581 s from one launch to the next, the second being the + # 8-thread time. + cmd = setenv(`$julia_bin --project=$project_dir/benchmark -t $n_threads $worker_script $n_points`, + merge(ENV, Dict("JULIA_EXCLUSIVE" => "1"))) output = readchomp(cmd) lines = filter(!isempty, split(output, '\n')) return JSON.parse(last(lines)) diff --git a/benchmark/benchmark_worker.jl b/benchmark/benchmark_worker.jl index 0397085..e6dd66e 100644 --- a/benchmark/benchmark_worker.jl +++ b/benchmark/benchmark_worker.jl @@ -34,10 +34,14 @@ sft = SCALING_SFT # Warmup (avoid counting compile time) SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = CB.ThreadedBackend(), verbose = false, show_progress = false) -# Timed run -t_start = time() -SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = CB.ThreadedBackend(), verbose = false, show_progress = false) -elapsed = time() - t_start +# The minimum of several runs, not one: a single sample on a shared machine is dominated by whatever +# else is resident, and at high thread counts that noise is the same size as the speedup being measured. +const SCALING_REPEATS = parse(Int, get(ENV, "SCALING_REPEATS", "5")) +elapsed = minimum(1:SCALING_REPEATS) do _ + t_start = time() + SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = CB.ThreadedBackend(), verbose = false, show_progress = false) + return time() - t_start +end result = Dict( "threads" => N_threads, diff --git a/docs/generate_assets/Project.toml b/docs/generate_assets/Project.toml index 24138ca..ce01593 100644 --- a/docs/generate_assets/Project.toml +++ b/docs/generate_assets/Project.toml @@ -1,25 +1,31 @@ [deps] -LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" -Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" -StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" Bessels = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" -SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" -FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" -StructureFunctions = "e93fee26-4d5e-49c1-899d-490508cfd19b" CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" -KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" +Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" +FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" +FlowGeometries = "0ccd6995-f618-4175-b01e-f437d0cb4974" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +LsqFit = "2fda8390-95c7-5789-9bda-21331edee243" +NonuniformFFTs = "cd96f58b-6017-4a02-bb9e-f4d81626177f" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" -Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" +StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" +Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +StructureFunctions = "e93fee26-4d5e-49c1-899d-490508cfd19b" + +[sources] +ComputationalBackends = {url = "https://github.com/jbphyswx/ComputationalBackends.jl"} +FlowGeometries = {url = "https://github.com/jbphyswx/FlowGeometries.jl"} +SpectralBackends = {url = "https://github.com/jbphyswx/SpectralBackends.jl"} +StructureFunctions = {path = "../.."} [compat] CairoMakie = "0.15" -KernelAbstractions = "0.9" JSON = "1" +KernelAbstractions = "0.9" OhMyThreads = "0.8" julia = "1.12" - -[sources] -SpectralBackends = { url = "https://github.com/jbphyswx/SpectralBackends.jl" } -StructureFunctions = { path = "../.." } diff --git a/docs/generate_assets/generate_assets.jl b/docs/generate_assets/generate_assets.jl index b68751d..5774e85 100644 --- a/docs/generate_assets/generate_assets.jl +++ b/docs/generate_assets/generate_assets.jl @@ -6,7 +6,7 @@ Run from the repo root: """ using ComputationalBackends: ComputationalBackends as CB -using StructureFunctions: StructureFunctions as SF, Calculations as SFC +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT using OhMyThreads: OhMyThreads # loads StructureFunctionsOhMyThreadsExt → enables ThreadedBackend using KernelAbstractions: KernelAbstractions as KA using CairoMakie: CairoMakie as CM @@ -73,8 +73,8 @@ function generate_kolmogorov_figure() r_min, r_max = 5.0, 400.0 bins = exp.(range(log(r_min), log(r_max); length=29)) - op = SF.SecondOrderStructureFunctionType() - result = SF.calculate_structure_function(op, x, u, bins; + op = SFT.SecondOrderStructureFunctionType() + result = SFC.calculate_structure_function(op, x, u, bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) sf2 = result.values @@ -124,12 +124,12 @@ function generate_long_vs_trans_figure() r_min, r_max = 5.0, 400.0 bins = exp.(range(log(r_min), log(r_max); length=29)) - op_L = SF.LongitudinalSecondOrderStructureFunctionType() - op_T = SF.TransverseSecondOrderStructureFunctionType() + op_L = SFT.LongitudinalSecondOrderStructureFunctionType() + op_T = SFT.TransverseSecondOrderStructureFunctionType() - res_L = SF.calculate_structure_function(op_L, x, u, bins; + res_L = SFC.calculate_structure_function(op_L, x, u, bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) - res_T = SF.calculate_structure_function(op_T, x, u, bins; + res_T = SFC.calculate_structure_function(op_T, x, u, bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) sf_L = res_L.values @@ -168,12 +168,12 @@ function generate_parity_figure() u = randn(2, N) bins = exp.(range(log(5.0), log(200.0); length=21)) - op = SF.SecondOrderStructureFunctionType() + op = SFT.SecondOrderStructureFunctionType() - res_serial = SF.calculate_structure_function(op, x, u, bins; + res_serial = SFC.calculate_structure_function(op, x, u, bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) - res_thread = SF.calculate_structure_function(op, x, u, bins; + res_thread = SFC.calculate_structure_function(op, x, u, bins; backend=CB.ThreadedBackend(), show_progress=false, verbose=false) sf_s = res_serial.values @@ -219,7 +219,7 @@ function generate_gpu_parity_figure() x = rand(FT, 2, N) u = rand(FT, 2, N) bin_edges = collect(FT, range(0.0, 1.4; length = 11)) - sft = SF.L2SFType() + sft = SFT.L2SFType() res_serial = SFC.calculate_structure_function( sft, x, u, bin_edges; @@ -271,7 +271,7 @@ function generate_single_pass_figure() # One O(N²) pass → NamedTuple of the six isotropic invariants; point-field input also # yields a `:helmholtz` entry (rotational/divergent decomposition). - res = SF.calculate_structure_functions_single_pass(x, u, bins; backend=CB.SerialBackend()) + res = SFC.calculate_structure_functions_single_pass(x, u, bins; backend=CB.SerialBackend()) fig = CM.Figure(size=(900, 560), fontsize=14) CM.Label(fig[0, 1], @@ -335,14 +335,14 @@ function generate_2d_binning_figure() for (row, (fname, mk)) in enumerate(fields) x, u = mk(N=2500) # Velocity-increment scale σ from L2(r); set per-order value ranges around it. - l2 = SF.calculate_structure_function(SF.LongitudinalSecondOrderStructureFunctionType(), + l2 = SFC.calculate_structure_function(SFT.LongitudinalSecondOrderStructureFunctionType(), x, u, dist_bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) σ2 = maximum(filter(isfinite, l2.values)); σ = sqrt(σ2) seq(hi) = collect(range(0.0, hi; length=nval + 1)) # ≥0 (2nd order) sym(hi) = collect(range(-hi, hi; length=nval + 1)) # ± (3rd order) # One pass → all six joint histograms (per-invariant value bins, common bin count). value_bins = (seq(24σ2), seq(12σ2), seq(12σ2), sym(15σ^3), sym(15σ^3), sym(15σ^3)) - res = SF.calculate_structure_functions_single_pass_2d(x, u, dist_bins, value_bins; + res = SFC.calculate_structure_functions_single_pass_2d(x, u, dist_bins, value_bins; backend=CB.SerialBackend()) for (col, (key, signed, lab)) in enumerate(invs) diff --git a/docs/generate_assets/generate_feature_figures.jl b/docs/generate_assets/generate_feature_figures.jl index c6f0f93..9ec9099 100644 --- a/docs/generate_assets/generate_feature_figures.jl +++ b/docs/generate_assets/generate_feature_figures.jl @@ -1,5 +1,5 @@ """ -Generate figure assets for the gridded, directional, multi-channel and spectral-transform features. +Generate figure assets for the gridded, directional, multi-field and spectral-transform features. Run from the repo root: julia --project=docs/generate_assets docs/generate_assets/generate_feature_figures.jl @@ -7,7 +7,11 @@ Run from the repo root: using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT +using StructureFunctions: MultiFields as MF using SpectralBackends: SpectralBackends as SB +using FlowGeometries: FlowGeometries as FG +using NonuniformFFTs: NonuniformFFTs +using LsqFit: LsqFit using Bessels: Bessels using FFTW: FFTW using CairoMakie: CairoMakie as CM @@ -222,9 +226,9 @@ function generate_helmholtz_spectra_figure() println(" wrote $out") end -# ─── Figure: scalar and multi-channel structure functions ────────────────── +# ─── Figure: scalar and multi-field structure functions ────────────────── -function generate_channels_figure() +function generate_fields_figure() Random.seed!(33) N = 4000 x = 2π .* rand(2, N) @@ -235,7 +239,7 @@ function generate_channels_figure() u[2, p] = -sin(3 * x[2, p]) θ[1, p] = cos(4 * x[1, p] + 0.3) + 0.4sin(9 * x[2, p]) end - fields = SF.Fields(vectors = (u,), scalars = (θ,)) + fields = MF.Fields(vectors = (u,), scalars = (θ,)) bins = collect(10 .^ range(log10(0.05), log10(2.5); length = 22)) mids = SF.midpoints(bins) @@ -249,7 +253,7 @@ function generate_channels_figure() fig = CM.Figure(size = (1100, 430)) ax1 = CM.Axis(fig[1, 1]; xscale = log10, yscale = log10, xlabel = "separation r", ylabel = "structure function", - title = "One pass over a velocity + tracer bundle") + title = "One pass over a velocity + tracer multi-field") CM.lines!(ax1, mids, vel.values; linewidth = 3, label = "⟨‖δu‖²⟩ (velocity)") CM.lines!(ax1, mids, scal.values; linewidth = 3, label = "⟨(δθ)²⟩ (tracer)") CM.axislegend(ax1; position = :lt) @@ -259,7 +263,7 @@ function generate_channels_figure() CM.lines!(ax2, mids, yag.values; linewidth = 3, color = :seagreen) CM.hlines!(ax2, [0.0]; color = :black, linestyle = :dash) - out = joinpath(ASSETS_DIR, "sf_channels.png") + out = joinpath(ASSETS_DIR, "sf_fields.png") CM.save(out, fig) println(" wrote $out") end @@ -365,7 +369,7 @@ function generate_advective_figure() mids = SF.midpoints(bins) asf = SFC.calculate_structure_function( - SFT.VectorDotSFType(1, 2), x, SF.Fields(vectors = (u, a)), bins; + SFT.VectorDotSFType(1, 2), x, MF.Fields(vectors = (u, a)), bins; output_type = SF.StructureFunctionSumsAndCounts) Ks = collect(range(1.5, 9.0; length = 60)) flux = SFC.spectral_flux(asf, Ks) @@ -658,16 +662,278 @@ function generate_covariance_figure() println(" wrote $out") end +# ─── Figure: pair weights, and a grid's cell measure as the weight ──────── + +function generate_weights_figure() + Random.seed!(41) + geo = FG.Geometry.SphericalGeometry(1.0) + n_lon, n_lat = 36, 24 + lam = range(0.0, step = 2π / n_lon, length = n_lon) + phi = range(-π / 2 + π / (2n_lat), step = π / n_lat, length = n_lat) + grid = FG.Grids.StructuredGrid(geo, lam, phi) + w = SFC.cell_measure(grid) + + u = zeros(2, n_lon, n_lat) + for j in 1:n_lat, i in 1:n_lon + u[1, i, j] = cos(3 * lam[i]) * cos(phi[j]) + 0.4sin(2 * phi[j]) + u[2, i, j] = -sin(2 * lam[i]) * cos(phi[j]) + end + bins = collect(range(0.0, π; length = 18)) .+ 1e-3 + mids = SF.midpoints(bins) + plain = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, Float64; + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + area = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, Float64; weights = w, + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + + fig = CM.Figure(size = (1100, 430)) + ax1 = CM.Axis(fig[1, 1]; xlabel = "latitude φ", ylabel = "cell measure", + title = "cell_measure(grid): a lat-lon cell shrinks toward the poles") + CM.lines!(ax1, collect(phi), w[1:n_lon:end]; linewidth = 3) + + ax2 = CM.Axis(fig[1, 2]; xlabel = "separation r", ylabel = "⟨δu_L²⟩", + title = "counting pairs equally vs weighting them by area") + CM.lines!(ax2, mids, plain.values; linewidth = 3, label = "every pair counts once") + CM.lines!(ax2, mids, area.values; linewidth = 3, linestyle = :dash, + label = "weights = cell_measure(grid)") + CM.axislegend(ax2; position = :rb) + + out = joinpath(ASSETS_DIR, "sf_weights.png") + CM.save(out, fig) + println(" wrote $out") +end + +# ─── Figure: the exact sorted route for one-dimensional point lists ─────── + +function generate_sorted_line_figure() + Random.seed!(42) + line_field(N) = begin + x = reshape(sort(100 .* rand(N)), 1, N) + u = reshape(sin.(0.4 .* x[1, :]) .+ 0.2 .* randn(N), 1, N) + (x, u) + end + bins = collect(range(0.0, 5.0; length = 21)) + mids = SF.midpoints(bins) + + # the sorted route is taken automatically for a polynomial operator on a line; + # a norm power is not a polynomial, so it keeps the pair loop + Ns = [1_000, 2_000, 4_000, 8_000, 16_000, 32_000] + t_sorted = Float64[] + t_pairs = Float64[] + for N in Ns + x, u = line_field(N) + f() = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Int64; + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + f() + push!(t_sorted, minimum(@elapsed(f()) for _ in 1:3)) + if N <= 8_000 + g() = SFC.calculate_structure_function(SFT.FullVectorStructureFunctionType{3}(), x, u, bins, + Int64; output_type = SF.StructureFunction, + verbose = false, show_progress = false) + g() + push!(t_pairs, @elapsed g()) + end + end + + # exactness against a pair loop written here, at a size where both are quick + Nc = 1_500 + x, u = line_field(Nc) + got = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Int64; + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + ref_s = zeros(length(mids)) + ref_c = zeros(Int, length(mids)) + for i in 1:Nc, j in (i + 1):Nc + r = abs(x[1, j] - x[1, i]) + b = searchsortedfirst(bins, r) - 1 + if 1 <= b <= length(mids) + ref_s[b] += (u[1, j] - u[1, i])^2 + ref_c[b] += 1 + end + end + ref = ref_s ./ max.(ref_c, 1) + + fig = CM.Figure(size = (1100, 430)) + ax1 = CM.Axis(fig[1, 1]; xscale = log10, yscale = log10, xlabel = "points N", + ylabel = "seconds", title = "Prefix sums of the monomials, not a pair loop") + CM.scatterlines!(ax1, Float64.(Ns), t_sorted; linewidth = 3, markersize = 11, + label = "sorted route (polynomial operator)") + CM.scatterlines!(ax1, Float64.(Ns[1:length(t_pairs)]), t_pairs; linewidth = 3, markersize = 11, + label = "pair loop (‖δu‖³, not a polynomial)") + CM.lines!(ax1, Float64.(Ns), t_sorted[1] .* (Ns ./ Ns[1]); linestyle = :dot, color = :gray, + label = "N") + CM.lines!(ax1, Float64.(Ns[1:length(t_pairs)]), t_pairs[1] .* (Ns[1:length(t_pairs)] ./ Ns[1]) .^ 2; + linestyle = :dash, color = :gray, label = "N²") + CM.axislegend(ax1; position = :lt) + + ax2 = CM.Axis(fig[1, 2]; xlabel = "separation r", ylabel = "⟨δu_L²⟩", + title = "and it is exact: every pair the loop counts, counted once") + CM.lines!(ax2, mids, ref; linewidth = 6, color = (:steelblue, 0.35), label = "pair loop") + CM.lines!(ax2, mids, got.values; linewidth = 2, color = :black, linestyle = :dash, + label = "sorted route") + CM.axislegend(ax2; position = :rb) + + out = joinpath(ASSETS_DIR, "sf_sorted_line.png") + CM.save(out, fig) + println(" wrote $out") +end + +# ─── Figure: the moment tensor, and its trace against the scalar entry ──── + +function generate_tensor_figure() + Random.seed!(43) + N = 3000 + x = 2π .* rand(2, N) + u = zeros(2, N) + for p in 1:N # anisotropic on purpose: the tensor is the point + u[1, p] = cos(3 * x[1, p]) + 0.3cos(5 * x[2, p]) + u[2, p] = 0.35 * (-sin(2 * x[2, p])) + end + bins = collect(range(0.1, 2.6; length = 18)) + mids = SF.midpoints(bins) + T = SFC.calculate_structure_function_tensor(Val(2), x, u, bins; verbose = false, + show_progress = false) + s2 = SFC.calculate_structure_function(SFT.S2SFType(), x, u, bins; + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + + fig = CM.Figure(size = (1100, 430)) + ax1 = CM.Axis(fig[1, 1]; xlabel = "separation r", ylabel = "⟨δu_a δu_b⟩", + title = "The second moment as a tensor, not a scalar") + CM.lines!(ax1, mids, T.values[1, 1, :]; linewidth = 3, label = "T₁₁") + CM.lines!(ax1, mids, T.values[2, 2, :]; linewidth = 3, label = "T₂₂") + CM.lines!(ax1, mids, T.values[1, 2, :]; linewidth = 3, label = "T₁₂") + CM.axislegend(ax1; position = :lt) + + ax2 = CM.Axis(fig[1, 2]; xlabel = "separation r", ylabel = "trace", + title = "its trace is the scalar second-order entry") + CM.lines!(ax2, mids, T.values[1, 1, :] .+ T.values[2, 2, :]; linewidth = 6, + color = (:seagreen, 0.35), label = "T₁₁ + T₂₂") + CM.lines!(ax2, mids, s2.values; linewidth = 2, color = :black, linestyle = :dash, + label = "⟨‖δu‖²⟩") + CM.axislegend(ax2; position = :rb) + + out = joinpath(ASSETS_DIR, "sf_tensor.png") + CM.save(out, fig) + println(" wrote $out") +end + +# ─── Figure: the soft-binned non-uniform FFT route for scattered points ─── + +function generate_scattered_modes_figure() + Random.seed!(44) + N = 6000 + x = 2π .* rand(2, N) + u = zeros(2, N) + for p in 1:N + u[1, p] = cos(2 * x[1, p]) + 0.4sin(3 * x[2, p]) + u[2, p] = -sin(2 * x[2, p]) + end + bins = collect(range(0.15, 2.0; length = 15)) + mids = SF.midpoints(bins) + exact = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; + output_type = SF.StructureFunction, verbose = false, + show_progress = false) + tag = SFC.NonuniformFFTsSpectralBackend() + Ms = [48, 64, 96, 128, 192] + curves = Dict{Int, Vector{Float64}}() + errs = Float64[] + for M in Ms + s = SFC.ScatteredModesSchedule(x, 2.0, (M, M); taper = SF.GaussianTaper(2π / M)) + r = SFC.calculate_structure_function(SFT.L2SFType(), s, u, bins, tag; + output_type = SF.StructureFunction, verbose = false) + curves[M] = collect(r.values) + push!(errs, maximum(abs.(r.values .- exact.values)) / maximum(abs, exact.values)) + end + + fig = CM.Figure(size = (1100, 430)) + ax1 = CM.Axis(fig[1, 1]; xlabel = "separation r", ylabel = "⟨δu_L²⟩", + title = "Scattered points through a non-uniform FFT: a soft bin") + CM.lines!(ax1, mids, exact.values; linewidth = 6, color = (:black, 0.3), label = "hard bins, pair loop") + for M in (48, 128, 192) + CM.lines!(ax1, mids, curves[M]; linewidth = 2, label = "$(M)² modes") + end + CM.axislegend(ax1; position = :rb) + + ax2 = CM.Axis(fig[1, 2]; xscale = log10, yscale = log10, xlabel = "modes per direction", + ylabel = "max relative difference", + title = "not exact at any finite mode count, and convergent") + CM.scatterlines!(ax2, Float64.(Ms), errs; linewidth = 3, markersize = 12) + + out = joinpath(ASSETS_DIR, "sf_scattered_modes.png") + CM.save(out, fig) + println(" wrote $out") +end + +# ─── Figure: fitting a spectrum and a flux instead of inverting them ────── + +function generate_fits_figure() + D = 2 + k_edges = collect(10 .^ range(log10(0.5), log10(20.0); length = 11)) + kc = SF.midpoints(k_edges) + E_true = 0.7 .* kc .^ (-5 / 3) + r = collect(10 .^ range(log10(0.05), log10(4.0); length = 70)) + edges = vcat(r, 2 * r[end] - r[end - 1]) + S2 = SFC.SpectrumForwardModel(Val(D), r, k_edges).H * E_true + res2 = SF.StructureFunction(SFT.S2SFType(), edges, S2) + seg = SFC.fit_spectrum(res2, [first(k_edges), last(k_edges)], SFC.SegmentedPowerLaw(1), Val(D)) + + # a flux with one injection step, through the third-order forward model + ε_true = 0.35 + ξ_true = zeros(length(kc)) + ξ_true[4] = 1.2 + fm = SFC.FluxForwardModel(r, k_edges) + S3 = fm.H * vcat(ε_true, ξ_true) + res3 = SF.StructureFunction(SFT.S3SFType(), edges, S3) + W = fill(1e-6, length(r)) + plain = SFC.fit_flux(res3, k_edges, SFC.RegularizedLeastSquares(nothing); W) + nnls = SFC.fit_flux(res3, k_edges, SFC.NonNegativeLeastSquares(); W) + F_true = SFC.flux_matrix(fm) * vcat(ε_true, ξ_true) + k_resolved = π / maximum(r) # a bin narrower than this is not resolved by the sampled range + + fig = CM.Figure(size = (1100, 430)) + ax1 = CM.Axis(fig[1, 1]; xscale = log10, yscale = log10, xlabel = "wavenumber k", + ylabel = "E(k)", title = "A spectrum fitted from S₂, not inverted") + CM.lines!(ax1, kc, E_true; linewidth = 6, color = (:black, 0.3), label = "true k^(-5/3)") + CM.lines!(ax1, kc, SFC.segmented_spectrum(seg.parameters, kc, seg.breakpoints); linewidth = 2, + linestyle = :dash, label = "SegmentedPowerLaw(1)") + CM.text!(ax1, 1.0, 0.05; text = "fitted slope $(round(seg.parameters[2]; digits = 3))") + CM.axislegend(ax1; position = :lb) + + ax2 = CM.Axis(fig[1, 2]; xscale = log10, xlabel = "wavenumber k", ylabel = "flux Π(k)", + title = "and a spectral flux from S₃, where the prior does the work") + CM.lines!(ax2, nnls.k, F_true; linewidth = 6, color = (:black, 0.3), label = "true flux") + CM.lines!(ax2, plain.k, plain.F; linewidth = 2, linestyle = :dash, color = :firebrick, + label = "least squares, no prior") + CM.lines!(ax2, nnls.k, nnls.F; linewidth = 2, color = :seagreen, + label = "NonNegativeLeastSquares (ξ ≥ 0)") + CM.vlines!(ax2, [k_resolved]; color = :gray, linestyle = :dashdot) + CM.text!(ax2, k_resolved * 1.04, minimum(F_true); text = "π / r_max", color = :gray) + CM.hlines!(ax2, [0.0]; color = :gray, linestyle = :dot) + CM.axislegend(ax2; position = :rb) + + out = joinpath(ASSETS_DIR, "sf_fits.png") + CM.save(out, fig) + println(" wrote $out") +end + println("Generating StructureFunctions.jl feature figures...") generate_spectra_figure() generate_missing_data_figure() generate_directional_figure() generate_helmholtz_spectra_figure() -generate_channels_figure() +generate_fields_figure() generate_gridded_algorithms_figure() generate_advective_figure() generate_exact_laws_figure() generate_spherical_figure() generate_culling_figure() generate_covariance_figure() +generate_weights_figure() +generate_sorted_line_figure() +generate_tensor_figure() +generate_scattered_modes_figure() +generate_fits_figure() println("Done.") diff --git a/docs/make.jl b/docs/make.jl index 02a48f6..c832006 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -13,6 +13,9 @@ const MODULES = [ StructureFunctions.StructureFunctionTypes, StructureFunctions.StructureFunctionObjects, StructureFunctions.Calculations, + StructureFunctions.HelperFunctions, + StructureFunctions.MultiFields, + StructureFunctions.KHM, ] makedocs(; @@ -23,7 +26,8 @@ makedocs(; canonical = "https://jbphyswx.github.io/StructureFunctions.jl", prettyurls = get(ENV, "CI", "false") == "true", assets = String[], - size_threshold = 400 * 1024, + size_threshold_warn = 400 * 1024, + size_threshold = 800 * 1024, ), pages = [ "Home" => "index.md", @@ -34,18 +38,25 @@ makedocs(; "Extensions" => "extensions.md", "Examples" => "examples.md", "Walkthrough" => "walkthrough.md", + "Exact Laws (KHM)" => "khm.md", "Validation" => "validation.md", "Binning Internals" => "uniform_bin_digitize.md", - "API Reference" => "api.md", + "API Reference" => [ + "api/operators.md", + "api/calculations.md", + "api/results.md", + "api/helpers.md", + "api/internals.md", + ], ], - # Loose hand-written pages contain links to source files outside docs/src/ and a few - # not-yet-cross-referenced names; keep the build green and tighten incrementally. - warnonly = true, - checkdocs = :none, + warnonly = false, + checkdocs = :exports, ) -deploydocs(; - repo = "github.com/jbphyswx/StructureFunctions.jl", - devbranch = "main", - push_preview = true, -) +if get(ENV, "CI", "false") == "true" + deploydocs(; + repo = "github.com/jbphyswx/StructureFunctions.jl", + devbranch = "main", + push_preview = true, + ) +end diff --git a/docs/src/api.md b/docs/src/api.md deleted file mode 100644 index 11aea0b..0000000 --- a/docs/src/api.md +++ /dev/null @@ -1,52 +0,0 @@ -```@meta -CurrentModule = StructureFunctions -``` - -# API Reference - -Complete reference for the public API. Use the index below to jump to a symbol, or browse the -grouped sections that follow. - -```@index -``` - -## Structure-function operator types - -The pairwise operators (`SFT` = `StructureFunctions.StructureFunctionTypes`) select *which* -structure function is accumulated. Shorthands such as `L2SFType`, `T2SFType`, `S3SFType` are -re-exported from the top-level module. - -```@autodocs -Modules = [StructureFunctions.StructureFunctionTypes] -Order = [:type, :function, :constant] -``` - -## Calculation entry points - -The `Calculations` submodule (`SFC`) holds the compute API: the point-field and batched drivers, -the single-pass functions, backend types, and the GPU workspace. - -```@autodocs -Modules = [StructureFunctions.Calculations] -Order = [:function, :type, :constant] -``` - -## Result containers - -Binned results live in `StructureFunctionObjects`. Raw accumulators carry the `…SumsAndCounts` -suffix; the bare names are the averaged/derived views. - -```@autodocs -Modules = [StructureFunctions.StructureFunctionObjects] -Order = [:type, :function] -``` - -## Bin edges & top-level API - -Fast O(1) bin-edge wrappers (`LinearBinEdges`, `LogBinEdges`, `InfPaddedBinEdges`) and the -remaining top-level re-exports. - -```@autodocs -Modules = [StructureFunctions] -Order = [:type, :function, :constant] -``` diff --git a/docs/src/api/calculations.md b/docs/src/api/calculations.md new file mode 100644 index 0000000..9c59f42 --- /dev/null +++ b/docs/src/api/calculations.md @@ -0,0 +1,23 @@ +```@meta +CurrentModule = StructureFunctions +``` + +# Calculations + +The compute API: the point-list and multi-field entries on every backend, the single-pass +invariants, the joint histograms, the tensors, the gridded sweeps and transforms, the spectral and +flux transforms, the regularised fits, and the device workspaces. + +```@index +Pages = ["calculations.md"] +``` + +```@docs +Calculations +``` + +```@autodocs +Modules = [StructureFunctions.Calculations] +Private = false +Order = [:function, :type, :constant] +``` diff --git a/docs/src/api/helpers.md b/docs/src/api/helpers.md new file mode 100644 index 0000000..71f46af --- /dev/null +++ b/docs/src/api/helpers.md @@ -0,0 +1,36 @@ +```@meta +CurrentModule = StructureFunctions +``` + +# Bins, tapers, fields and geometry + +The bin-edge wrappers with `O(1)` digitizing, the tapers shared by the spectra and the harmonic +route, the `HarmonicNodes` and `ModeBinEdges` objects a kernel-binned result carries, the `Fields` +multi-field, and the geometry helpers: pair frames, transverse conventions and the spherical +metric. + +```@index +Pages = ["helpers.md"] +``` + +## Top-level + +```@autodocs +Modules = [StructureFunctions] +Private = false +Order = [:type, :function, :constant] +``` + +## MultiFields + +```@autodocs +Modules = [StructureFunctions.MultiFields] +Private = false +``` + +## Geometry + +```@autodocs +Modules = [StructureFunctions.HelperFunctions] +Private = false +``` diff --git a/docs/src/api/internals.md b/docs/src/api/internals.md new file mode 100644 index 0000000..a8cdf45 --- /dev/null +++ b/docs/src/api/internals.md @@ -0,0 +1,77 @@ +```@meta +CurrentModule = StructureFunctions +``` + +# Internals + +Types and functions that are not exported but that the exported entries name: the schedules a grid +resolves to, the lag transports, the field shapes, culling, the second histogram axis, the +polynomial contract of the operators and the squared-distance digitizing. + +```@index +Pages = ["internals.md"] +``` + +## Schedules and transports + +```@docs +Calculations.AbstractSeparableSchedule +Calculations.UniformLagSchedule +Calculations.RectilinearLagSchedule +Calculations.ZonalLagSchedule +Calculations.ScatteredPairs +Calculations.AbstractLagTransport +Calculations.IdentityTransport +Calculations.FrameTransport +Calculations.uniform_axes +Calculations.n_slabs +Calculations.separable_layout +Calculations.lag_limits +Calculations.uniform_lag_box +Calculations.lag_transport +Calculations.NoWeights +Calculations.AllValid +Calculations.field_validity +Calculations.BatchLeading +``` + +## Kernels of the transforms + +```@docs +Calculations.isotropic_kernel +Calculations.AbstractMissingLagPolicy +``` + +## Shapes, culling and the second axis + +```@docs +Calculations.AbstractFieldShape +Calculations.CullingPolicy +Calculations.AutoCulling +Calculations.AlwaysCulling +Calculations.NoCulling +Calculations.CellGrid +Calculations.AbstractSecondAxisSource +Calculations.InvariantValueAxis +Calculations.SeparationAngleAxis +Calculations.axis_bounds +``` + +## The polynomial contract + +```@docs +StructureFunctionTypes.is_polynomial_operator +StructureFunctionTypes.moment_contract +StructureFunctionTypes.SymmetricMoments +StructureFunctionTypes.symmetric_indices +StructureFunctionTypes.order +StructureFunctionTypes.scalar_order +``` + +## Squared-distance digitizing + +```@docs +AbstractSquaredDigitizePlan +squared_digitize_plan +squared_digitize +``` diff --git a/docs/src/api/operators.md b/docs/src/api/operators.md new file mode 100644 index 0000000..3eb831c --- /dev/null +++ b/docs/src/api/operators.md @@ -0,0 +1,20 @@ +```@meta +CurrentModule = StructureFunctions +``` + +# Operators + +An operator names the statistic of a pair's increment that is accumulated. Every pairwise operator is +callable on one pair, `sf(δu, r̂)`, and the transforms consume it through its polynomial contract +(`moment_contract`). The shorthands `L2SFType`, `T2SFType`, `S3SFType`, … are re-exported from the +top-level module; the instances `L2SF`, `T2SF`, … are the same operators already constructed. + +```@index +Pages = ["operators.md"] +``` + +```@autodocs +Modules = [StructureFunctions.StructureFunctionTypes] +Private = false +Order = [:type, :constant, :function] +``` diff --git a/docs/src/api/results.md b/docs/src/api/results.md new file mode 100644 index 0000000..4a49936 --- /dev/null +++ b/docs/src/api/results.md @@ -0,0 +1,18 @@ +```@meta +CurrentModule = StructureFunctions +``` + +# Result containers + +Binned results. Raw accumulators carry the `…SumsAndCounts` suffix and add across processes and time +steps; the bare names are the averaged views. + +```@index +Pages = ["results.md"] +``` + +```@autodocs +Modules = [StructureFunctions.StructureFunctionObjects] +Private = false +Order = [:type, :function] +``` diff --git a/docs/src/architecture.md b/docs/src/architecture.md index f8cb507..82e830d 100644 --- a/docs/src/architecture.md +++ b/docs/src/architecture.md @@ -1,361 +1,155 @@ -# Architecture: Design & Implementation +# Architecture + +How the package is organised and how a call becomes a kernel. + +## Three orthogonal choices + +Every calculation is a product of three independent choices, each a type: + +``` +what to accumulate an operator L2SFType(), MixedSFType{1,0,2}(), MomentTensorOperator{3}(), … +over which pairs the input's shape and schedule: a point list, a multi-field, a grid's + UniformLagSchedule / RectilinearLagSchedule / ZonalLagSchedule / ScatteredPairs, + a ScatteredModesSchedule, HarmonicNodes +how to execute a backend SerialBackend(), ThreadedBackend(), DistributedBackend(), + GPUBackend(device), AutoBackend(); and on a grid a spectral tag, + FastFourierTransformSpectralBackend() / AutoSpectralBackend() +``` + +The operator knows nothing about the data layout, the schedule nothing about the operator beyond its +polynomial contract, and the backend nothing about either. A new operator is a subtype with one +functor method (and a `moment_contract` method if the transforms are to compute it); a new +convention for the transverse direction is a subtype with one `transverse_basis` method; a new +execution backend is a set of methods on the backend type. + +## Modules + +| module | file(s) | holds | +|---|---|---| +| `StructureFunctions` | `src/StructureFunctions.jl`, `src/BinEdges.jl`, `src/AuxiliaryAxes.jl` | exports, the bin-edge wrappers and squared-distance digitize plans, tapers, `HarmonicNodes`, `ModeBinEdges` | +| `MultiFields` | `src/MultiFields.jl` | `Fields` — several vector and scalar fields sampled at the same points, packed `(V·D + K, N)` | +| `HelperFunctions` | `src/HelperFunctions.jl` | pair frames on flat and spherical geometry, transverse conventions, `SphericalDistance` | +| `StructureFunctionTypes` | `src/StructureFunctionTypes.jl` | the operators, their functors, and the polynomial contract (`order`, `is_polynomial_operator`, `SymmetricMoments`, `moment_contract`) | +| `StructureFunctionObjects` | `src/StructureFunctionObjects.jl` | the result containers | +| `Calculations` | `src/Calculations.jl`, `src/Calculations/*.jl` | every entry point and kernel: dispatch, serial and single-pass point loops, culling, batches over auxiliary axes, gridded schedules and the direct sweep, the lag algebra of the transform, the sorted line route, the scattered-modes schedule, tensors, transforms and fits, the harmonic route, device stubs | +| `KHM` | `src/KHM.jl` | the exact-law inversions | + +Extensions supply what needs another package: see [Extensions](extensions.md). + +## From a call to a kernel + +`calculate_structure_function(sf, x, u, bins; backend, distance_metric, weights, culling, …)`: + +1. **Shape.** `_validate_array_shape` reads the velocity width `D = size(u, 1)` and the coordinate + count the metric's geometry needs (`(D, N)` flat; `(2, N)` positions for a sphere whatever `D`), and + classifies the ranks into a `PointField`, `SharedPositionField` or `VaryingPositionField`. The width + is an array axis length, so the entry branches on it once and re-enters with a literal + `Val{D}`; below that point every type is concrete. +2. **Backend.** `_dispatch_execution_backend(backend, shape, …)` selects the serial, threaded, + distributed, MPI or device implementation; `AutoBackend` takes the threaded one when Julia has + more than one thread and the OhMyThreads extension is loaded. Paths with no implementation for a + request (weights on the GPU point kernels, in-place auxiliary axes on a device) refuse by name. +3. **Geometry.** `pair_geometry_for(metric, Val(D))` fixes a `FlatGeometry{D}` or + `SphericalGeometry{D}`; `prepare_pair_inputs` widens spherical input to ambient 3-vectors once. +4. **Kernel.** Flat two- and three-dimensional point lists take the SIMD compute/scatter kernel over + blocked pair tiles, with a cell-culling grid when the last bin edge bounds the separations; curved + geometry takes the scalar per-point kernel through `pair_frame`; one-dimensional lists with a + polynomial operator take the sorted line route; multi-fields take the multi-field kernel with the same + blocking. Each pair's value is `sf(δu, r̂)` binned by a squared-distance plan, and an operator odd + in a scalar increment reads the pair in its canonical orientation. +5. **Result.** The backends return the raw `StructureFunctionSumsAndCounts`; the public entry turns it + into the requested `output_type` — the averaged `StructureFunction` by default. + +A grid enters through the FlowGeometries extension: `calculate_structure_function(sf, grid, u, bins[, +spectral_tag]; backend, …)` reads the grid's **axis types** (a range is uniform, a coordinate vector is +not) and emits a schedule. Without a spectral tag the schedule runs the direct lag sweep, one +implementation for every separable schedule; with `FastFourierTransformSpectralBackend()` it runs the +transform engine; `AutoSpectralBackend()` costs both and takes the cheaper. + +## The transform engine + +For each pair of slabs (one slab on a uniform grid; the latitude rows of a lat-lon grid; the stretched +coordinates of a rectilinear one) the engine takes the forward transforms of every masked, weighted +monomial of degree up to the operator's order, forms the inverse columns of the increment moment +tensor — the `2^p` signed terms of the binomial expansion folded in the transform domain under +identity transport, or the raw cross-moments transformed by the pair frame per lag under frame +transport — and, per lag, contracts the symmetric moment store with the operator +(`moment_contract`) or accumulates it whole (the tensor entries). The host loop and the device kernel +share the lag algebra in `src/Calculations/lag_moments.jl`; the device version batches slab pairs and +runs two kernels per batch. The sorted line route and the harmonic route reuse the same contract: a +range's moments are prefix-sum differences, a harmonic kernel's are spin-weighted pseudo-spectra. + +## Result containers -This document explains how StructureFunctions.jl is organized internally and how computations are dispatched. - -## Table of Contents -- [Module Organization](#module-organization) -- [Type Hierarchy](#type-hierarchy) -- [Backend Dispatch](#backend-dispatch) -- [Extension System](#extension-system) -- [Code Layout](#code-layout) - -## Module Organization - -### Core Module: StructureFunctions - -The main module (`src/StructureFunctions.jl`) defines: -- **Type definitions**: `AbstractExecutionBackend`, `SerialBackend`, `ThreadedBackend`, etc. -- **Core functions**: `calculate_structure_function`, dispatcher methods -- **Result container**: `StructureFunction` type for storing results - -### Architecture Pattern: Operator × Container - -StructureFunctions.jl uses a **operator composition** pattern: - -``` -Data (x, u) - ↓ -[StructureFunction Operator] ← Type specifies WHICH calculation - ↓ -[Execution Backend] ← Type specifies HOW to compute - ↓ -Result Container ← Stores sums, counts, structure functions -``` - -Example: ```julia -# Operator: "Compute 2nd-order SF" -operator = SecondOrderStructureFunctionType() - -# Backend: "Use 4 threads" -backend = ThreadedBackend() - -# Call dispatcher with both -SF_result = calculate_structure_function(operator, x, u, bins; backend) +StructureFunction(operator, distance, values) # the averaged view, NaN where a bin is empty +StructureFunctionSumsAndCounts(operator, distance, sums, counts) # the raw accumulator; adds across processes and time steps +StructureFunction2DSumsAndCounts(operator, distance_bins, value_bins, sums, counts) # joint (distance × value) or (distance × angle) +StructureFunctionTensor(order, distance_bins, values) # (D, …, D, n_bins[, aux...]) +StructureFunctionTensorSumsAndCounts(order, distance_bins, sums, counts) +StructureFunctionTensor2DSumsAndCounts(order, distance_bins, axis_bins, sums, counts) +HelmholtzDecomposition2D(...) # rotational and divergent second-order components ``` -The **operator type** determines *what calculation* to perform (which SF variant, which order). The **backend type** determines *how* to execute it (serial, threaded, GPU, etc.). +`distance` is whatever binned the result: bin edges (a plain vector or an `AbstractBinEdges`), +`HarmonicNodes` for a kernel-binned result on a sphere, `ModeBinEdges` for the soft-binned non-uniform +FFT route. `midpoints(distance)` is the abscissa in every case, and the transforms and fits read a +result through its operator and distance rather than through bare arrays. ---- +## Bin edges -## Type Hierarchy +`AbstractBinEdges{T} <: AbstractVector{T}` wrappers give `digitize` an `O(1)` path: -### Execution Backends - -All backends inherit from `AbstractExecutionBackend`: - -``` -AbstractExecutionBackend (abstract) -├── SerialBackend -├── ThreadedBackend -├── DistributedBackend -├── GPUBackend{B} [parametric in device backend] -└── AutoBackend -``` - -**Key property**: Each backend type is **singleton-like** — zero memory overhead, pure dispatch. Example: -```julia -serial = SerialBackend() # Type ≈ Singleton -threaded = ThreadedBackend() # Type ≈ Singleton ``` - -### Structure Function Operators - -Operators describe *which* calculation variant: - +AbstractBinEdges +├── BinEdges a sorted vector, binary search +├── LinearBinEdges a range: floor((x − first)/step) + 1 by one fused multiply-add, then a one-ulp correction +├── LogBinEdges log-spaced edges: log(x) then the linear rule on the log grid +├── InfPaddedBinEdges ±∞ pads around another edge set, no copy +└── ModeBinEdges edges of a soft-binned result, carrying the mode schedule ``` -AbstractStructureFunctionType (abstract) -├── AbstractPairwiseStructureFunctionType -│ ├── SecondOrderStructureFunctionType # S2SF = ||δu||² -│ ├── ThirdOrderStructureFunctionType # S3SF = δu_L ||δu||² -│ ├── FullVectorStructureFunctionType{NF} # generic norm power ||δu||^NF -│ └── ProjectedStructureFunctionType{NL,NT} # L2SF, T2SF, L3SF, L1T2SF, ... -└── AbstractDerivedStructureFunctionType - └── Helmholtz-derived 2D rotational/divergent quantities -``` - -Each operator stores: -- **Order** (n=2, 3, 4, ...) — which structure function order -- **Projection** (if applicable) — which component to analyze -### Bin Edges (AbstractBinEdges) +The pair loops digitize the **squared** separation against a plan of squared edges +(`squared_digitize_plan`), which skips the square root; see [Binning Internals](uniform_bin_digitize.md) +for the derivation and why `round` is the wrong operator. -To eliminate the $O(\log B)$ binary search overhead in distance binning, StructureFunctions.jl provides custom, fast, zero-allocation collections subtyping `AbstractBinEdges{T}`: - -``` -AbstractBinEdges (abstract) -├── BinEdges [generic wrapper for standard vectors] -├── LinearBinEdges [O(1) FMA-based search for uniform ranges] -├── LogBinEdges [O(1) Exponent LUT Hybrid search for log ranges] -└── InfPaddedBinEdges [wrapper to append/prepend ±∞ boundaries] -``` - -These types implement custom `Base.searchsortedfirst` overrides, enabling highly efficient $O(1)$-like bin lookups within core calculations. - -#### Algorithmic Design - -##### 1. Linear Binning via Fused Multiply-Add (FMA) -When bin edges are uniformly spaced (a range), a standard binary search takes $O(\log B)$ steps. Instead, `LinearBinEdges` performs a constant-time $O(1)$ mapping from value to index: -$$\text{index}(x) = \text{round}\left(\text{Int}, x \cdot \text{inv\_step} + \text{offset}\right)$$ -where $\text{inv\_step} = 1/\delta$ and $\text{offset} = 1 - v_1/\delta$. By evaluating this via a Fused Multiply-Add (`muladd`) instruction, the CPU executes it in a single cycle. A subsequent $O(1)$ floating-point boundary check corrects any potential 1-ULP precision mismatch at bin edges, ensuring 100% numerical parity with standard binary search in only **~3 ns** (a **15x+ speedup**). - -##### 2. Log Binning via Exponent Lookup Tables (LUT) -Logarithmic binning normally requires evaluating $\ln(x)$ to map the value to linear space, but the hardware `log` instruction is highly latent (20-40 CPU cycles). To bypass this, `LogBinEdges` extracts the binary floating-point exponent of the query value using `exponent(x)`. This operation is an IEEE 754 bit-mask and shift, taking **< 0.5 ns**. - -During construction, a Lookup Table (LUT) is created to map each binary exponent (octave) to the first index in the bin edges vector that intersects with that octave. When searching: -1. Extract exponent $e = \text{exponent}(x)$. -2. Query the precomputed LUT to retrieve bounds `idx_start` and `idx_end` for that octave, restricting the search range. -3. Perform a hybrid search: if the restricted subrange contains $\le 8$ elements, use a fast cache-friendly linear scan; otherwise, run a binary search restricted to that subrange. -This hybrid strategy bypasses `log(x)` completely, reducing lookups to **~5-8 ns** (a **5x+ speedup**). - -##### 3. Out-Of-Bounds Handling via Virtual Padding -Calculations need to determine if a point pair's separation falls within the bounds of the bin edges. Rather than introducing branching code inside inner loops, `InfPaddedBinEdges` virtually prepends $-\infty$ (or `typemin(T)`) and appends $+\infty$ (or `typemax(T)`) to any existing `AbstractBinEdges` collection. Out-of-bounds inputs automatically fall into the boundary pads in $O(1)$ time without copying or allocating additional memory. - -### Result Containers - -StructureFunctions.jl decouples raw accumulation, processed 1D structure functions, and 2D joint-probability binning into separate parametric result types inheriting from `AbstractStructureFunction`: - -1. **`StructureFunction`**: Stores the final processed structure function values. -```julia -struct StructureFunction{FT, OT, BT, VT} <: AbstractStructureFunction - operator::OT # AbstractStructureFunctionType - distance_bins::BT # AbstractVector of (r_min, r_max) - values::VT # AbstractVector{FT} — computed SF - order::Int # 1, 2, 3, ... -end -``` - -2. **`StructureFunctionSumsAndCounts`**: Stores exact computed sums and point counts per bin. Ideal for distributed or chunked temporal aggregation. -```julia -struct StructureFunctionSumsAndCounts{FT, OT, BT, VT} <: AbstractStructureFunction - operator::OT - distance_bins::BT - sums::VT # Exact computed SF value sums - counts::VT # Integer counts of contributing pairs -end -``` - -3. **`StructureFunction2DSumsAndCounts`**: Stores the 2D joint-probability binning grid (separation distance $r$ vs. SF value $v$). -```julia -struct StructureFunction2DSumsAndCounts{FT, OT, BT, VT, MT, CT} <: AbstractStructureFunction - operator::OT - distance_bins::BT - value_bins::VT # Value increment bin edges - sums::MT # 2D matrix of exact sums (distance x value) - counts::CT # 2D matrix of contribution counts -end -``` - -All result containers support basic `Base` algebraic operations (like `+` and `+=`) to allow seamless aggregation across distributed processes or temporal timesteps. - ---- - -## Backend Dispatch - -### Dispatch Flow - -When you call `calculate_structure_function(operator, x, u, bins; backend)`: - -1. **Type signature selected** based on `backend` type -2. **Preparation phase** (same for all backends): - - Validate inputs - - Allocate result container - - Set up spatial binning -3. **Execution phase** (backend-specific): - - `SerialBackend`: Single loop over points - - `ThreadedBackend`: Multi-threaded loop via OhMyThreads - - `DistributedBackend`: Distribute over processes - - `GPUBackend`: Launch kernels - - `AutoBackend`: Detect available resources → select best backend -4. **Reduction phase** (same for all backends): - - Finalize sums and normalize - - Store in result container - -### Code Structure +## Code layout ``` src/ -├── Calculations.jl # Core calculation logic (backend-agnostic) -├── StructureFunctionTypes.jl # Operator type definitions -├── HelperFunctions.jl # Utilities (binning, normalization) -└── Backends.jl # Backend type definitions - +├── StructureFunctions.jl exports and includes +├── MultiFields.jl BinEdges.jl HelperFunctions.jl AuxiliaryAxes.jl +├── StructureFunctionTypes.jl operators and the polynomial contract +├── StructureFunctionObjects.jl result containers +├── Calculations.jl the compute module +├── Calculations/ +│ ├── backends.jl shapes.jl dispatch.jl shape → width literal → backend +│ ├── serial.jl serial_2d.jl serial_single_pass.jl culling.jl pair_schedule.jl point kernels +│ ├── batch.jl batch_api.jl batch_leading.jl workspace.jl gpu_stubs.jl auxiliary axes, device stubs +│ ├── multifields.jl second_axis.jl multi-fields, the second histogram axis +│ ├── gridded.jl gridded_zonal.jl lag_moments.jl scattered_modes.jl sorted_line.jl schedules, sweeps, lag algebra +│ ├── tensor.jl transforms.jl fits.jl harmonic.jl +└── KHM.jl ext/ -├── StructureFunctionsOhMyThreadsExt.jl # OhMyThreads integration -├── StructureFunctionsDistributedExt.jl # Distributed.jl integration -├── StructureFunctionsKernelAbstractionsExt.jl # KernelAbstractions integration -├── StructureFunctionsCairoMakieExt.jl # Plotting helpers -└── gpu/ # GPU kernel organization -``` - -### Example: ThreadedBackend Dispatch - -When `backend=ThreadedBackend()` is passed: - -```julia -# Simplified view of internal dispatcher -calculate_structure_function(op::StructureFunctionType, - x, u, bins; - backend::ThreadedBackend) = begin - # Setup (shared) - result = StructureFunction(...) - - # Execution (ThreadedBackend-specific) - # Uses OhMyThreads.tmapreduce to parallelize point-pair iteration - compute_threaded!(result, x, u, bins) - - # Finalize (shared) - normalize!(result) - - return result -end -``` - -This **method specialization** ensures: -- ✅ No runtime overhead choosing between backends -- ✅ Each backend can use its best algorithm -- ✅ Type-stable dispatch - ---- - -## Extension System - -### Lazy Loading via Extensions - -Optional dependencies are loaded **only when needed** via Julia's extension mechanism: - -```toml -[weakdeps] -OhMyThreads = "67456a42-ebe4-4781-8ad1-67f7eda8d8f7" -Distributed = "8ba89e20-285c-5519-8a0c-887f00cd4b76" -KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1f7f1" - -[extensions] -OhMyThreadsExt = "OhMyThreads" -DistributedExt = "Distributed" -GPUExt = "KernelAbstractions" -``` - -**Benefits**: -- Users who don't use ThreadedBackend pay zero cost (no OhMyThreads load time) -- GPU users can optionally install KernelAbstractions -- Fresh Julia session starts fast (no big dependency tree by default) - -### Adding a New Extension - -To add support for a new backend (e.g., `CUDABackend`): - -1. **Add weakdep** in Project.toml: - ```toml - CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" - ``` - -2. **Create extension** `ext/CUDAExt.jl`: - ```julia - module CUDAExt - - using StructureFunctions - using CUDA - - struct CUDABackend end - - function calculate_structure_function(op, x, u, bins; - backend::CUDABackend) - # CUDA-specific dispatch - end - - end # module - ``` - -3. **Publish** as part of release - -## Code Layout - -### Key Files - -| File | Purpose | -|------|---------| -| `src/Calculations.jl` | Main dispatcher; backend-agnostic logic | -| `src/StructureFunctionTypes.jl` | Operator type definitions | -| `src/HelperFunctions.jl` | Binning, distance metrics, utils | -| `src/Backends.jl` | Backend type definitions | -| `ext/StructureFunctionsOhMyThreadsExt.jl` | OhMyThreads integration | -| `ext/StructureFunctionsDistributedExt.jl` | Distributed.jl integration | -| `ext/StructureFunctionsKernelAbstractionsExt.jl` | KernelAbstractions + GPU kernels | -| `ext/StructureFunctionsCairoMakieExt.jl` | Plotting helpers | -| `src/__init__.jl` | Exports public types/functions | - -### Import Strategy - -```julia -# src/StructureFunctions.jl (main module) - -# Public exports -export SerialBackend, ThreadedBackend, DistributedBackend, - GPUBackend, AutoBackend, - calculate_structure_function, - StructureFunction - -# Dependencies -using LinearAlgebra -using Distances -using ProgressMeter -using StaticArrays - -# No imports of optional dependencies (those are extensions) -``` - -### Public vs Internal - -**Public API** (safe to use, won't change): -- `calculate_structure_function` function -- All `*Backend` types -- `StructureFunction` container -- Exported operator types - -**Internal** (subject to change): -- Helper functions in `HelperFunctions.jl` marked `@doc hide` -- Kernel implementations in extensions -- Intermediate data structures - ---- - -## Design Principles - -1. **Type Dispatch**: Use Julia's type system, not string dispatch - - ✅ Static overhead elimination - - ✅ Runtime type safety - - ✅ IDE autocompletion - -2. **Zero-Cost Abstraction**: Backend dispatch adds no runtime cost - - Single method per backend type - - Compiler resolves at dispatch time - - No runtime branching - -3. **Extensibility**: Users can add custom backends - - Define new `Backend <: AbstractExecutionBackend` type - - Define `calculate_structure_function` method for it - - Works instantly (static dispatch) - -4. **Separation of Concerns**: - - Operators describe *what* to compute (decoupled from backend) - - Backends describe *how* to compute (decoupled from operator) - - Result container is pure data (independent of both) - ---- - -## Related Topics - -- [Theory](theory.md): Mathematical foundations -- [Backends](backends.md): When to use each backend -- [Examples](../examples/README.md): Worked code examples +├── StructureFunctionsOhMyThreadsExt.jl StructureFunctionsDistributedExt.jl StructureFunctionsMPIExt.jl +├── StructureFunctionsKernelAbstractionsExt.jl + gpu/ (device kernels) StructureFunctionsCUDAExt.jl +├── StructureFunctionsAbstractFFTsExt.jl StructureFunctionsAbstractFFTsKernelAbstractionsExt.jl +├── StructureFunctionsNonuniformFFTsExt.jl StructureFunctionsNonuniformFFTsKernelAbstractionsExt.jl +├── StructureFunctionsFINUFFTExt.jl StructureFunctionsFINUFFTKernelAbstractionsExt.jl +├── StructureFunctionsNUFSHTExt.jl StructureFunctionsFlowGeometriesExt.jl +└── StructureFunctionsBesselsExt.jl StructureFunctionsLsqFitExt.jl +``` + +## Design rules + +- **Decide by types, never by inspecting values.** A range axis is uniform and a coordinate vector is + not; a spectral tag is a type; validity is `AllValid()` or a mask; a taper, a culling policy and a + missing-lag policy are types. No `Symbol` options. +- **Exactness is a property of a route, stated on it.** The direct sweep, the transform and the sorted + line are exact and are tested against each other; the harmonic route and the non-uniform FFT route + are kernel-binned and their results carry a distance object that says so; spectra from masked data + are estimators and their docstrings say so. +- **A request that cannot be met errors and names why.** Nothing falls back silently to a different + quantity. +- **Culling, transforms and backends never change an answer**, only its cost: counts equal exactly, + sums to round-off, and the tests hold every pair of routes to that. diff --git a/docs/src/assets/gpu_problem_size_scaling.png b/docs/src/assets/gpu_problem_size_scaling.png index b055a8a..2e658f1 100644 Binary files a/docs/src/assets/gpu_problem_size_scaling.png and b/docs/src/assets/gpu_problem_size_scaling.png differ diff --git a/docs/src/assets/gpu_slice_batch_scaling.png b/docs/src/assets/gpu_slice_batch_scaling.png index e35a615..0c6d79f 100644 Binary files a/docs/src/assets/gpu_slice_batch_scaling.png and b/docs/src/assets/gpu_slice_batch_scaling.png differ diff --git a/docs/src/assets/sf_advective_flux.png b/docs/src/assets/sf_advective_flux.png index bf57658..48ffbf9 100644 Binary files a/docs/src/assets/sf_advective_flux.png and b/docs/src/assets/sf_advective_flux.png differ diff --git a/docs/src/assets/sf_backend_parity.png b/docs/src/assets/sf_backend_parity.png index a9c78b0..fb88fca 100644 Binary files a/docs/src/assets/sf_backend_parity.png and b/docs/src/assets/sf_backend_parity.png differ diff --git a/docs/src/assets/sf_channels.png b/docs/src/assets/sf_channels.png deleted file mode 100644 index 8e50a41..0000000 Binary files a/docs/src/assets/sf_channels.png and /dev/null differ diff --git a/docs/src/assets/sf_culling.png b/docs/src/assets/sf_culling.png index dc8c5d6..61ee6dc 100644 Binary files a/docs/src/assets/sf_culling.png and b/docs/src/assets/sf_culling.png differ diff --git a/docs/src/assets/sf_fields.png b/docs/src/assets/sf_fields.png new file mode 100644 index 0000000..4b54f5c Binary files /dev/null and b/docs/src/assets/sf_fields.png differ diff --git a/docs/src/assets/sf_fits.png b/docs/src/assets/sf_fits.png new file mode 100644 index 0000000..14aa86d Binary files /dev/null and b/docs/src/assets/sf_fits.png differ diff --git a/docs/src/assets/sf_gpu_parity.png b/docs/src/assets/sf_gpu_parity.png index c1d182a..1cc979e 100644 Binary files a/docs/src/assets/sf_gpu_parity.png and b/docs/src/assets/sf_gpu_parity.png differ diff --git a/docs/src/assets/sf_gridded_algorithms.png b/docs/src/assets/sf_gridded_algorithms.png index 2274022..9d8c497 100644 Binary files a/docs/src/assets/sf_gridded_algorithms.png and b/docs/src/assets/sf_gridded_algorithms.png differ diff --git a/docs/src/assets/sf_scattered_modes.png b/docs/src/assets/sf_scattered_modes.png new file mode 100644 index 0000000..bafffb0 Binary files /dev/null and b/docs/src/assets/sf_scattered_modes.png differ diff --git a/docs/src/assets/sf_single_pass.png b/docs/src/assets/sf_single_pass.png index 1a62181..82c6ce3 100644 Binary files a/docs/src/assets/sf_single_pass.png and b/docs/src/assets/sf_single_pass.png differ diff --git a/docs/src/assets/sf_sorted_line.png b/docs/src/assets/sf_sorted_line.png new file mode 100644 index 0000000..d7e54ee Binary files /dev/null and b/docs/src/assets/sf_sorted_line.png differ diff --git a/docs/src/assets/sf_spherical.png b/docs/src/assets/sf_spherical.png index 0b54a90..5ab7b2a 100644 Binary files a/docs/src/assets/sf_spherical.png and b/docs/src/assets/sf_spherical.png differ diff --git a/docs/src/assets/sf_tensor.png b/docs/src/assets/sf_tensor.png new file mode 100644 index 0000000..523a0b2 Binary files /dev/null and b/docs/src/assets/sf_tensor.png differ diff --git a/docs/src/assets/sf_weights.png b/docs/src/assets/sf_weights.png new file mode 100644 index 0000000..275be31 Binary files /dev/null and b/docs/src/assets/sf_weights.png differ diff --git a/docs/src/assets/strong_scaling.png b/docs/src/assets/strong_scaling.png index 92d2734..21ebc74 100644 Binary files a/docs/src/assets/strong_scaling.png and b/docs/src/assets/strong_scaling.png differ diff --git a/docs/src/assets/weak_scaling.png b/docs/src/assets/weak_scaling.png index 7ffacb5..27d139a 100644 Binary files a/docs/src/assets/weak_scaling.png and b/docs/src/assets/weak_scaling.png differ diff --git a/docs/src/backends.md b/docs/src/backends.md index a8e4e2b..1f17a69 100644 --- a/docs/src/backends.md +++ b/docs/src/backends.md @@ -1,494 +1,92 @@ -# Backends: Execution Models & Performance +# Backends -This document explains each execution backend, when to use it, and performance characteristics. +Where a calculation runs is a type passed as `backend`. The result never depends on it: every backend +gives the same counts exactly and the same sums to round-off, and the tests hold each pair of +backends to that (see [Validation](validation.md) for the tolerance policy). -## Table of Contents -- [Backend Comparison](#backend-comparison) -- [SerialBackend](#serialbackend) -- [ThreadedBackend](#threaded-backend) -- [DistributedBackend](#distributedbackend) -- [GPUBackend](#gpubackend) -- [AutoBackend](#autobackend) -- [Performance Tuning](#performance-tuning) +| backend | needs | runs | +|---|---|---| +| `SerialBackend()` | nothing | every route, on one thread; the reference the others are checked against | +| `ThreadedBackend()` | `using OhMyThreads`, `julia -t N` | point lists, multi-fields, tensors, the gridded sweeps and transforms, the sorted line route | +| `DistributedBackend()` | `using Distributed`, `addprocs` | point lists, multi-fields and tensors, each worker taking a share of the outer index; `DistributedBackend(ThreadedBackend())` threads inside each worker | +| `MPIBackend()` | `using MPI` | point lists across ranks | +| `GPUBackend(device)` | `using KernelAbstractions` and a device package | point lists, joint histograms, single-pass invariants, batches over auxiliary axes, tensors, multi-fields, and the gridded transform engine; `GPUBackend(KernelAbstractions.CPU())` runs the same kernels on the host | +| `AutoBackend()` | — | the default: the distributed backend when workers are present, the threaded one when Julia has more than one thread and its extension is loaded, the serial one otherwise | ---- - -## Backend Comparison - -| Backend | Best For | Parallelism | Memory Overhead | Setup Time | -|---------|----------|-------------|-----------------|------------| -| **Serial** | Development, debugging, small data (~10M points) | None | Minimal | Immediate | -| **Threaded** | Medium data (10M–500M points), shared-memory systems | Within-node threads | Low | ~100ms (OhMyThreads) | -| **Distributed** | Large data (>500M points), multi-node clusters | Across nodes | Moderate | ~1s (worker startup) | -| **GPU** | Very large data (>1B points), if GPU available | GPU device | Moderate | ~500ms (kernel compile) | -| **Auto** | Unknown resource availability | Adaptive | Low | ~100ms (detection) | - ---- - -## SerialBackend - -### Definition -Single-threaded, reference implementation. All computations run on the calling thread. - -### When to Use -- ✅ **Development & debugging**: Deterministic, easy to profile -- ✅ **Small datasets**: <10M points (threads don't help much) -- ✅ **Shared environments**: Where spawning threads is discouraged -- ✅ **Validation**: Reference implementation for comparing other backends - -### When NOT to Use -- ❌ Large data (>10M points): Too slow -- ❌ Multi-CPU available: Wastes resources - -### Examples - -**1. Allocating API:** - -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -# Small test dataset -x = (randn(1000), randn(1000)) -u = (randn(1000), randn(1000)) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] - -# Calculate using SerialBackend explicitly -result = SFC.calculate_structure_function( - SFT.S2SFType(), - x, u, bins; - backend=CB.SerialBackend(), - show_progress=true -) - -println("Structure Function values: ", result.values) -``` - -**2. Pre-allocated In-place API:** - -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -x = (randn(1000), randn(1000)) -u = (randn(1000), randn(1000)) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] - -# Pre-allocate output arrays -n_bins = length(bins) -sums = zeros(Float64, n_bins) -counts = zeros(Float64, n_bins) - -# Compute in-place (accumulates directly into provided arrays) -SFC.calculate_structure_function!( - sums, counts, SFT.S2SFType(), - x, u, bins; - backend=CB.SerialBackend() -) -``` - -### Performance Notes -- O(N²) complexity; for N=1M, expect ~1 sec -- Mutating `calculate_structure_function!` completely avoids allocating temporary arrays, making it ideal for temporal loops. - ---- - -## ThreadedBackend - -### Definition -Multi-threaded execution using OhMyThreads.jl. Distributes pairwise calculations across `Threads.nthreads()` worker threads. - -### When to Use -- ✅ **Medium datasets**: 10M–500M points -- ✅ **Shared-memory systems**: Single workstation, server -- ✅ **Quick turnaround**: Faster than serial, no cluster setup -- ✅ **Memory-constrained**: All threads can access same data - -### When NOT to Use -- ❌ Only 1 thread available: Falls back to serial (no benefit) -- ❌ Very large data (>500M): GPU/Distributed faster -- ❌ Cluster environment: Use DistributedBackend instead - -### Requirements - -```toml -# Add to Project.toml if not present -[extras] -OhMyThreads = "67456a42-ebe4-4781-8ad1-67f7eda8d8f7" -``` - -### Examples - -**1. Allocating API:** - -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -N = 50_000 -x = (randn(N), randn(N)) -u = (randn(N), randn(N)) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] - -result = SFC.calculate_structure_function( - SFT.L2SFType(), - x, u, bins; - backend=CB.ThreadedBackend(), - show_progress=true -) -``` - -**2. Pre-allocated In-place API:** +The backend types come from `ComputationalBackends`: ```julia +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT -N = 50_000 -x = (randn(N), randn(N)) -u = (randn(N), randn(N)) -bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] +x = rand(2, 50_000) .* 100.0 # (D, N) coordinates +u = randn(2, 50_000) # (D, N) velocities +bins = range(0.0, 20.0; length = 41) # a range is wrapped as LinearBinEdges, O(1) digitizing -# Pre-allocate output arrays -n_bins = length(bins) -sums = zeros(Float64, n_bins) -counts = zeros(Float64, n_bins) - -# Compute in-place (accumulates directly into provided arrays) -SFC.calculate_structure_function!( - sums, counts, SFT.L2SFType(), - x, u, bins; - backend=CB.ThreadedBackend() -) +SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.SerialBackend()) +SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.ThreadedBackend()) +SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins) # AutoBackend() ``` -### Performance & Memory Efficiency - -The modern mutating threaded backend (`threaded_calculate_structure_function!`) utilizes a **chunked reduction** strategy via `OhMyThreads.chunks` to divide point indexes into exactly `nthreads()` sub-ranges. - -* **Chunked Workspaces**: Each task/thread allocates exactly **one local buffer pair** for its entire chunk (rather than per-point). -* **Memory Scaling**: This reduces the number of thread-local heap allocations to exactly **$O(n_{\text{threads}})$**, compared to the highly wasteful **$O(N_{\text{points}})$** allocation pattern in naive map-reduce implementations. -* **Cache Locality**: This optimization maximizes L1/L2 cache locality while maintaining complete thread safety and task-migration protection. - -### Thread Safety - -ThreadedBackend uses **thread-local reduction buffers** to avoid race conditions: -- Each task computes on its own local chunk workspace. -- The results are folded together thread-safely using a parallel tree reduction. -- No global locks or atomic conflicts are triggered, maximizing performance. +## In place ---- - -## DistributedBackend - -### Definition -Multi-process execution using Distributed.jl. Distributes work across multiple Julia processes, potentially on different compute nodes. - -### When to Use -- ✅ **Very large data**: >500M points -- ✅ **Cluster environments**: HPC, cloud, multiple machines -- ✅ **Limited per-node memory**: Distribute data across nodes -- ✅ **Need fault tolerance**: Can add checkpointing - -### When NOT to Use -- ❌ Shared-memory system with <10 cores: ThreadedBackend faster -- ❌ Interactive/exploratory work: Higher latency -- ❌ Small data: Communication overhead kills performance - -### Setup +Every entry has a mutating form that accumulates into caller-owned buffers, for loops over time +steps or for adding partial results across processes: ```julia -using StructureFunctions -using Distributed - -# Start 4 worker processes (can be on different machines) -addprocs(4) - -# Ensure StructureFunctions is loaded on all workers -@everywhere using StructureFunctions - -# Large dataset (distributed across RAM) -N = 1_000_000_000 # 1 billion points -x = randn(N, 2) -u = randn(N, 2) - -backend = DistributedBackend() -bins = 10:10:5000 - -@time result = calculate_structure_function( - SecondOrderStructureFunctionType(), - x, u, bins; - backend=backend, - verbose=true -) - -# Clean up -rmprocs(workers()) -``` - -### Cluster Job Submission - -Example SLURM submission script: - -```bash -#!/bin/bash -#SBATCH --nodes=4 # Request 4 nodes -#SBATCH --cpus-per-task=8 # 8 CPUs per node -#SBATCH --time=01:00:00 # 1 hour - -export JULIA_NUM_THREADS=8 # Let each process use 8 threads - -srun julia -p $((${SLURM_NNODES} * ${SLURM_CPUS_PER_TASK})) compute_sf.jl -``` - -### Performance Notes -- Communication overhead: ~50–200 ms per calculation (one-time cost) -- Scales nearly linearly with process count (for large enough problems) -- Best when N >> communication cost (i.e., N > 100M) - ---- - -## GPUBackend - -### Definition -GPU-accelerated computation using KernelAbstractions.jl. Production kernels live in -`StructureFunctionsKernelAbstractionsExt` (tiled pair histograms, UInt32 counts). See **[gpu.md](gpu.md)** -for workspace reuse, slice batches, testing tiers, and benchmark regeneration. - -### When to Use -- ✅ **Large datasets**: roughly **few×10³ points and up** (see committed GPU scaling JSON) -- ✅ **GPUs available**: NVIDIA A100, RTX 4090, AMD MI200, etc. -- ✅ **Repeated calls or time series**: `GPUSFWorkspace` and `calculate_structure_function_batch!` -- ✅ **Research clusters**: Many HPC centers provide GPUs - -### When NOT to Use -- ❌ No GPU: `KA.CPU()` is slower than `ThreadedBackend` -- ❌ Data doesn't fit on GPU memory -- ❌ Very small N: CPU threading wins - -### Requirements - -```toml -[weakdeps] -KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" - -# Plus one of: CUDA.jl, AMDGPU.jl, Metal.jl -``` - -### Example: single snapshot + workspace - -```julia -using StructureFunctions: StructureFunctions as SF, Calculations as SFC -using KernelAbstractions: KernelAbstractions as KA -using CUDA: CUDA - -backend = CUDA.CUDABackend() -N = 20_000 -FT = Float32 -x = CUDA.CuArray{FT}(rand(FT, 3, N)) -u = CUDA.CuArray{FT}(rand(FT, 3, N)) -bins = collect(FT, range(0.0f0, 1.5f0; length = 21)) -sft = SF.LongitudinalSecondOrderStructureFunctionType() - -ws = SFC.GPUSFWorkspace(backend, bins) -result = SFC.gpu_calculate_structure_function( - sft, backend, x, u, bins; workspace = ws, -) # returns a StructureFunctionSumsAndCounts (raw sums + counts) -SFC.release!(ws) -``` - -### Example: time-slice batch `(N_dims, N, T)` - -```julia -T = 100 -x_batch = CUDA.CuArray{FT}(rand(FT, 3, N, T)) -u_batch = CUDA.CuArray{FT}(rand(FT, 3, N, T)) -sums = zeros(FT, length(bins) - 1, T) -counts = zeros(UInt32, length(bins) - 1, T) -SFC.gpu_calculate_structure_function_batch!( - sums, counts, sft, backend, x_batch, u_batch, bins; workspace = ws, -) -``` - -### Performance - -Committed timings: `gpu/benchmark_results/assets_latest.json` and README GPU figures. -Regenerate on a GPU allocation with `julia --project=gpu gpu/collect_benchmark_assets.jl`. -Doc assets measure **problem-size scaling** (1 GPU vs **serial CPU**, sweep N) and -**slice-batch scaling** (sweep T) — same bins/SF as -[`benchmark/scaling_config.jl`](../benchmark/scaling_config.jl). This is not multi-GPU -strong/weak scaling; see [`gpu/collect_multi_gpu_scaling.jl`](../gpu/collect_multi_gpu_scaling.jl). - -### Testing - -| Tier | Command | -|------|---------| -| Default CI | `Pkg.test()` — `KA.CPU()` parity only | -| CUDA smoke | `julia --project=gpu gpu/runtests.jl` — on GPU allocation | - -See [gpu.md — Testing tiers](gpu.md#testing-tiers). - -### Kernel Details - -GPU kernels use tiled upper-triangle pair loops with block-local UInt32 histograms, -then merge to global bins. See [`docs/gpu.md`](gpu.md) for supported routes and -CUDA validation commands. - ---- - -## AutoBackend - -### Definition -Automatically selects the best backend based on available resources: -1. If `Distributed.nworkers() > 1` → DistributedBackend -2. Else if `Threads.nthreads() > 1` → ThreadedBackend -3. Else → SerialBackend - -### When to Use -- ✅ **Generic libraries**: Let code adapt to environment -- ✅ **Unknown deployment**: Works on laptop, cluster, or cloud -- ✅ **Single shared script**: No backend changes needed -- ✅ **Production pipelines**: Automatic resource utilization - -### Example - -```julia -using StructureFunctions - -# Same code runs on laptop (serial), workstation (threaded), -# or cluster (distributed) without changes! - -x = randn(50_000_000, 2) -u = randn(50_000_000, 2) -bins = 10:10:500 - -result = calculate_structure_function( - SecondOrderStructureFunctionType(), - x, u, bins; - backend=AutoBackend(), # Default—chooses best option - show_progress=true -) -``` - -### Algorithm - -```julia -function select_backend() - if nworkers() > 1 - return DistributedBackend() - elseif Threads.nthreads() > 1 - return ThreadedBackend() - else - return SerialBackend() - end -end -``` - -### Notes -- Default behavior (no `backend` kwarg) also uses AutoBackend -- Detection is fast (~1 ms) -- Users can override with explicit backend if needed - ---- - -## Performance Tuning - -### CPU performance tips (important) - -- **Use `LinearBinEdges`/`LogBinEdges`, not a plain `Vector` of edges.** Digitizing each of the - O(N²) pairs is on the hot path; the wrapped edge types use an O(1) FMA lookup while a plain - `Vector` falls back to binary search. For point-field 1D this is ~**3.8×** end-to-end. Pass a - `range` (auto-wrapped to `LinearBinEdges`) or wrap explicitly — never `collect(range(...))`. -- **Batched inputs are fastest by far.** The batch paths (velocity `u` with trailing - axes; positions fixed `(D,N)` or batched) are `Val{D}`-specialized and SIMD-vectorized over - the batch axis — multiple Gpair/s. For repeated calls on huge batches you can pass - `BatchLeading(u)` (data already stored `(B, D, N)`) to skip the internal transpose. -- **Threaded throughput saturates near one socket.** On a 2-socket box the batch threaded path - is memory-bandwidth-bound and plateaus around the per-socket core count (more threads don't - help). Set **`JULIA_EXCLUSIVE=1`** (built-in thread pinning) for ~**+25%**. To scale *past* one - socket, use the hybrid backend below (one process per socket). -- **Hybrid distributed + threaded** via `DistributedBackend(ThreadedBackend())`: each worker - threads over its share. With one worker pinned per NUMA node - (`addprocs(2; exeflags="-t 24"); numactl --membind`), each process keeps its data socket-local, - beating the single-socket bandwidth ceiling of pure threading. - -### Choice Decision Tree - -``` -Data size? -├─ < 10M → SerialBackend (or ThreadedBackend if multi-core) -├─ 10M–500M → ThreadedBackend (or AutoBackend to auto-select) -├─ 500M–1B → DistributedBackend (or GPUBackend if GPU available) -└─ > 1B → GPUBackend (or DistributedBackend if no GPU) -``` - -### Memory Considerations - -| Backend | Memory per Point (approx) | Total for 1B | -|---------|--------------------------|-------------| -| Serial | 20 bytes (buffers only) | 20 GB | -| Threaded | 20 bytes (shared data) | 20 GB | -| Distributed | 20 bytes (per node) | 20 GB / N_nodes | -| GPU | 8 bytes (Float32) | 8 GB | - -### Thread/Process Count Tuning - -**ThreadedBackend**: Use `Threads.nthreads() = CPU_count - 1` to leave resources for OS - -```bash -# Start Julia with specific thread count -JULIA_NUM_THREADS=7 julia script.jl # On 8-core machine -``` - -**DistributedBackend**: Tune `addprocs(N)` based on cluster resources - -```julia -# Rule of thumb: N ~= (total_cores / 2) for interactive work -# N ~= total_cores for batch jobs -addprocs(32) # On 64-core system for batch -``` - -### Optimizing Bin Edges (AbstractBinEdges) - -For datasets with $N \ge 2000$ points, lookups inside the distance bins become the primary CPU bottleneck, often taking over 50% of the total runtime. This is because a standard sorted array uses $O(\log B)$ binary search logic (`searchsortedfirst`) which triggers branch mispredictions and L1/L2 cache misses under millions of pairwise evaluations. - -You can bypass this bottleneck by wrapping your bin definitions in custom `AbstractBinEdges` types: - -1. **`LinearBinEdges`** (for uniformly-spaced bins): Uses Fused Multiply-Add (FMA) math to compute indexes directly in $O(1)$ time, yielding a **15x+ lookup speedup** (~3 ns vs ~46 ns). -2. **`LogBinEdges`** (for log-spaced bins): Extracts floating-point exponents directly from the IEEE 754 representation (bitwise shifts/masks) and runs a precomputed lookup table, bypassing the expensive `log(x)` CPU instruction to achieve a **5x+ lookup speedup** (~5-8 ns vs ~39 ns). - -#### Usage Example -To leverage this optimization in single-pass calculations, wrap your raw bin vector before invoking the calculation: - -```julia -using StructureFunctions: Calculations as SFC -using StructureFunctions: LogBinEdges - -# Raw geometric boundaries -raw_bins = collect(exp.(range(log(0.01), log(10.0), length=51))) - -# Wrap log bins for O(1) exponent extraction lookup table search -distance_bins = LogBinEdges(raw_bins) - -# Bypasses binary search bottleneck completely -results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.ThreadedBackend()) -``` - -### Profiling - -Use `@time` or `@profile` to measure: - -```julia -@time result = calculate_structure_function(...) - -# For detailed timing: -using ProfilingTools -@profile calculate_structure_function(...) - -# Generate flame graph -ProfileCanvas.show() -``` - ---- - -## Related Topics - -- [Theory](theory.md): What structure functions represent -- [Architecture](architecture.md): Internal design and dispatch -- [Examples](../examples/README.md): Complete worked examples +sums = zeros(Float64, length(bins) - 1) +counts = zeros(UInt32, length(bins) - 1) +SFC.calculate_structure_function!(sums, counts, SFT.L2SFType(), x, u, bins; backend = CB.ThreadedBackend()) +``` + +The mutating entries add into the buffers they are given; zero them first. The count element type +must hold the worst-case pair count `N(N−1)/2` (`UInt32` up to `N = 92 682`), and weighted results +take a floating-point count type. + +## What each backend does + +**Serial.** Flat two- and three-dimensional point lists take a SIMD compute/scatter kernel over +blocked pair tiles: the pair distances and operator values of a block are computed in a vectorised +loop and scattered into the histogram in a scalar one. When the last bin edge bounds the separations +of interest, cells beyond it are never enumerated (`AutoCulling()`, the default; `AlwaysCulling()` +insists and errors where culling is not implemented; `NoCulling()` sweeps every pair). Curved geometry +takes the scalar per-point kernel through the pair frame; one-dimensional lists take the sorted line +route. + +**Threaded.** The outer index is split round-robin over tasks — work for index `i` is `N − i`, so a +contiguous split would skew the load by the thread count — each task accumulates into private +histograms, and the partials are added. Gridded sweeps and transforms split slab pairs (or the lags of +a single slab) across tasks the same way. Throughput saturates near one socket's memory bandwidth on +the batched paths; `JULIA_EXCLUSIVE=1` pins threads. + +**Distributed.** Each worker receives a balanced share of the outer index (`w:k:N`) and computes its +partial sums and counts with the serial kernel — or the threaded one under +`DistributedBackend(ThreadedBackend())`, one process per NUMA node being the way past a single +socket's bandwidth. The partials are reduced on the caller. + +**GPU.** See [GPU acceleration](gpu.md). One thread per point walks its partners with block-local +histograms; the gridded transform engine takes its forward transforms through the device's +`AbstractFFTs` implementation and bins every lag of every slab pair in one kernel. + +## Choosing + +- Under a few thousand points, or for a check, the serial backend. +- Otherwise the threaded backend on one node, which is what `AutoBackend()` picks with + `julia -t N` and `using OhMyThreads`. +- A GPU from a few thousand points up when the data fit in device memory; the gridded transform on a + device from about a million cells. +- Several nodes: the distributed backend, threaded inside each worker. +- On a grid, prefer the transform (`FastFourierTransformSpectralBackend()`) to any pair loop: it is + exact and its cost does not grow with the number of pairs. `AutoSpectralBackend()` costs the two + gridded algorithms and takes the cheaper. + +## Bin edges on the hot path + +Digitizing each of the `O(N²)` pairs is the inner loop. Pass a `range` (wrapped as `LinearBinEdges`) +or `LogBinEdges(edges)` for `O(1)` digitizing by a fused multiply-add or an exponent lookup; a plain +`Vector` of edges falls back to binary search. See [Binning Internals](uniform_bin_digitize.md). + +## Related pages + +- [Architecture](architecture.md) — how a call becomes a kernel. +- [Extensions](extensions.md) — which package each backend needs. diff --git a/docs/src/extensions.md b/docs/src/extensions.md index 1dfbcff..0b91a10 100644 --- a/docs/src/extensions.md +++ b/docs/src/extensions.md @@ -1,85 +1,77 @@ # Extensions -StructureFunctions.jl keeps optional integrations behind Julia package extensions. The core package should stay focused on array-based structure-function calculations; extensions only add execution backends or visualization helpers. - -## Available Extensions - -### OhMyThreads - -Loading `OhMyThreads.jl` activates threaded CPU methods used by `ThreadedBackend()`. +The core package computes structure functions of arrays and multi-fields on the serial backend +and depends on nothing but `ComputationalBackends`, `Distances`, `LinearAlgebra`, `ProgressMeter`, +`SpectralBackends` and `StaticArrays`. Everything else — parallel execution, transforms, grids, +spectral providers, fits — is a package extension that loads when its trigger packages are loaded. A +method that needs an extension which is not loaded throws an `ArgumentError` naming the package to +load; nothing falls back silently. + +The algorithm tags — `AutoSpectralBackend()`, `DirectSumSpectralBackend()`, +`FastFourierTransformSpectralBackend()`, `NUFSHTSpectralBackend()` and the non-uniform FFT tags — come +from `SpectralBackends`, a dependency, so they are always available (also as +`StructureFunctions.SpectralBackends`); the two provider-specific non-uniform FFT tags, +`NonuniformFFTsSpectralBackend(; tolerance)` and `FINUFFTSpectralBackend(; tolerance)`, are this +package's own. A tag whose transform is not loaded refuses by name. + +| Extension | Load | Adds | +|---|---|---| +| `StructureFunctionsOhMyThreadsExt` | `using OhMyThreads` | `ThreadedBackend()` on every CPU path: point lists, multi-fields, gridded sweeps and transforms, tensors, the sorted line route | +| `StructureFunctionsDistributedExt` | `using Distributed` | `DistributedBackend()` for point lists, multi-fields and tensors across worker processes | +| `StructureFunctionsMPIExt` | `using MPI` | the MPI backend for point lists | +| `StructureFunctionsKernelAbstractionsExt` | `using KernelAbstractions` | `GPUBackend(device)` kernels: point lists, joint histograms, single-pass invariants, batches over auxiliary axes, tensors, multi-fields; `KernelAbstractions.CPU()` runs them on the host | +| `StructureFunctionsCUDAExt` | `using CUDA` with `KernelAbstractions` | CUDA-specific launch configuration and shared-memory routes for the device kernels | +| `StructureFunctionsAbstractFFTsExt` | `using FFTW` (any `AbstractFFTs` implementation) | the transform engine: every polynomial operator on every separable schedule, masks, weights, joint histograms over angle, moment tensors, `gridded_spectrum`, and the `Auto` cost model | +| `StructureFunctionsAbstractFFTsKernelAbstractionsExt` | the one above with `KernelAbstractions` | the transform engine on a device: monomial transforms through the device's `AbstractFFTs` and one lag kernel for the binning | +| `StructureFunctionsNonuniformFFTsExt` | `using NonuniformFFTs` | the NonuniformFFTs provider of the soft-binned route for scattered points on a `ScatteredModesSchedule` (`NonuniformFFTsSpectralBackend`): type-1 non-uniform FFTs of the masked, weighted monomials | +| `StructureFunctionsNonuniformFFTsKernelAbstractionsExt` | the one above with `KernelAbstractions` | the same transforms on the device the points live on | +| `StructureFunctionsFINUFFTExt` | `using FINUFFT` | the FINUFFT provider of the same route (`FINUFFTSpectralBackend`), two real monomials per complex transform in one batched plan | +| `StructureFunctionsFINUFFTKernelAbstractionsExt` | the one above with `KernelAbstractions` (and `CUDA`) | cuFINUFFT for points on a CUDA device | +| `StructureFunctionsNUFSHTExt` | `using NUFSHT` | the fast spherical harmonic pseudo-coefficients behind the harmonic route on `HarmonicNodes` and `harmonic_spectra` | +| `StructureFunctionsFlowGeometriesExt` | `using FlowGeometries` | the grid entries: `calculate_structure_function(sf, grid, u, bins[, spectral_backend]; …)`, `calculate_structure_function_tensor(order, grid, …)`, `cell_measure(grid)`, routing a grid's axis types to the uniform, rectilinear, zonal or scattered schedule | +| `StructureFunctionsBesselsExt` | `using Bessels` | the Bessel functions `J₀`–`J₃`: the two-dimensional isotropic kernel, the flux relations, the Helmholtz spectra and forward models | +| `StructureFunctionsLsqFitExt` | `using LsqFit` | the bounded Levenberg–Marquardt fit behind `SegmentedPowerLaw` | + +## Examples + +Threads: ```julia -using StructureFunctions +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT +using ComputationalBackends: ComputationalBackends as CB using OhMyThreads -result = calculate_structure_function(sf, x, u, bins; backend = ThreadedBackend()) -``` - -### Distributed - -Loading `Distributed` activates the distributed CPU methods used by `DistributedBackend()`. - -```julia -using StructureFunctions -using Distributed - -addprocs(4) -result = calculate_structure_function(sf, x, u, bins; backend = DistributedBackend()) -``` - -### KernelAbstractions - -Loading `KernelAbstractions.jl` activates GPU and KA.CPU methods used by `GPUBackend`. - -```julia -using StructureFunctions -using KernelAbstractions - -backend = GPUBackend(KernelAbstractions.CPU()) -result = calculate_structure_function(sf, x, u, bins; backend) +res = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.ThreadedBackend()) ``` -Use CUDA.jl or another KernelAbstractions backend package to run on actual accelerator hardware. - -### CairoMakie - -Loading `CairoMakie.jl` activates plotting helpers, if those helpers are used by downstream code. +A device: ```julia -using StructureFunctions -using CairoMakie +using KernelAbstractions, CUDA +res = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.GPUBackend(CUDA.CUDABackend())) ``` -## Not Provided +`CB.GPUBackend(KernelAbstractions.CPU())` runs the same kernels on the host, which is how the test +suite covers them without a device. -StructureFunctions.jl does not provide file-format loaders. Pass arrays directly to the calculation APIs: +The transform on a grid: ```julia -calculate_structure_function(sf, x, u, bins) +using FFTW, FlowGeometries +using SpectralBackends: SpectralBackends as SB +sf = calculate_structure_function(SFT.L3SFType(), grid, u, bins, SB.FastFourierTransformSpectralBackend()) ``` -Application-specific I/O, preprocessing, and metadata handling should live outside this package. - -## Project.toml Entries +`SB.AutoSpectralBackend()` costs the transform and the direct sweep and takes the cheaper; the direct +sweep is the default when no tag is given. -The package currently declares only the optional dependencies needed by the remaining extensions: +## Not provided -```toml -[weakdeps] -CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" -Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" -KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" -OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" - -[extensions] -StructureFunctionsCairoMakieExt = ["CairoMakie"] -StructureFunctionsDistributedExt = ["Distributed"] -StructureFunctionsKernelAbstractionsExt = ["KernelAbstractions"] -StructureFunctionsOhMyThreadsExt = ["OhMyThreads"] -``` +The package reads arrays, multi-fields and `FlowGeometries` grids. File formats, preprocessing and +metadata belong to the caller. -## Related Topics +## Related pages - [Backends](backends.md) -- [GPU](gpu.md) +- [GPU acceleration](gpu.md) - [Architecture](architecture.md) diff --git a/docs/src/gpu.md b/docs/src/gpu.md index 0016b19..9604e76 100644 --- a/docs/src/gpu.md +++ b/docs/src/gpu.md @@ -1,211 +1,160 @@ -# GPU acceleration guide +# GPU acceleration -StructureFunctions.jl provides GPU structure-function kernels via -[`StructureFunctionsKernelAbstractionsExt`](@ref) (loaded when `KernelAbstractions.jl` is available). -This guide covers production APIs: single snapshots, workspace reuse, and time-slice batches. +The device kernels live in the `StructureFunctionsKernelAbstractionsExt` extension (loaded with +`using KernelAbstractions`); `using CUDA` adds the CUDA launch configuration. Every device route is +also run on `KernelAbstractions.CPU()`, which executes the same kernel source on the host and is how +the default test suite covers the kernels without a device. CUDA is the tested hardware. -For backend selection across serial / threaded / distributed / GPU, see [backends.md](backends.md). -For CUDA validation and SLURM benchmark scripts, see [`gpu/README.md`](../gpu/README.md). +For backend selection across serial / threaded / distributed / GPU see [Backends](backends.md); the +CUDA validation and benchmark scripts are in the repository's +[`gpu/`](https://github.com/jbphyswx/StructureFunctions.jl/tree/main/gpu) directory. ## When to use the GPU -- **Problem size:** GPU pair histograms pay off when `N` is roughly **few×10³ and up** - (exact crossover depends on hardware; see [benchmark figures](#benchmarks--figures)). -- **Memory:** Device arrays use layout `(N_dims, N_points)` or `(N_dims, N_points, T)` for batches. - Prefer **Float32** on GPU for bandwidth; Float64 is supported but often much slower. -- **Not a drop-in speedup on CPU:** Without a GPU, `KA.CPU()` runs the same kernels on CPU and is - slower than `ThreadedBackend()`. +- **Problem size.** Pair histograms pay off from a few thousand points up; the crossover depends on + the hardware. Below it the threaded CPU backend wins. +- **Memory.** Device arrays use the layout `(D, N)` or `(D, N, T)` for batches. `Float32` is faster on + the device; `Float64` is supported and is what the parity tests compare. +- **Not a drop-in speedup on the CPU.** Without a GPU, `KA.CPU()` runs the same kernels on the host + and is slower than `ThreadedBackend()`. -## Single snapshot +## Point lists ```julia -using StructureFunctions: StructureFunctions as SF, Calculations as SFC -using KernelAbstractions: KernelAbstractions as KA -using CUDA: CUDA - -backend = CUDA.functional() ? CUDA.CUDABackend() : KA.CPU() -N = 20_000 -FT = Float32 -x = CUDA.functional() ? CUDA.CuArray{FT}(rand(FT, 3, N)) : rand(FT, 3, N) -u = CUDA.functional() ? CUDA.CuArray{FT}(rand(FT, 3, N)) : rand(FT, 3, N) -bins = collect(FT, range(0.0f0, 1.5f0; length = 21)) -sft = SF.LongitudinalSecondOrderStructureFunctionType() - -result = SFC.gpu_calculate_structure_function( - sft, backend, x, u, bins, -) # returns a StructureFunctionSumsAndCounts (raw sums + counts) +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT +using ComputationalBackends: ComputationalBackends as CB +using KernelAbstractions, CUDA + +x = CUDA.CuArray{Float32}(rand(Float32, 3, 20_000)) +u = CUDA.CuArray{Float32}(rand(Float32, 3, 20_000)) +bins = collect(Float32, range(0.0f0, 1.5f0; length = 21)) + +res = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.GPUBackend(CUDA.CUDABackend())) ``` -`distance_bins` must have the **same element type** as `x` and `u` (e.g. `Float32` fields → -`collect(Float32, edges)`). The GPU API does not cast bin edges silently. +`distance_bins` must have the element type of `x` and `u`; the device API casts nothing silently. +The joint value-binned histogram (`value_bins`), the six single-pass invariants and the batches over +auxiliary axes take the same `backend` keyword. ### `GPUSFWorkspace` — reuse device histogram buffers -Repeated calls with the same bin layout should reuse a workspace to avoid reallocating -device histogram buffers each launch (~10–15% end-to-end win at `N=20k` on A100): +Repeated calls with one bin layout reuse a workspace, which avoids reallocating the device histogram +buffers on every launch: ```julia -ws = SFC.GPUSFWorkspace(backend, bins) +ws = SFC.GPUSFWorkspace(CUDA.CUDABackend(), bins) for _ in 1:10 - SFC.gpu_calculate_structure_function( - sft, backend, x, u, bins; workspace = ws, - ) + SFC.gpu_calculate_structure_function(SFT.L2SFType(), CUDA.CUDABackend(), x, u, bins; workspace = ws) end -SFC.release!(ws) # optional explicit free +SFC.release!(ws) ``` -## Time series — slice batch API +### Time series — the batch drivers -For `T` snapshots, stack data as **`(N_dims, N_points, T)`**, upload once, and call the slice driver: +For `T` snapshots stack the data as `(D, N, T)`, upload once and call the batch driver, which keeps the +batch on the device and synchronises once: ```julia -T = 100 -x_batch = rand(FT, 3, N, T) # host or CuArray -u_batch = rand(FT, 3, N, T) - -sums = zeros(FT, length(bins) - 1, T) +x_batch = rand(Float32, 3, N, T) +u_batch = rand(Float32, 3, N, T) +sums = zeros(Float32, length(bins) - 1, T) counts = zeros(UInt32, length(bins) - 1, T) -ws = SFC.GPUSFWorkspace(backend, bins) - -SFC.gpu_calculate_structure_function_batch!( - sums, counts, sft, backend, x_batch, u_batch, bins; workspace = ws, -) +SFC.calculate_structure_function_batch!(sums, counts, SFT.L2SFType(), x_batch, u_batch, bins; + backend = CB.GPUBackend(CUDA.CUDABackend())) ``` -**Avoid** a naive loop that uploads a host slice each `t` — that pays H2D + allocation every step. -The slice driver keeps the batch on device, reuses the workspace, and performs one final sync. +The batch entries — `calculate_structure_function_batch!`, `calculate_structure_function_2d_batch!`, +`calculate_structure_functions_single_pass_batch!`, `calculate_structure_functions_single_pass_2d_batch!` — +dispatch on the backend; the CPU backends run them too. -Public stubs with backend dispatch: +### Route table for point lists -- `calculate_structure_function_batch!` -- `calculate_structure_function_2d_batch!` -- `calculate_structure_functions_single_pass_batch!` (GPU-only for now) -- `calculate_structure_functions_single_pass_2d!` — six `(dist × value)` histograms; GPU HTP-EJ when eligible +| call | shapes | `D` | bins | device route | +|---|---|---|---|---| +| `calculate_structure_function(sf, x, u, bins; backend)` | `(D, N)` | 2, 3 | linear, log, general | tiled pair blocks with a block-local histogram | +| shared positions | `x::(D, N)`, `u::(D, N, aux...)` | 2 (fused), any | linear for the fused route | fixed-position batch kernels | +| varying positions | `x, u::(D, N, aux...)` | 2 (fused), any | linear for the fused route | varying-position batch kernels | +| `calculate_structure_function(sf, x, u, bins, value_bins; backend)` | `(2, N)` or batches | 2 | typed or vector value bins | shared-memory joint histogram when it fits, global atomics otherwise | +| `calculate_structure_functions_single_pass(x, u, bins; backend)` | `(D, N)` or batches | 2, 3 | linear, log, general | tiled six-row histogram | +| `calculate_structure_functions_single_pass_2d(x, u, bins, value_bins; backend)` | `(D, N)` or batches | 2, 3 | typed or vector value bins | shared, type-plane or direct strategy, frozen when the workspace is built | +| `calculate_structure_function_tensor(order, x, u, bins; backend)` | `(D, N)` or shared positions | flat and spherical | any | one thread per point, global atomics per tensor component (orders 2 and 3) | -## Production route table +`D = size(u, 1)` is the velocity width and `N = size(x, 2) = size(u, 2)`; trailing axes are +independent auxiliary calculations. -| Public call | Shapes | Dimensions | Bin support | GPU route | -|-------------|--------|------------|-------------|-----------| -| `calculate_structure_function(sf, x, u, bins; backend=GPUBackend(...))` | `(D,N)` | `D=2,3` | linear, log, general vectors | tiled128 1D histogram route; explicit error for unsupported `D` | -| same with shared positions | `x::(D,N)`, `u::(D,N, auxiliary...)` | currently production optimized for `D=2` auxiliary batch kernels | linear distance bins for fused batch route | fixed-position auxiliary batch route | -| same with varying positions | `x,u::(D,N, auxiliary...)` | currently production optimized for `D=2` auxiliary batch kernels | linear distance bins for fused batch route | varying-position auxiliary batch route | -| `calculate_structure_function(sf, x, u, bins, value_bins; backend=GPUBackend(...))` | `(2,N)` or auxiliary variants | `D=2` | typed and vector value-bin plans | joint 2D shared-memory route when eligible, otherwise global route | -| `calculate_structure_functions_single_pass(x, u, bins; backend=GPUBackend(...))` | `(D,N)` or auxiliary variants | `D=2,3` point fields; `D=2` optimized auxiliary batch kernels | linear/log/general point fields; linear fused batch route | tiled 2D fast path for eligible `D=2`, global fallback otherwise | -| `calculate_structure_functions_single_pass_2d(x, u, bins, value_bins; backend=GPUBackend(...))` | `(D,N)` or auxiliary variants | `D=2,3` point fields; `D=2` optimized auxiliary batch kernels | linear/log/general point fields; typed or vector value bins | HTP-EJ shared/typeplane/direct strategy for eligible `D=2`; global fallback otherwise | +## Grids: the transform engine on a device -The public shape contract is always `D = size(x, 1) = size(u, 1)`, `N = size(x, 2) = size(u, 2)`. -Trailing axes are independent auxiliary calculations; `ndims(x) == 3` is not interpreted as 3D space. +The gridded transform takes the hardware from the same `backend` keyword. With `using FFTW: FFTW` (or +another `AbstractFFTs` implementation) and `using KernelAbstractions: KernelAbstractions`, a +`GPUBackend` moves the masked, weighted monomials to the device, takes their transforms there through +the device's own `AbstractFFTs` implementation, forms every inverse column of a batch of slab pairs in +one kernel, and bins every lag of every slab pair in a second kernel with a privatized histogram. +Uniform, stretched and lat-lon grids, masks, weights, multi-fields, every polynomial order, the +joint histogram over angle and the soft-binned non-uniform FFT route run through it; the counts are +exactly the CPU engine's. -## Single-type joint 2D smem - -[`GPUSFWorkspace`](@ref) for `kind=:joint2d` defaults to exact compile-time shared histogram width -`n_dist × n_val`. Optional override: `joint2d_compile_cells=joint2d_smem_max()` or -`joint2d_smem_align256(n_dist, n_val)`. See [`gpu/GPU_2d_joint_sf_plan.md`](../gpu/GPU_2d_joint_sf_plan.md). - -## Six-invariant-type single-pass 2D (SP2D) - -Production GPU path for `calculate_structure_functions_single_pass_2d!` with typed distance bins -(`LinearBinEdges` / `LogBinEdges`) and `GPUSFWorkspace(...; kind=:single_pass_2d)`. Histogram strategy -(`:shared` / `:typeplane` / `:direct`) is frozen at workspace build from a 48 KiB shared-memory budget. +```julia +using FFTW, FlowGeometries +using SpectralBackends: SpectralBackends as SB +sf = calculate_structure_function(SFT.L3SFType(), grid, u, bins, SB.FastFourierTransformSpectralBackend(); + backend = CB.GPUBackend(CUDA.CUDABackend())) +``` -Rows are fixed to the six invariant/default quantities: +`AutoSpectralBackend()` on a device always takes the transform, since the direct lag sweep has no +device method. On an A100 the 720×360 lat-lon `L2` transform runs 28× faster than the 8-thread CPU +(`0.045 s` against `1.28 s`), and a stretched 256×128 grid 3.6× (`0.0027 s` against `0.0098 s`). -1. `S2 = |delta u|^2` -2. `L2 = delta u_L^2` -3. `T2 = |delta u_T|^2` -4. `S3 = delta u_L |delta u|^2` -5. `L3 = delta u_L^3` -6. `LT2 = delta u_L |delta u_T|^2` +A schedule with many slabs transforms many short monomials, so the *number* of operations rather than +their size sets the cost. Each monomial is built for every slab in one broadcast, the slabs are +transformed in one batch, and the spectra are laid out in the order the spectral kernel reads them, so +assembling its input is a reshape rather than a copy per spectrum. -Basis-dependent component diagnostics such as `T3SF` and `L2T1SF` are not included in default -single-pass outputs. Those require an explicit transverse-basis convention rather than the invariant -bulk six-row contract. +The binning kernel launches each slab pair over the lags that pair can reach, the same box the host +loop takes. On a lat-lon grid a parallel spans less distance the nearer it lies to a pole, so the box +over all row pairs stays as wide as the equator's however small the largest bin edge is; a schedule +that reports `uniform_lag_box` instead shares one box across every pair and is indexed by division. -- **On-chip** (`:shared`, `:typeplane`): shared histogram + joint-style flush to output (no merge). -- **Direct** (`:direct`): partitioned global accumulation + merge when even one value plane does not fit in smem. +## Single-type joint 2D shared memory -**Benchmark on GPU:** `julia --project=gpu gpu/benchmark_2d_grid_scaling.jl` -**Design, gate, perf gaps:** [`gpu/SP2D_HTP_EJ.md`](../gpu/SP2D_HTP_EJ.md) +[`GPUSFWorkspace`](@ref StructureFunctions.Calculations.GPUSFWorkspace) for `kind = :joint2d` defaults to the exact compile-time shared histogram +width `n_dist × n_val`; `joint2d_compile_cells = joint2d_smem_max()` or `joint2d_smem_align256(n_dist, +n_val)` override it. -The production gate is e2e SP2D **< 6 × joint_2d**. A naive “~2× digitize vs 1D” bound is too optimistic: -SP2D performs six value digitizations per pair and may replay the full tile schedule -`n_type_passes` times (typeplane). See the doc for a per-pair work table and future optimizations. +## Six-invariant single-pass 2D +The device path for `calculate_structure_functions_single_pass_2d!` with typed distance bins +(`LinearBinEdges` / `LogBinEdges`) and `GPUSFWorkspace(...; kind = :single_pass_2d)` picks its histogram +strategy — `:shared`, `:typeplane` or `:direct` — when the workspace is built, from a 48 KiB +shared-memory budget. The six rows are `S2`, `L2`, `T2`, `S3`, `L3`, `L1T2`; the basis-dependent +`T3` and `L2T1` are not part of the single-pass contract and take the general entries with their +transverse convention. ## Testing tiers -| Tier | Command | What it proves | -|------|---------|----------------| -| **1 — default CI** | `Pkg.test()` | Kernel math, binning, workspace reset, slice logic via **`KA.CPU()`** (same `@kernel` source, no CUDA) | -| **2 — CUDA smoke** | `julia --project=gpu gpu/runtests.jl` | Device alloc, H2D/D2H, sync, Float32 on real GPU (**skipped** if `!CUDA.functional()`) | -| **3 — benchmarks** | `julia --project=gpu gpu/benchmark_suite.jl` | Release-performance gates and timing JSON (run on GPU allocation) | - -**Important:** Tier 1 does **not** prove CUDA correctness. Always run tier 2 on a GPU node before trusting production CUDA runs. - -Tier 2 tests live in [`gpu/runtests.jl`](../gpu/runtests.jl) and are **not** included in [`test/runtests.jl`](../test/runtests.jl). - -## Benchmarks & figures +| tier | command | what it proves | +|---|---|---| +| default suite | `julia --project=test test/runtests.jl` | kernel arithmetic, binning, workspaces and slices on `KA.CPU()`, the same kernel source without CUDA | +| CUDA | `julia --project=gpu gpu/runtests.jl` | every CUDA suite: point kernels, workspaces, 1-D and 2-D parity, end-to-end 2-D, slices, and the gridded engine's parity table (skipped when `!CUDA.functional()`) | +| gridded parity table | `sbatch gpu/run_cuda_gridded_parity.sh` | counts exact and sums to round-off against the 8-thread CPU on every schedule, the non-uniform FFT route and the tensor kernel, with timings | +| benchmarks | `julia --project=gpu gpu/benchmark_suite.jl` | release-performance gates and timing JSON | -Shared bin layout and SF type with CPU benchmarks ([`benchmark/scaling_config.jl`](../benchmark/scaling_config.jl)). +`KA.CPU()` does not prove CUDA correctness: five device-only compile faults (a runtime-length tuple, a +boxed capture, a runtime-value branch, an `@index` inside a branch, a formatted throw message) and two +CUDA library accuracy issues were found only on the device, which is why the CUDA tier exists. -| Study | Script | What varies | What is fixed | -|-------|--------|-------------|---------------| -| **CPU strong scaling** | [`benchmark/benchmark_scaling.jl`](../benchmark/benchmark_scaling.jl) | threads | N | -| **CPU weak scaling** | same | threads + N | work/thread | -| **GPU problem-size scaling** | [`gpu/collect_benchmark_assets.jl`](../gpu/collect_benchmark_assets.jl) | N | 1 GPU, **serial CPU** | -| **GPU slice-batch scaling** | same | T (slices) | N_SLICE, 1 GPU | -| **GPU release gates** | [`gpu/benchmark_suite.jl`](../gpu/benchmark_suite.jl) | route | 1 GPU, shared bins | -| **GPU strong/weak (multi-GPU)** | [`gpu/collect_multi_gpu_scaling.jl`](../gpu/collect_multi_gpu_scaling.jl) | — | **not implemented** | +## Benchmarks and figures -Problem-size scaling is the usual name for “one device, sweep input size.” It is **not** HPC strong or weak scaling. +The GPU figures in the README are problem-size scaling — one device against the serial CPU, sweeping +`N`, and one device sweeping the slice count `T` — not strong or weak scaling. They are regenerated on a +GPU allocation with `gpu/collect_benchmark_assets.jl` followed by +`docs/generate_assets/generate_gpu_figures.jl`; the parity figure (`KA.CPU()` against serial) with +`docs/generate_assets/generate_assets.jl`. CPU thread scaling is in `benchmark/benchmark_scaling.jl`. -The GPU collector always uses **`SerialBackend`** for the CPU reference (1 logical worker), independent of `julia -t`. That keeps doc assets reproducible on any GPU allocation. **CPU thread scaling** is only in [`benchmark/benchmark_scaling.jl`](../benchmark/benchmark_scaling.jl) (strong/weak figures); readers combine those plots with the GPU problem-size figure as needed. - -The release benchmark suite is separate from docs asset generation: - -```bash -julia --project=gpu gpu/benchmark_suite.jl -``` +![GPU problem-size scaling](assets/gpu_problem_size_scaling.png) -It writes `gpu/benchmark_results/benchmark_suite_latest.json` and a timestamped copy. -The key ratios are workspace reuse, `6 * joint2D` vs SP2D, shared-position auxiliary -fusion vs explicit loops, and varying-position auxiliary fusion vs explicit loops. -`BENCH_BACKEND=kacpu` is useful only as a smoke test; CUDA runs with representative -`N` and `BATCH` are the performance signal. - -### Regenerate GPU doc assets (on GPU allocation) - -```bash -julia --project=gpu gpu/collect_benchmark_assets.jl -julia --project=docs/generate_assets docs/generate_assets/generate_gpu_figures.jl -``` - -Outputs: - -- `gpu/benchmark_results/assets_latest.json` -- `docs/src/assets/gpu_problem_size_scaling.png` -- `docs/src/assets/gpu_slice_batch_scaling.png` - -Parity figure (KA.CPU vs serial, no GPU): - -```bash -julia --project=docs/generate_assets docs/generate_assets/generate_assets.jl -``` - -Produces `docs/src/assets/sf_gpu_parity.png`. - -### Figures (from latest collector run) - -![GPU problem-size scaling](src/assets/gpu_problem_size_scaling.png) - -![GPU slice-batch scaling](src/assets/gpu_slice_batch_scaling.png) +![GPU slice-batch scaling](assets/gpu_slice_batch_scaling.png) ## Examples -- [`examples/gpu_acceleration.jl`](../examples/gpu_acceleration.jl) — single snapshot + workspace -- [`examples/gpu_time_slices.jl`](../examples/gpu_time_slices.jl) — slice batch vs naive loop (small N/T, KA.CPU route) - -## See also - -- [backends.md — GPUBackend](backends.md#gpubackend) -- [`gpu/SP2D_HTP_EJ.md`](../gpu/SP2D_HTP_EJ.md) — six-invariant-type single-pass 2D (HTP-EJ) +- [`examples/gpu_acceleration.jl`](https://github.com/jbphyswx/StructureFunctions.jl/blob/main/examples/gpu_acceleration.jl) — a single snapshot with a workspace +- [`examples/gpu_time_slices.jl`](https://github.com/jbphyswx/StructureFunctions.jl/blob/main/examples/gpu_time_slices.jl) — the slice batch against a naive loop diff --git a/docs/src/index.md b/docs/src/index.md index 9a9ec72..467fc57 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -4,61 +4,63 @@ CurrentModule = StructureFunctions # StructureFunctions.jl -**High-performance structure function calculations for turbulence and spatial correlation analysis.** - -StructureFunctions.jl computes structure functions (SFs) from scattered or gridded data, -characterizing the spatial correlations and scaling properties of turbulent / spatially-varying -fields. It is optimized for multi-dimensional data with a typed backend system supporting -**serial, threaded, distributed, and GPU** execution, and a fused **single-pass** path that -produces the six isotropic invariants (plus the Helmholtz rotational/divergent decomposition) in -one O(N²) pair pass. +**Structure functions of turbulent and spatially varying fields, on point lists, multi-fields, grids +and the sphere, with the spectra, fluxes and fits derived from them.** ## Features -- **Operators**: 1st/2nd/3rd-order; longitudinal & transverse projections in 1D/2D/3D. -- **Single pass**: six isotropic invariants `S2, L2, T2, S3, L3, L1T2` (+ `helmholtz`) in one pass. -- **2D joint binning**: distance × value histograms (`StructureFunction2DSumsAndCounts`). -- **Typed backends**: `SerialBackend`, `ThreadedBackend`, `DistributedBackend`, `GPUBackend`, `AutoBackend`. -- **Native batching**: vectorized over a trailing `(D, N, T)` axis (CPU batch-leading SoA / GPU batch kernels). -- **In-place API**: pre-allocated mutating drivers for zero-allocation loops. -- **Fast bins**: O(1) `LinearBinEdges` / `LogBinEdges` digitizers; `Float32` & `Float64` first-class. -- **Type-stable & validated**: JET / Aqua, serial≡threaded≡distributed≡GPU parity tests. +- **Operators** of any order: the longitudinal, transverse and full increments, signed transverse + components with a stated convention, scalar and mixed velocity–scalar moments, cross-field + advective moments, the whole increment moment tensor. +- **Point lists** `(D, N)` on the serial, threaded, distributed, MPI and GPU backends, with cell + culling, pair weights, joint (distance × value) and (distance × angle) histograms, the six isotropic + invariants and the Helmholtz split in one pass, and batches over auxiliary axes. +- **Grids** through FlowGeometries: uniform, stretched and lat-lon grids, masks at any order, and an + exact transform engine that computes each polynomial operator at every lag at once, on the CPU or a + device. A direct lag sweep computes the same quantity by a different route. +- **The sphere**: parallel-transported pair frames, `SphericalDistance(R)`, the zonal transform, and a + harmonic route with Legendre and Wigner-d kernels. +- **One-dimensional lists** in `O(N log N)`, and **scattered points by non-uniform FFT**, which soft + bins and is not exact. +- **Spectra** from structure functions in one, two and three dimensions and on the sphere, exact on + grids through the lag space; the Helmholtz `E`/`B` split; **fluxes** from third-order functions with + their boundary terms; **regularised fits** of spectra and fluxes with posterior covariances. +- **Exact laws**: four-fifths, four-thirds and Yaglom inversions. ## Quick start ```julia using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, LogBinEdges +using ComputationalBackends: ComputationalBackends as CB x = rand(2, 2048) .* 1.0e4 # (D, N) coordinates u = randn(2, 2048) # (D, N) velocity components bins = LogBinEdges(collect(exp10.(range(log10(50.0), log10(5.0e3); length = 41)))) -# Second-order longitudinal SF, averaged S₂(r): sf = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.AutoBackend()) -sf.distance, sf.values +sf.distance, sf.values # the bin edges and the averaged ⟨δu_L²⟩ per bin -# All six invariants (+ Helmholtz) in one pass: res = SFC.calculate_structure_functions_single_pass(x, u, bins) -res.L2, res.T2, res.helmholtz +res.L2, res.T2, res.helmholtz # all six invariants and the Helmholtz split in one pass ``` ## Where to next -- **[Theory](theory.md)** — what structure functions are and why they matter. -- **[Architecture](architecture.md)** — operator × result-container design and dispatch. -- **[Backends](backends.md)** — serial / threaded / distributed / GPU, and when to use each. -- **[GPU Acceleration](gpu.md)** — GPU kernels, batching, and `GPUSFWorkspace`. -- **[Extensions](extensions.md)** — the optional weakdep-gated integrations. -- **[Examples](examples.md)** — runnable scripts and featured snippets. -- **[API Reference](api.md)** — the complete public surface. +- [Theory](theory.md) — the definitions, conventions and relations the code implements. +- [Walkthrough](walkthrough.md) — one analysis end to end, on fields whose answers are known. +- [Architecture](architecture.md) — operator × schedule × backend, and how a call becomes a kernel. +- [Backends](backends.md) and [GPU acceleration](gpu.md) — where each calculation runs. +- [Extensions](extensions.md) — what each optional package adds. +- [Exact laws](khm.md), [Validation](validation.md), [API reference](api/operators.md). ## Installation ```julia using Pkg -Pkg.add(url = "https://github.com/jbphyswx/StructureFunctions.jl.git") +Pkg.add("StructureFunctions") ``` -Optional backends/visualization load via package extensions when you bring their trigger packages -(`OhMyThreads`, `Distributed`, `KernelAbstractions` + `CUDA`, `MPI`, `CairoMakie`); -see [Extensions](extensions.md). +The package depends on `ComputationalBackends` for the backend types; bring the trigger packages of +the [extensions](extensions.md) you need (`OhMyThreads`, `KernelAbstractions` + `CUDA`, `FFTW`, +`FlowGeometries`, `Bessels`, `NUFSHT`, `NonuniformFFTs` or `FINUFFT`, `LsqFit`). The algorithm tags come +from `SpectralBackends`, a dependency. diff --git a/docs/src/khm.md b/docs/src/khm.md new file mode 100644 index 0000000..8fc55ba --- /dev/null +++ b/docs/src/khm.md @@ -0,0 +1,44 @@ +# Exact laws (KHM) + +```@meta +CurrentModule = StructureFunctions +``` + +The Kármán–Howarth–Monin exact laws relate a third-order structure function in the inertial range to +a dissipation or flux. `StructureFunctions.KHM` inverts them on already-binned results and reports +the residual of each law. Every law is stated for one specific moment, and the laws are not +interchangeable: applying the four-fifths law to `S3SF` returns a number that is wrong by exactly +`5/3` and looks entirely reasonable. + +| law | moment | operator | relation | inversion | +|---|---|---|---|---| +| four-fifths (Kolmogorov 1941) | ``⟨δu_L³⟩`` | `L3SFType` | ``⟨δu_L³⟩ = -\tfrac{4}{5} ε r`` | [`KHM.epsilon_from_four_fifths`](@ref) | +| four-thirds | ``⟨δu_L ‖δu‖²⟩`` | `S3SFType` | ``⟨δu_L ‖δu‖²⟩ = -\tfrac{4}{3} ε r`` | [`KHM.epsilon_from_four_thirds`](@ref) | +| Yaglom | ``⟨δu_L (δθ)²⟩`` | `MixedSFType{1,0,2}` | ``⟨δu_L (δθ)²⟩ = -\tfrac{4}{3} ε_θ r`` | [`KHM.epsilon_theta_from_yaglom`](@ref) | + +```julia +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT + +res = SFC.calculate_structure_function(SFT.L3SFType(), x, u, bins) +r = SF.midpoints(res.distance) +ε = SF.KHM.epsilon_from_four_fifths(r, res.values) # one estimate per bin; flat in the inertial range +SF.KHM.four_fifths_residual(r, res.values, ε[5]) # how far each bin is from the law at that ε +``` + +The residual of the planar isotropy relation between the longitudinal and transverse second-order +functions, ``D_{TT} = D_{LL} + r\,\mathrm{d}D_{LL}/\mathrm{d}r`` in two dimensions (Lindborg 1999, +eq. 53), is [`KHM.transverse_incompressibility_residual`](@ref); on a sphere it holds only to +``O((r/R)^2)``. + +These are inertial-range relations for homogeneous isotropic turbulence with a single cascade. A +synthetic Gaussian field has no cascade and its third-order moments are consistent with zero, so the +laws have nothing to recover there; the spectral flux relations of the transforms +(`spectral_flux`, `enstrophy_flux`) and the regularised fits (`fit_flux`) are the scale-resolved +counterparts. + +## Functions + +```@autodocs +Modules = [StructureFunctions.KHM] +Private = false +``` diff --git a/docs/src/theory.md b/docs/src/theory.md index e4023f4..ffdcbc0 100644 --- a/docs/src/theory.md +++ b/docs/src/theory.md @@ -1,278 +1,294 @@ -# Theory: Structure Functions in Turbulence +# Theory -This document explains the mathematical foundation of structure functions and how they're used to characterize turbulent flows. - -## Table of Contents -- [Definition](#definition) -- [Longitudinal vs Transverse](#longitudinal-vs-transverse) -- [Order](#order) -- [Dimensional Variants](#dimensional-variants) -- [Curved Geometry: Structure Functions on a Sphere](#curved-geometry-structure-functions-on-a-sphere) -- [Kolmogorov Theory](#kolmogorov-theory) -- [References](#references) +What the package computes, in the conventions the code uses. Every formula here is one the tests hold +the code to; the [Validation](validation.md) page lists the oracle for each. ## Definition -A **structure function** measures the statistical properties of velocity differences in a turbulent flow. Formally, the nth-order structure function in 1D is: - -$$S_n(\Delta x) = \left\langle |\Delta u(\Delta x)|^n \right\rangle$$ - -where: -- $\Delta u(\Delta x) = u(x + \Delta x) - u(x)$ is the velocity increment over separation $\Delta x$ -- The angle brackets $\langle \cdot \rangle$ denote ensemble/time averaging -- $n$ is the order (typically 2, 3, or higher) - -### Physical Interpretation - -Structure functions quantify how velocity changes as you move through a turbulent medium: - -- **$S_2$ (Second-order)**: Measures the variance of velocity increments; related to the energy cascade -- **$S_3$ (Third-order)**: Directly related to the energy dissipation rate; satisfies the famous "-4/5 law" in Kolmogorov-scale turbulence -- **Higher orders**: Capture tail statistics and intermittency; used to detect coherent structures - -## Longitudinal vs Transverse - -For a point pair separated by vector $\vec{r}$, there are two natural projections of velocity differences: - -### Longitudinal Structure Function - -The velocity difference **along** the separation vector: - -$$S^L_n(r) = \left\langle ([\Delta \vec{u}(\vec{r})] \cdot \hat{r})^n \right\rangle$$ - -where $\hat{r} = \vec{r} / |\vec{r}|$ is the unit vector in the direction of separation. - -**Intuition**: Measures how velocity changes *in the direction you're moving*. - -### Transverse Structure Function - -The velocity difference **perpendicular** to the separation vector: - -$$S^T_n(r) = \left\langle ([\Delta \vec{u}(\vec{r})] \times \hat{r})^2 \right\rangle^{n/2}$$ - -**Intuition**: Measures how velocity changes *perpendicular to your direction of motion*. - -### Anisotropy - -In most real turbulent flows (e.g., stratified atmosphere, rotating fluids), longitudinal and transverse structure functions differ. The ratio $S^L_n / S^T_n$ quantifies flow **anisotropy** — deviations from isotropy. - -## Order - -### Second-Order: Energy Spectrum - -The second-order structure function is most commonly used: - -$$S_2(\Delta x) = \langle (\Delta u)^2 \rangle$$ - -In isotropic turbulence, this relates to the energy spectrum $E(k)$ via: - -$$S_2(r) = \int_0^{k_r} E(k) \sin(kr) / (kr) dk$$ - -### Third-Order: Energy Dissipation - -The third-order longitudinal structure function has special significance: - -$$S_3^L(r) = -\frac{4}{5} \varepsilon r$$ - -This **"-4/5 law"** (Kolmogorov, 1941; Landau & Lifshitz, 1987) directly relates the third-order SF to the energy dissipation rate $\varepsilon$, provided you're in the *inertial range* of turbulence. - -### Higher Orders: Intermittency - -Higher-order SFs are sensitive to **intermittency** — the non-Gaussian nature of velocity increments in real turbulence. The scaling exponents $\zeta_n$ defined by: - -$$S_n(r) \sim r^{\zeta_n}$$ - -deviate from linear scaling ($\zeta_n \neq n/3$) in intermittent flows. These anomalous exponents are studied in **multifractal analysis** of turbulence. - -## Dimensional Variants - -StructureFunctions.jl supports calculations in multiple dimensions: - -### 2D Flows +For two points ``x`` and ``x' = x + \vec r`` of a field ``u``, the **increment** is +``δu = u(x') - u(x)``. A structure function is the average of a polynomial in the increment over all +pairs whose separation ``|\vec r|`` falls in a bin, and the package's operators are those +polynomials. With ``\hat r = \vec r / |\vec r|`` the unit separation: -For 2D velocity fields $(u_x, u_y)$ in horizontal planes: -- Compute longitudinal/transverse SFs in the $(x, y)$ plane -- Study anisotropy between meridional and zonal components -- Common in meteorology (weather systems, jet streams) - -### 3D Flows - -For full 3D velocity fields $(u_x, u_y, u_z)$: -- Compute SFs along any separation vector -- Study isotropy/anisotropy in all directions -- Standard in direct numerical simulations (DNS) - -### Projected / Vector Variants - -- **Full vector SF**: Uses complete velocity difference vector -- **Projected SF**: Projects onto specific directions (e.g., vertical, meridional) -- Flexibility for analyzing anisotropic flows - -## Curved Geometry: Structure Functions on a Sphere - -Everything above assumes flat space: $\hat{r} = \vec{r}/|\vec{r}|$ is a single vector, and $\Delta\vec{u}$ -is a plain difference of two velocity vectors. On a sphere neither holds. The two points have -*different* tangent planes, so "the separation direction" is two different vectors, and subtracting -velocities that live in different tangent spaces is not defined. +| operator | value on one pair | shorthand | +|---|---|---| +| `SecondOrderStructureFunctionType` | ``‖δu‖²`` | `S2SFType` | +| `ProjectedStructureFunctionType{2,0}` | ``δu_L^2``, ``δu_L = δu · \hat r`` | `L2SFType` | +| `ProjectedStructureFunctionType{0,2}` | ``‖δu_T‖² = ‖δu‖² - δu_L^2`` | `T2SFType` | +| `ThirdOrderStructureFunctionType` | ``δu_L ‖δu‖²`` | `S3SFType` | +| `ProjectedStructureFunctionType{3,0}` | ``δu_L^3`` | `L3SFType` | +| `ProjectedStructureFunctionType{1,2}` | ``δu_L ‖δu_T‖²`` | `L1T2SFType` | +| `ProjectedStructureFunctionType{2,1}`, `{0,3}` | ``δu_L^2\, (δu·\hat n)``, ``(δu·\hat n)^3`` | `L2T1SFType`, `T3SFType` | +| `ProjectedStructureFunctionType{NL,NT}` | ``δu_L^{NL}`` times ``‖δu_T‖^{NT}`` for ``NT = 2``, ``(δu·\hat n)^{NT}`` otherwise | | +| `TransverseComponentSecondOrderStructureFunctionType`, `LongitudinalTransverseComponentThirdOrderStructureFunctionType` | ``‖δu_T‖²/(D-1)``, ``δu_L ‖δu_T‖²/(D-1)`` — per transverse component | `T2ComponentSFType`, `L1T2ComponentSFType` | +| `FullVectorStructureFunctionType{NF}` | ``‖δu‖^{NF}`` | | +| `ScalarStructureFunctionType{P}` | ``(δθ)^P`` on a scalar field | `ScalarSFType` | +| `MixedStructureFunctionType{NL,NT,P}` | ``δu_L^{NL} ‖δu_T‖^{NT} (δθ)^P`` | `MixedSFType` | +| `VectorDotStructureFunctionType(a, b)`, `ScalarDotStructureFunctionType(a, b)` | ``δu^{(a)} · δu^{(b)}``, ``δθ^{(a)}\, δθ^{(b)}`` across fields | | +| `MomentTensorOperator{P}` | the whole tensor ``δu_{i_1} ⋯ δu_{i_P}`` | | + +``δu_L`` is the **longitudinal** increment, the component along the separation, and +``‖δu_T‖² = ‖δu‖² - δu_L^2`` is the **transverse** energy, the squared norm of everything +perpendicular to it — in any dimension. + +The two readings of ``NT`` in the table differ only for ``D ≥ 3``, where the transverse plane has +more than one direction; in two dimensions ``‖δu_T‖² = (δu·\hat n)²``. They cannot be made uniform: +``‖δu_T‖^{NT}`` is a polynomial in ``δu`` only for even ``NT``, because ``‖δu_T‖²`` is one and an odd +power needs its square root, so an odd ``NT`` admits the component reading alone. ``NT = 2`` is the +energy because that is the quantity the second-order relations below are written in — the Helmholtz +split and the ``D_{LL}``/``D_{TT}`` isotropy relations all take it. The per-component form has its own +operator, `T2ComponentSFType`. + +The signed transverse component ``δu · \hat n`` that the +odd transverse operators read needs a direction ``\hat n`` perpendicular to ``\hat r``, which is a +convention: in two dimensions ``\hat n = \hat z × \hat r = (-\hat r_2, \hat r_1)``, and in three the +`CanonicalTransverseBasis` is ``\hat n = \hat z × \hat r / |\hat z × \hat r|`` continued about +``\hat x`` where ``\hat r ∥ \hat z``, with ``\hat r × \hat n`` as the second transverse direction. +`ReferenceAxisTransverseBasis(a)` is the same rule about an axis ``a`` of the caller's choosing. The +convention travels with the operator into every result, and every rule must give a first transverse +vector that is **odd** under ``\hat r ↦ -\hat r``: reading a pair from its other end flips ``δu`` and +``\hat r`` together, and the transverse component has to flip with them so that the operator's value +is the same from either end. + +That swap invariance holds for every operator above except one class. A scalar increment +``δθ = θ(x') - θ(x)`` changes sign when the pair is read backwards, so an operator odd in a scalar +increment (`ScalarSFType{3}`, `MixedSFType{1,0,1}`, …) has no value on an unordered pair without a +rule. The package reads every pair from the lower to the upper end along the first coordinate that +separates the two points — on a sphere from south to north, and along one parallel from west to +east by the shorter way — so those moments are independent of how the input happens to be ordered. +Where neither end comes first (a lag half-turning a periodic direction) the two readings are averaged +and the odd moment is zero. + +### Weights + +With one weight per point or cell, every statistic is +``\sum_{ij} w_i w_j\, \mathrm{sf}(δu_{ij}, \hat r_{ij}) / \sum_{ij} w_i w_j`` over the pairs of a bin, +and the counts become the weighted pair mass. `cell_measure(grid)` gives a grid's cell areas as +weights, which turns a lat-lon sum into an area average. + +## Second order and spectra + +For a homogeneous isotropic field in ``D`` dimensions the second-order trace and the shell spectrum +``E(k)`` (``∫_0^∞ E\,dk`` the variance) are related by + +```math +S_2(r) = 2 ∫_0^∞ E(k) \left[1 - \mathrm{kernel}_D(kr)\right] dk, \qquad +\mathrm{kernel}_1 = \cos x, \quad \mathrm{kernel}_2 = J_0(x), \quad \mathrm{kernel}_3 = \frac{\sin x}{x}, +``` + +the kernel being the angular average of ``\cos(\vec k · \vec r)``. The package inverts this in +`isotropic_spectrum` for the density ``P(k)`` over ``d^D k`` (``E = Ω_D k^{D-1} P``, `shell_spectrum`), +and the ``k = 0`` mode is not recoverable: a structure function is blind to the mean and the +variance. On a grid the same information is available **exactly** through the lag space +(`gridded_spectrum`): the transform of the unbiased autocovariance ``C(h) = σ̂² - D(h)/2`` over every +lag, with no direction averaged and no separation binned. With cells missing that is still the +exact transform of the exact structure function, equal to the complete field's spectrum in +expectation; a bounded direction gives the windowed (Blackman–Tukey) estimate on a padded lag grid, +with an optional taper. + +For a two-dimensional vector field the longitudinal and transverse functions split the spectrum into +its gradient (divergent, ``E``) and curl (rotational, ``B``) parts: + +```math +D_{LL} + D_{TT} = 2 ∫ (E_E + E_B)\,[1 - J_0(kr)]\,dk, \qquad +D_{LL} - D_{TT} = 2 ∫ (E_E - E_B)\, J_2(kr)\,dk, +``` + +inverted by `helmholtz_spectra(L2, T2, k)`. On a sphere the counterparts are Legendre and Wigner +series: ``C_l = -π ∫_0^π D(σ) P_l(\cos σ) \sin σ\, dσ`` for a scalar or the trace, and +``C^E_l ∓ C^B_l`` from ``D_{LL} ∓ D_{TT}`` through ``d^l_{1,-1}`` and ``d^l_{11}``. + +## Third order, exact laws and fluxes + +In the inertial range of homogeneous isotropic turbulence the third-order functions are linear in +``r`` with the dissipation as the slope — Kolmogorov's four-fifths law ``⟨δu_L^3⟩ = -\tfrac45 ε r``, +the four-thirds law ``⟨δu_L ‖δu‖²⟩ = -\tfrac43 ε r`` and Yaglom's law +``⟨δu_L (δθ)^2⟩ = -\tfrac43 ε_θ r``. Each is stated for one specific moment; the +[KHM](khm.md) page inverts them. + +Scale by scale, the interscale energy flux of a two-dimensional flow follows from the advective +structure function ``SF_A = ⟨δu · δ\mathcal{A}_u⟩``, ``\mathcal{A}_u = u·∇u``, without any isotropy +assumption, and — for an isotropic flow — from the third-order functions themselves, with the +boundary terms their integrations by parts leave at the largest separation ``R``: + +```math +\begin{aligned} +Π_K &= -\tfrac{K}{2} ∫_0^R SF_A\, J_1(Kr)\, dr \\ +Π_K &= -\tfrac{K^2}{4} ∫_0^R S_3\, J_2(Kr)\, dr - \tfrac{K}{4} S_3(R) J_1(KR) \\ +Π_K &= -\tfrac{K^3}{12} ∫_0^R L_3\, J_3(Kr)\, r\, dr - \tfrac{K^2}{12}\left[R\, L_3(R) J_2(KR) + \tfrac{3}{K} S_3(R) J_1(KR)\right] +\end{aligned} +``` + +with ``S_3 = ⟨δu_L‖δu‖²⟩`` and ``L_3 = ⟨δu_L^3⟩``, and the same forms for the scalar-variance and +enstrophy fluxes (`spectral_flux`, `enstrophy_flux`). The boundary terms are not small: without them +the estimate can change sign. The sign convention is positive towards small scales. + +## Exact algorithms + +### Polynomial moments on a grid by transform + +Every operator above except the odd norms is a polynomial of degree ``p`` in the increment, so its +pair sum over a lag ``h`` of a uniform grid is a contraction of the increment moment tensor + +```math +M_{c_1 ⋯ c_p}(h) = \sum_x m(x) m(x+h) \prod_{k=1}^p \left[u_{c_k}(x+h) - u_{c_k}(x)\right] + = \sum_{S ⊆ \{1..p\}} (-1)^{p-|S|}\; X\!\left[m\,μ_{S^c},\; m\,μ_S\right](h), +``` + +a signed sum of cross-correlations ``X[f, g](h) = \sum_x f(x) g(x+h)`` of the **masked monomials** +``m\,μ_S = m \prod_{k∈S} u_{c_k}`` — each a Fourier product — with the counts ``X[m, m]``. This is +exact at every lag that has a pair, for any mask ``m`` and any order, on periodic or zero-padded +bounded directions. A grid with some uniform directions and some enumerated ones (a stretched +axis, or the latitude rows of a lat-lon grid) is handled by enumerating index pairs on the latter and +transforming along the former, with the pair frame applied per lag; on the sphere that frame depends +only on the two latitudes and the longitude offset, so no rotation of the grid is needed. The +tensor itself is available (`calculate_structure_function_tensor` on a grid), and the transform is +compared against the direct lag sweep and the pair loop to round-off on every schedule. + +### The sphere by spherical harmonics + +For any point set with weights ``w_i`` and mask ``m_i``, the pseudo-coefficients +``\tilde a_{lm} = \sum_i w_i m_i f_i Y_{lm}(x_i)`` of a scalar give, as an identity, + +```math +\sum_{l ≤ L} \frac{2l+1}{4π}\, b_l\, \tilde C_l\, P_l(\cos β) = \sum_{ij} w_i w_j m_i m_j f_i f_j\, K_L(γ_{ij}, β), +\qquad K_L(γ, β) = \frac{1}{16π^2} \sum_{l ≤ L} (2l+1)\, b_l\, P_l(\cos γ) P_l(\cos β), +``` + +the pair sum with a soft kernel of width ``≈ π/L`` in place of a hard bin (`HarmonicNodes`). Vectors +ride the same identity through the spin-1 quantity ``u_θ + i u_φ`` and Wigner ``d^l_{ss'}`` kernels, +and the higher-order operators through the spin-weighted monomials their polynomials expand into. On +a Gauss–Legendre grid with exact quadrature weights and a band-limited field the series terminates +and the route returns the continuous rotation average exactly. + +### Points on a line + +For one-dimensional coordinates every bin of every point is one index range once the points are +sorted, so the polynomial moments are prefix-sum differences of the monomials: exact, in +``O(N \log N + N\, n_{\mathrm{bins}})`` rather than ``O(N^2)``. The CPU backends take this route for +every polynomial operator. + +### Scattered points by non-uniform FFT — soft bins + +Scattered points mapped into a padded periodic box and a mode grid give, through type-1 non-uniform +FFTs of the masked monomials, the same transform the gridded engine expects, and the inverse products +are pair sums with the periodic Dirichlet kernel of the mode set in place of a delta at each lag: a +**soft bin** of width about one cell of the mode grid, with sidelobes a `GaussianTaper` trades for +width. This route (`ScatteredModesSchedule`, `ModeBinEdges`) is **not exact**; it converges to the +hard-binned pair sum as the mode count grows. Its results carry `ModeBinEdges` and its counts are a +kernel-weighted pair mass, not pair counts. It is selected only by passing the tag. + +## Fitting instead of inverting + +The relations above invert a structure function directly. On sparse or noisy data an estimator with +a stated prior is the alternative: a forward model from values on wavenumber bins to the structure +function at the measured separations — `SpectrumForwardModel` for ``E(k)`` from ``S_2``, +`HelmholtzForwardModel` for ``(E_E, E_B)`` from ``(D_{LL}, D_{TT})``, `FluxForwardModel` for a +piecewise-constant flux ``F(k) = -ε + \sum_j ξ_j Δk_j H(k - k_j)`` from ``S_3``, exact for that +``F`` through ``S_3(r) = 2εr - \sum_j 4\,ξ_j Δk_j J_1(k_j r)/k_j`` — fitted by regularised least +squares with a posterior covariance, by non-negative least squares, or by a continuous segmented +power law fitted on the relative residual. These are estimators; the transforms are the exact +relations they approximate, and the tests hold the two to each other. + +## Curved geometry: structure functions on a sphere + +Everything above in flat space treats ``\hat r`` as one vector and ``δu`` as a plain difference. On a +sphere neither holds. The two points have *different* tangent planes, so "the separation direction" +is two different vectors, and subtracting velocities that live in different tangent spaces is not +defined. ### The transported frame -The separation is the great-circle arc. With $\hat{p}, \hat{q}$ the unit position vectors, -$c = \hat{p}\cdot\hat{q}$, $\vec{w} = \hat{p}\times\hat{q}$, $s = |\vec{w}| = \sin\sigma$: - -$$\sigma = 2\,\mathrm{atan2}\!\left(|\hat{q}-\hat{p}|,\ |\hat{q}+\hat{p}|\right), \qquad r = R\sigma$$ - -$$\hat{t}_A = \frac{\hat{q} - c\,\hat{p}}{s}, \qquad - \hat{t}_B = \frac{c\,\hat{q} - \hat{p}}{s}, \qquad - \hat{m} = \frac{\vec{w}}{s}$$ +The separation is the great-circle arc. With ``\hat p, \hat q`` the unit position vectors, +``c = \hat p · \hat q``, ``\vec w = \hat p × \hat q``, ``s = |\vec w| = \sin σ``: -$\hat{t}_A$ and $\hat{t}_B$ are the geodesic tangents at each endpoint, and $\hat{m}$ is the -great-circle normal. Two facts make this cheap: $|\hat{q}-c\hat{p}|^2 = |c\hat{q}-\hat{p}|^2 = s^2$, -so one reciprocal square root normalises both; and $\hat{m}$ is **the same vector at both endpoints**, -so the transverse direction needs no transport at all. +```math +σ = 2\,\mathrm{atan2}\!\left(|\hat q - \hat p|,\ |\hat q + \hat p|\right), \qquad r = Rσ, +\qquad +\hat t_A = \frac{\hat q - c\,\hat p}{s}, \qquad +\hat t_B = \frac{c\,\hat q - \hat p}{s}, \qquad +\hat m = \frac{\vec w}{s}. +``` -The increments are then +``\hat t_A`` and ``\hat t_B`` are the geodesic tangents at each endpoint and ``\hat m`` the +great-circle normal, the same vector at both endpoints, so the transverse direction needs no +transport. The increments are -$$\delta u_L = \vec{u}_B\cdot\hat{t}_B - \vec{u}_A\cdot\hat{t}_A, \qquad - \delta u_T = (\vec{u}_B - \vec{u}_A)\cdot\hat{m}$$ +```math +δu_L = \vec u_B · \hat t_B - \vec u_A · \hat t_A, \qquad δu_T = (\vec u_B - \vec u_A) · \hat m . +``` -Projecting each velocity onto its *own* geodesic frame before differencing **is** parallel transport, -not an approximation: a geodesic parallel-transports its own tangent, and transport on $S^2$ is an -orientation-preserving isometry, so the frame carried from $A$ arrives at $B$ rotated by exactly the -difference of forward azimuths. +Projecting each velocity onto its own geodesic frame before differencing **is** parallel transport: +a geodesic parallel-transports its own tangent, and transport on ``S^2`` is an orientation-preserving +isometry, so the frame carried from ``A`` arrives at ``B`` rotated by exactly the difference of forward +azimuths. In this frame the components of an increment are the same whichever end the pair is read +from, so the odd-rank tensor takes no reading sign on a sphere. ### Why a flat frame is wrong, and by how much -Using one flat direction for both endpoints ignores the **meridian convergence** — the angle $\psi$ -between the two local frames: - -$$\psi \approx \frac{r}{R}\tan\varphi$$ - -| separation | latitude | $\psi$ | -|---|---|---| -| 100 km | 45° | 0.9° | -| 1000 km | 45° | 9° | -| 1000 km | 70° | 25° | - -$D_{LT}$ vanishes identically under reflection symmetry, so this leaks $O(\psi)\,(D_{TT}-D_{LL})/2$ -into a quantity whose true value is zero, and the third-order cascade diagnostics $D_{LLL}$, $D_{LTT}$ -inherit $O(\psi)$. It is the same pathology as spurious B-modes from flat-sky projection in weak -lensing. A direct measurement of the effect: for a solid-body rotation — which has *no* strain, so -$D_{LL}$ must vanish at every separation — the transported frame gives $\Sigma D_{LL}/\Sigma S_2 -\approx 5\times10^{-32}$, while a flat lon/lat frame puts **36% of the total signal** into $D_{LL}$. - -**Guidance:** below ~10 km a flat tangent plane is fine; beyond ~100 km, or anywhere poleward of -about 60°, use a spherical metric. +Using one flat direction for both endpoints ignores the meridian convergence, the angle +``ψ ≈ (r/R)\tan φ`` between the two local frames: 0.9° at 100 km and 45° latitude, 9° at 1000 km, +25° at 1000 km and 70°. ``D_{LT}`` vanishes identically under reflection symmetry, so this leaks +``O(ψ)(D_{TT} - D_{LL})/2`` into a quantity whose true value is zero, and the third-order cascade +diagnostics inherit ``O(ψ)``. For a solid-body rotation, which has no strain, the transported frame +gives ``\sum D_{LL} / \sum S_2 ≈ 5×10^{-32}`` while a flat lon/lat frame puts 36 % of the signal into +``D_{LL}``. Below about 10 km a flat tangent plane is fine; beyond about 100 km, or poleward of about +60°, use a spherical metric. ### Conventions and limits -- **Radial component.** For a thin shell ($D = 3$, $u = (\text{east},\text{north},\text{up})$) the +- **Radial component.** For a thin shell (``D = 3``, ``u = (\mathrm{east}, \mathrm{north}, \mathrm{up})``) the radial component is differenced as a scalar and never transported: the geodesic frame is tangent to - the shell, hence orthogonal to $\hat{p}$ at both endpoints, so radial motion cannot leak into - $\delta u_L$ or $\delta u_T$. Ambient-transporting the full 3-vector would leak radial into - tangential at $O(r/R)$ — a *first*-order error. -- **Coordinates.** A point on a shell is located by two numbers. `x` is `(2, N)` lon/lat while `u` may - be `(2, N)` or `(3, N)`; the shell radius belongs to the metric, not to each point. -- **Angle units follow the metric.** `Distances.Haversine` is degrees, `Distances.SphericalAngle` is - radians. Mixing them rescales every separation by ~57. -- **Handedness.** $\hat{n} = \hat{z}\times\hat{r}$, so $(\hat{r},\hat{n},\hat{z})$ is right-handed. + the shell, hence orthogonal to ``\hat p`` at both endpoints, so radial motion cannot leak into + ``δu_L`` or ``δu_T``. +- **Coordinates.** A point on a shell is located by two numbers: `x` is `(2, N)` lon/lat while `u` may + be `(2, N)` or `(3, N)`; the shell radius belongs to the metric, `SphericalDistance(R)`. +- **Angle units follow the metric.** `Distances.Haversine` is degrees, `Distances.SphericalAngle` and + `SphericalDistance` radians. Mixing them rescales every separation by about 57. - **Degenerate pairs are excluded.** Coincident points have no direction, and antipodal points are - joined by infinitely many great circles, so parallel transport is genuinely non-unique. Both are - masked out rather than producing a NaN. + joined by infinitely many great circles. Both are skipped rather than given a `NaN`. - **Precision.** Sub-metre separations on Earth need `Float64` input: at 45°, one `Float32` ulp of - latitude is already ~4 m on the ground. -- **Isotropy relations are planar.** `KHM.jl`'s `transverse_incompressibility_residual` - ($D_{TT} = \mathrm{d}(rD_{LL})/\mathrm{d}r$, Lindborg 1999 eq. 53) is a *planar* isotropic relation - and holds on the sphere only to $O((r/R)^2)$. - -### What the literature does - -Published velocity-SF work is almost entirely regional ($\lesssim 500$ km), where $\psi$ is -negligible, and works in a local tangent plane: Balwada, LaCasce & Speer (2016) define -$\vec{r} = \Delta x\,\hat{i} + \Delta y\,\hat{j}$; `FluidSF` uses a great-circle distance for the -*scalar separation only* and then rotates with a flat grid-space angle. The transported-frame -convention adopted here is the one established in CMB polarization and weak-lensing shear -$\xi_\pm$, which face the identical problem. - -## Kolmogorov Theory - -### The Inertial Range + latitude is already about 4 m on the ground. +- **Isotropy relations are planar.** The relation ``D_{TT} = \mathrm d(r D_{LL})/\mathrm dr`` + (Lindborg 1999, eq. 53) holds on the sphere only to ``O((r/R)^2)``. -Kolmogorov's 1941 theory predicts that at scales $\eta \ll r \ll L$ (the *inertial range*): +## Kolmogorov theory -$$S_2(r) \sim \varepsilon^{2/3} r^{2/3}$$ - -where: -- $\eta$ is the Kolmogorov scale (smallest scales, dominated by viscosity) -- $L$ is the integral length scale (largest scales, energy injection) -- $\varepsilon$ is the energy dissipation rate - -### K41 Predictions - -Kolmogorov predicted universal scaling exponents in isotropic turbulence: -- $\zeta_n = n/3$ (all orders scale identically) -- $S_2 \sim r^{2/3}$, $S_3 \sim r^{1}$, $S_4 \sim r^{4/3}$, etc. - -### Deviations: Intermittency Correction - -Real turbulence exhibits **anomalous exponents**: -$$\zeta_n = \frac{n}{3} + \delta_n$$ - -where $\delta_n > 0$ represents intermittency. These corrections are significant for $n > 3$. +At scales ``η ≪ r ≪ L`` between the dissipation scale and the integral scale, Kolmogorov's 1941 +theory predicts ``S_2(r) ∼ ε^{2/3} r^{2/3}`` and, more generally, ``S_n(r) ∼ r^{ζ_n}`` with +``ζ_n = n/3``. Real turbulence is intermittent: the measured exponents deviate, +``ζ_n = n/3 + δ_n``, increasingly so for ``n > 3``, which is what the higher-order operators measure. +A prescribed shell spectrum ``E(k) ∼ k^{-(ζ+1)}`` implies ``S_2 ∼ r^{ζ}`` — the two are one statement +about a field, and the [Walkthrough](walkthrough.md) shows both on the same data. ## References -### Foundational - -1. **Kolmogorov, A. N. (1941).** "The Local Structure of Turbulence in Incompressible Viscous Fluid for Very Large Reynolds Numbers." *Dokl. Akad. Nauk SSSR*, 30, 301–305. - - Classic paper establishing the inertial-range energy cascade and K41 theory. - -2. **Landau, L. D., & Lifshitz, E. M. (1987).** *Fluid Mechanics* (2nd ed.). Pergamon Press. - - Chapter on turbulence; comprehensive treatment of SF theory and K41 predictions. - -### Modern Reviews - -3. **Frisch, U. (1995).** *Turbulence: The Legacy of A. N. Kolmogorov.* Cambridge University Press. - - Modern perspective on Kolmogorov theory and intermittency corrections. - -4. **Bos, W. J. T., & Rubinstein, R. (2014).** "On the energy spectrum of isotropic turbulence." *Physics of Fluids*, 26, 055107. - - Recent review of SF scaling and spectrum relationships. - -### Applications - -5. **Balwada, D., Smith, K. S., & Flierl, G. (2016).** "Layer-specific parameterization of shortwave penetration radiation in the ocean." *Journal of Advances in Modeling Earth Systems*, 8, 1545–1567. - - Application of structure functions to ocean turbulence. - -6. **Skamarock, W. C., et al. (2019).** "A Description of the Advanced Research WRF Version 4." NCAR Technical Note. - - Structure functions used in validation of weather model turbulence. - -### Curved Geometry - -8. **Kamionkowski, M., Kosowsky, A., & Stebbins, A. (1997).** "Statistics of cosmic microwave background polarization." *Physical Review D*, 55, 7368. - - Establishes the transported-frame convention for two-point vector statistics on a sphere; flat-sky projection is documented to produce spurious B-modes, the same failure mode as spurious $D_{LT}$. - -9. **Absil, P.-A., Mahony, R., & Sepulchre, R. (2008).** *Optimization Algorithms on Matrix Manifolds.* Princeton University Press, Ex. 8.1.1. - - Closed-form parallel transport on $S^2$. - -10. **Aluie, H. (2019).** "Convolutions on the sphere: commutation with differential operators." *GEM — International Journal on Geomathematics*, 10, 9. [doi:10.1007/s13137-019-0123-9](https://doi.org/10.1007/s13137-019-0123-9) - - Prop. 2: normal/tangent character is preserved, which is why the radial component is differenced rather than transported. +Foundations -11. **Lindborg, E. (1999).** "Can the atmospheric kinetic energy spectrum be explained by two-dimensional turbulence?" *Journal of Fluid Mechanics*, 388, 259–288. [doi:10.1017/S0022112099004851](https://doi.org/10.1017/S0022112099004851) - - §5 longitudinal–transverse–vertical convention; eq. 53 the planar isotropy relation. +- Kolmogorov, A. N. (1941). The local structure of turbulence in incompressible viscous fluid for very large Reynolds numbers. *Dokl. Akad. Nauk SSSR*, 30, 301–305. +- Landau, L. D., & Lifshitz, E. M. (1987). *Fluid Mechanics* (2nd ed.). Pergamon. +- Frisch, U. (1995). *Turbulence: The Legacy of A. N. Kolmogorov.* Cambridge University Press. +- She, Z.-S., & Leveque, E. (1994). Universal scaling laws in fully developed turbulence. *Physical Review Letters*, 72, 336. +- Lindborg, E. (1999). Can the atmospheric kinetic energy spectrum be explained by two-dimensional turbulence? *Journal of Fluid Mechanics*, 388, 259–288. [doi:10.1017/S0022112099004851](https://doi.org/10.1017/S0022112099004851) -12. **Balwada, D., LaCasce, J. H., & Speer, K. G. (2016).** "Scale-dependent distribution of kinetic energy from surface drifters in the Gulf of Mexico." *Geophysical Research Letters*, 43. [doi:10.1002/2016GL069405](https://doi.org/10.1002/2016GL069405) - - Representative of the local-tangent-plane convention used in regional studies. +Fluxes and fits -### Multifractal & Intermittency +- Xie, J.-H., & Bühler, O. (2018). Exact third-order structure functions for two-dimensional turbulence. *Journal of Fluid Mechanics*, 851, 672–686. +- Pearson, B., Wagner, G. L., Fox-Kemper, B., & Samelson, R. (2025). Bessel-function estimators of the interscale kinetic energy and enstrophy fluxes from structure functions. *Journal of Physical Oceanography*, 55(9), 1335–1352. [doi:10.1175/JPO-D-24-0211.1](https://doi.org/10.1175/JPO-D-24-0211.1) — the ``J_1``, ``J_2`` and ``J_3`` relations; see the validation page on the printed boundary terms. +- Balwada, D., Xie, J.-H., Marino, R., & Feraco, F. (2022). Direct observational evidence of an oceanic dual kinetic energy cascade and its seasonality. *Science Advances*, 8(41). [arXiv:2202.08637](https://arxiv.org/abs/2202.08637) — the non-negative flux fit. +- Gutierrez-Villanueva, M. O., Cornuelle, B., Gille, S., Mazloff, M., & Balwada, D. (2026). Regularised least-squares estimates of the spectral kinetic energy flux from third-order structure functions. *Journal of Atmospheric and Oceanic Technology*, 43(3), 355–372 — the regularised flux fit and its posterior covariance. +- Bhattacharjee, A., Jones, J., Balwada, D., Elipot, S., & Gutierrez-Villanueva, M. O. (2026). Segmented power-law spectra from second-order structure functions. [arXiv:2604.27200](https://arxiv.org/abs/2604.27200) — the segmented power-law fit. -7. **She, Z. S., & Leveque, E. (1994).** "Universal dimensionality of intermittent structures in fully developed turbulence." *Physical Review Letters*, 72, 336. - - Anomalous exponents and multifractal model. +Grids, masks and scattered points ---- +- Marcotte, D. (1996). Fast variogram computation with FFT. *Computers & Geosciences*, 22(10), 1175–1186. [doi:10.1016/S0098-3004(96)00026-X](https://doi.org/10.1016/S0098-3004(96)00026-X) — the second-order case of the masked-monomial expansion. +- Slepian, Z., & Eisenstein, D. J. (2016). A practical computational method for the anisotropic redshift-space three-point correlation function. *MNRAS*, 455, L31. [arXiv:1506.04746](https://arxiv.org/abs/1506.04746) — binned pair counts as FFT convolutions and the padding remark. +- Campagne, J.-E. (2026). Kernel-weighted correlation of irregularly sampled series by non-uniform FFT. [arXiv:2609.03866](https://arxiv.org/abs/2609.03866) — the soft-binned route's flat-space precedent. +- Szapudi, I., Prunet, S., & Colombi, S. (2001). Fast analysis of inhomogeneous megapixel CMB maps. *ApJ*, 561, L11. Chon, G., Challinor, A., Prunet, S., Colombi, S., & Szapudi, I. (2004). Fast estimation of polarization power spectra using correlation functions. *MNRAS*, 350, 914 — the kernel-binned harmonic statistic and its E/B split. -## Related Topics in StructureFunctions.jl +Curved geometry -- [Backends](backends.md): How to select the right computational backend for your data size -- [Architecture](architecture.md): How the library implements calculations -- [API Reference](../README.md#api-reference): Full function documentation -- [Examples](../examples/README.md): Worked examples +- Kamionkowski, M., Kosowsky, A., & Stebbins, A. (1997). Statistics of cosmic microwave background polarization. *Physical Review D*, 55, 7368 — the transported-frame convention for two-point vector statistics on a sphere. +- Absil, P.-A., Mahony, R., & Sepulchre, R. (2008). *Optimization Algorithms on Matrix Manifolds.* Princeton University Press, Ex. 8.1.1 — closed-form parallel transport on ``S^2``. +- Aluie, H. (2019). Convolutions on the sphere: commutation with differential operators. *GEM — International Journal on Geomathematics*, 10, 9. [doi:10.1007/s13137-019-0123-9](https://doi.org/10.1007/s13137-019-0123-9) — normal and tangent character preserved, which is why the radial component is differenced rather than transported. +- Balwada, D., LaCasce, J. H., & Speer, K. G. (2016). Scale-dependent distribution of kinetic energy from surface drifters in the Gulf of Mexico. *Geophysical Research Letters*, 43. [doi:10.1002/2016GL069405](https://doi.org/10.1002/2016GL069405) — the local-tangent-plane convention of regional studies. diff --git a/docs/src/validation.md b/docs/src/validation.md index 8bf80a0..a252cfe 100644 --- a/docs/src/validation.md +++ b/docs/src/validation.md @@ -1,7 +1,7 @@ # Validation -Every calculation in this package is checked against something that knows the answer independently. -This page lists those oracles, strongest first, and says what each one can and cannot catch. +Each calculation is cross-checked against an independent reference. This page lists those oracles, +strongest first, with what each one can and cannot catch. The ordering matters. An oracle that is exact to round-off will catch a defect that a percent-level physical check never notices, and most of the defects found in this package's history @@ -14,6 +14,7 @@ were of exactly that kind — a plausible number that was wrong by a constant fa | 1 | Closed-form Fourier modes | round-off | binning, operators, lag enumeration | `test/test_known_truth.jl` | | 2 | Transform vs direct sweep | round-off | the two gridded algorithms against each other | `test/test_gridded_fft.jl` | | 3 | Gridded vs unstructured pair loop | exact counts | the whole gridded path against the reference loop | `test/test_gridded.jl` | +| 3b | Separable transform vs sweep vs pair loop | exact counts, round-off | lat-lon and stretched grids on both algorithms and every backend | `test/test_gridded_separable.jl` | | 4 | Culled vs uncalled | exact counts | culling changes cost, never results | `test/test_cpu_pair_blocking.jl` | | 5 | Backend agreement | round-off | serial, threaded, distributed, MPI, GPU | `test/test_parallel_equivalence.jl` | | 6 | Unit invariance | round-off | quantities that may not depend on a choice of unit | `test/test_known_truth.jl` | @@ -24,6 +25,25 @@ were of exactly that kind — a plausible number that was wrong by a constant fa | 11 | Gridded transform vs the field's own spectrum | round-off | the lag-space spectral route | `test/test_transforms.jl` | | 12 | Closed-form quadrature | round-off | the flux relation's kernel and prefactor | `test/test_transforms.jl` | | 13 | Linearity of the Helmholtz split | round-off | rotational + divergent spectra sum to the trace's | `test/test_transforms.jl` | +| 14 | Windowed estimator vs its definition | round-off | the bounded-domain spectrum against the unbiased autocovariance written out | `test/test_spectra_lagspace.jl` | +| 15 | Closed-form Helmholtz spectra | quadrature | the `J₀`/`J₂` inversion against a Gaussian gradient and curl field | `test/test_spectra_lagspace.jl` | +| 16 | Prescribed angular spectrum | quadrature | the spherical inversion returns the `C_l`, `C^E_l`, `C^B_l` it was built from | `test/test_spectra_lagspace.jl` | +| 17 | Harmonic identity | round-off | the pseudo-spectral series against the kernel-weighted pair sum with random weights and a mask | `test/test_harmonic_sphere.jl` | +| 18 | Exact rotation average | 10⁻⁹ | every polynomial operator through fourth order on a band-limited field, by an independent quadrature over pairs | `test/test_harmonic_sphere.jl` | +| 19 | Spin-1 closed forms | round-off | `L2`, `T2` and the `E`/`B` spectra of single gradient and curl harmonics | `test/test_harmonic_sphere.jl` | +| 20 | Third-order flux routes | quadrature | the `S3`, `L3`, scalar-variance and enstrophy routes against closed forms, and against the `J₁` route on analytic isotropic families | `test/test_transforms.jl` | +| 21 | Device engine parity | round-off, counts exact | the transform engine on a KernelAbstractions backend against the CPU engine on every schedule, masked and complete, one-dimensional and joint | `test/test_gridded_device.jl`, `gpu/test_cuda_gridded_parity.jl` | +| 22 | Transverse convention contract | round-off | every basis rule is unit, perpendicular and odd under `r̂ ↦ −r̂`; `op(−δu, −r̂) == op(δu, r̂)` for the odd transverse operators on every route | `test/test_helpers.jl`, `test/test_core_correctness.jl`, `test/test_gpu_tiled_parity.jl` | +| 23 | Weighted pair loop | bit for bit, round-off | weights of one reproduce the unweighted results; random weights equal the weighted pair loop on sweep, transform, device and the point entries; `cell_measure` equals the point entry with the same weights | `test/test_gridded_weights.jl` | +| 24 | Lattice identity of the NUFFT route | 10⁻⁹ | points on the mode grid reproduce the periodic gridded transform; the 1-D kernel identity written out; convergence to the hard bins with the mode count — on both providers, NonuniformFFTs and FINUFFT, which agree with each other to 10⁻¹⁰ | `test/test_scattered_modes.jl` | +| 25 | Sorted line against the pair loop | counts exact, 10⁻¹² | every polynomial operator, multi-fields, weights, unsorted and coincident points; linear in the points | `test/test_sorted_line.jl` | +| 26 | Tensor from the transform against the point tensor | counts exact, 10⁻⁹ | flat and spherical grids, orders 2–4, the joint tensor over angle | `test/test_tensor_khm.jl` | +| 27 | Forward models against closed forms | 10⁻⁸–10⁻¹² | the spectrum, Helmholtz and flux forward models; round trips through the inversions; the fitted flux is the flux the `J₂` transform recovers | `test/test_fits.jl` | + +Every route with a device kernel — the point kernels, the transform engine on every schedule, the +non-uniform FFT route and the tensor kernel — is also run on an A100 against the CPU by +`gpu/test_cuda_gridded_parity.jl` and `gpu/runtests.jl`, counts exact and sums to round-off; the +tolerance policy below says what "round-off" means there. ### 1. Closed-form Fourier modes @@ -126,6 +146,14 @@ constant advective structure function `c` must give ``Π_K = -(c/2)(1 - J_0(KR)) the kernel and the prefactor with nothing left to fit — which matters, because a flux wrong by a constant, or by a sign, still looks like a cascade. +**The third-order routes against each other.** For an isotropic incompressible flow the advective, +`S3` and `L3` structure functions are tied by `SF_A = (1/2r)\,d(r\,S3)/dr` and +`S3 = (1/3r^2)\,d(r^3 L3)/dr`, so the three flux relations must agree on any analytic family built +through those relations. They do only with the boundary terms their integrations by parts leave at +the last separation: the tests show the integrals alone miss by tens of percent and can change sign, +and the three routes then agree to `10⁻⁶`. The enstrophy routes are gated the same way through +`SF_{Aω} = -∇² SF_{Au}`. + **The Helmholtz split by linearity.** ``D_{rot} + D_{div} = D_{LL} + D_{TT}`` exactly and the transform is linear, so the rotational and divergent spectra must sum to the spectrum of the trace, whatever the field is. This is an identity rather than a physical expectation, which is what makes it @@ -147,9 +175,84 @@ positive-definiteness**. The error falls as the square of the separation spacing So two quite different failures land in the same place, and the check distinguishes them: a covariance function that is invalid is off by the scale of the matrix itself, while one that is valid -but under-resolved is off by a discretisation error. Tripping the check on a coarse covariance is -useful output — it says the representation cannot support a valid matrix — not a nuisance to be -tuned away. +but under-resolved is off by a discretisation error. A coarse covariance that trips the check is +reporting that the representation cannot support a valid matrix. + +### 22–27. The later routes + +**Weights.** The weighted statistic is ``\sum w_i w_j v_{ij} / \sum w_i w_j``. The gate is a pair loop +written in the test with the same weights: the sweep matches it bit for bit, the transform to +`1e-12`, and weights of one reproduce the unweighted results exactly, so the weighted code path +cannot have drifted from the unweighted one. + +**The non-uniform FFT route.** Points placed exactly on the mode grid make the soft-binned route the +periodic gridded transform, which is exact, and the two agree to `1e-9` in one, two and three +dimensions with masks, weights and multi-fields. Off the grid the one-dimensional kernel identity +is written out in the test — the pair sum with the Dirichlet or Gaussian-tapered kernel — and the +route matches it to `1e-9`; against the hard-binned pair loop the error falls monotonically as the +mode count grows. The route is soft-binned by construction and the tests say so: no finite mode +count reproduces the hard bins. + +**The sorted line.** For one-dimensional points the pair loop and the sorted route bin every pair +with the same `digitize` call on the same difference, so the counts are equal bit for bit and the +sums to `1e-12`; the test also holds the route's cost linear in the points (10⁵ points in well under +a second where the pair loop would need 5·10⁹ pairs). + +**Tensors.** The transform's symmetric moment store, expanded to the dense tensor, equals the point +tensor on the grid's points at orders 2, 3 and 4 on flat grids and on a lat-lon grid, and the joint +tensor over angle marginalises to the tensor and, through its trace, to the joint histogram of `S2`. +Odd ranks read a pair canonically in a fixed frame and take no sign in the sphere's geodesic frame; +both are tested. + +**Fits.** The forward models are held to closed forms (the one-dimensional bin integral is +elementary; the flux model is exact for a piecewise-constant flux and equals the quadrature of the +defining integral to `1e-8`), the inversions to round trips of the models' own data, the posterior +covariance to ``σ²(HᵀH)^{-1}``, and the fitted flux to the flux the `J₂` transform of the same +`S3` recovers between the model's jumps — so the forward model of the fits and the inverse relation +of the transforms are the same transform. + +## Backend parity: the tolerance policy + +Two backends computing one statistic on one data set must give **equal counts** and sums that differ +by round-off only. "Round-off" is stated as a relative bound on the largest sum, +`max |Δsum| / max |sum|`, and the bound is what a different summation order can produce: + +| comparison | bound | why | +|---|---|---| +| serial vs threaded vs distributed CPU | `1e-12` | the same arithmetic in a different order | +| CPU vs device, flat lattice | `1e-10`, counts exact | squared separations of rational spacings are exact on both, so bins agree bit for bit; sums differ by fused-multiply-add and reduction order | +| CPU vs device, sphere | `1e-10`, counts exact **off the lattice's edges** | the device's `sin`/`cos`/`acos` round differently from the host's; a pair whose separation lies exactly on a bin edge can change bins, so the parity tests place edges between the lattice's own separations | +| transform vs sweep | `1e-10` (`1e-9` at third order and above) | the transform's inverse FFT accumulates `O(n log n)` operations | +| weighted counts | `1e-12` relative | a weighted count is a floating sum, not an integer | +| soft-binned NUFFT route, CPU vs device | `1e-9` | the non-uniform FFT's own accuracy, once its kernel is evaluated in double precision | +| `Float32` joint histogram over a value axis, CPU vs device | `3e-5` of pairs in a different value bin | the second axis bins on the pair's own value, so a value within an ulp of a value-bin edge falls either side of it under the two devices' rounding. The count of one bin is therefore not an invariant of the pair set and equality of counts is not the criterion; what is invariant is that every pair is placed, so the measure is the misplaced share of the total. Measured at `NMOM = 1`: ≤ 2.3e-7; at `NMOM = 6`, six binned invariants per pair and cubic values: ≤ 3.2e-5 | + +A test that needs a looser bound than these is testing something other than parity, and says what. + +Every parity script fixes its draw, so that a row is reproducible and a change in it is attributable to +the code. A fixed draw is never what makes a row pass: each row's verdict is one of the bounds above, +which hold for any draw. A boolean that happens to come out true on one draw is not a criterion — the +`Float32` value-axis row above was such a boolean until 2026-09-16, and it could not distinguish a +regression from luck. +The one exception recorded: NonuniformFFTs chooses a different kernel evaluation on CUDA than it does +on the host, and under it a `Float64` transform of ours came out near `1e-5` rather than `1e-15`. The +package's extension therefore names the kernel and the evaluation explicitly on every backend rather +than taking a backend's default, which brings the device transform to `1e-15`. Why the default +evaluation loses that much is not established here, and the difference belongs to that library's +choice of defaults, not to a claim about it. + +## The printed boundary terms of Pearson et al. (2025) + +The third-order flux relations (the `J₂` and `J₃` routes and the enstrophy route from the velocity's +advective structure function) come from integrating the `J₁` relation by parts at a finite radius +``R``, and the boundary terms are essential: the closed-form gate on the power-law family fails +without them at every wavenumber, and the estimate can change sign. Appendix B of the paper prints +two boundary terms in a form that is dimensionally inconsistent as read — `3 SF_Luu J₁(Kr)` in (B4) +where a flux ``∼ u^3/L`` requires `(3/K) SF_Luu J₁(Kr)`, and `K (dSF_Au/dr) J₁` in (B7) where the +enstrophy flux ``∼ u^3/L^3`` requires `(1/K)(dSF_Au/dr) J₁`. The consistent forms are the ones that +close on the power-law family and make the three energy routes and the three enstrophy routes agree +to `1e-6` on analytic isotropic families; they are what the package ships. The paper has no erratum +at the time of writing; the difference may be a rendering of a small `/K`. ## What is checked statistically, and why it is not a gate @@ -191,4 +294,12 @@ Each oracle lives in a targeted test file that can be run on its own: julia --project=test test/test_known_truth.jl julia --project=test test/test_gridded_fft.jl julia --project=test test/test_spherical_geometry.jl +julia --project=test test/test_gridded_weights.jl +julia --project=test test/test_scattered_modes.jl +julia --project=test test/test_sorted_line.jl +julia --project=test test/test_tensor_khm.jl +julia --project=test test/test_fits.jl ``` + +The device parity runs need a GPU allocation: `sbatch gpu/run_cuda_gridded_parity.sh` writes its +table to `gpu/benchmark_results/`, and `julia --project=gpu gpu/runtests.jl` runs every CUDA suite. diff --git a/docs/src/walkthrough.md b/docs/src/walkthrough.md index ab7b719..37b7c1d 100644 --- a/docs/src/walkthrough.md +++ b/docs/src/walkthrough.md @@ -1,12 +1,12 @@ # Walkthrough: from a velocity field to a cascade diagnostic -This page runs one analysis end to end — six structure-function invariants, the Helmholtz split, -the directional signal, and the spectral slope — on fields whose answers are known in advance, so -every number below can be checked rather than taken on faith. +This page runs one analysis end to end: six structure-function invariants, the Helmholtz split, the +directional signal and the spectral slope. The fields are ones whose answers are known in advance, +so every number below can be compared against a value derived independently. -Two acts, because the two data layouts want different algorithms. Scattered points go through the -pair loop; a uniform grid goes through the transform, which is roughly two orders of magnitude -faster and exact. +Two acts, because the two data layouts take different algorithms. Scattered points go through the +pair loop; a uniform grid goes through the transform, which is exact and about two orders of +magnitude faster. ## Act 1 — scattered points @@ -44,6 +44,11 @@ x = 2π .* rand(2, 6000) u = solenoidal_field(x) ``` +A point list carries no mask. A non-finite sample makes every bin it pairs into `NaN`, as any sum +does, so drop such points before the call: `keep = vec(all(isfinite, u; dims = 1))`, then +`x[:, keep]` and `u[:, keep]`. Grids are different, because their lags and transforms need every cell +in place; there the mask travels with the data (Act 2). + ### Six invariants in one pass The six second- and third-order invariants share a pair loop, a separation and a bin, so computing @@ -134,6 +139,48 @@ field has no energy cascade, so its third-order moments are consistent with zero (`⟨δu_L³⟩ = 1.3e-2` against `⟨δu_L²⟩ ≈ 1`, i.e. sampling noise). A meaningful `ε` needs data with a genuine flux — a forced simulation or an observational record. +### Pair weights + +A weight per point turns every statistic into `Σ w_i w_j v_ij / Σ w_i w_j` and the counts into a +weighted pair mass, which is why weighted results take floating-point counts: + +```julia +w = 0.5 .+ rand(size(x, 2)) +sfw = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Float64; weights = w, + backend = CB.SerialBackend()) +``` + +Weights of one reproduce the unweighted result bit for bit. On a grid, `cell_measure(grid)` gives the +cell areas, so a lat-lon sum becomes an area average — the same weighting the harmonic route uses. + +![Pair weights](assets/sf_weights.png) + +*A lat-lon cell shrinks toward the poles, so weighting the pairs by `cell_measure(grid)` moves the +average away from the one that counts every pair once.* + +### Points on a line + +One-dimensional data — a transect, a time series read as a line — never needs the pair loop. Once the +points are sorted, every bin of every point is one index range, and the polynomial moments over a +range are prefix-sum differences of the monomials. The CPU backends take this route automatically +for every polynomial operator, arrays and multi-fields alike, and its cost is +`O(N log N + N n_bins)`: + +```julia +xl = reshape(sort(rand(100_000)) .* 100.0, 1, :) +ul = randn(1, 100_000) +sfl = SFC.calculate_structure_function(SFT.L3SFType(), xl, ul, collect(range(0.0, 0.5; length = 21)), Int64) +``` + +On eight cores a million points — five billion pairs binned — take `0.4 s`; the pair loop on the same +data would take an hour. Counts are bit for bit the pair loop's, because the route bins each pair with +the same `digitize` call on the same coordinate difference. + +![The sorted route on a line](assets/sf_sorted_line.png) + +*Left: the sorted route's cost grows with the points, the pair loop's with their square. Right: it is +the pair loop's answer, not an approximation of it.* + ## Act 2 — a uniform grid On a grid the same quantity is available by transform, exactly, for every lag at once. @@ -207,12 +254,156 @@ the excited band, and saturation at `0` beyond the largest. A prescribed `E(k) ~ `D_LL ~ r^(2/3)`, and the measured plateau sits at `0.71 ± 0.03` — the excess is the finite width of the band, which leaves the plateau squeezed between the two limbs rather than flat. -This is worth stating plainly, because it is the honest limit of the method: a scattered-point -sample cannot show this at all. Its small-scale end is capped by the mean point spacing, so a +A scattered-point sample cannot show this at all. Its small-scale end is capped by the mean point +spacing, so a one-decade band gives a slope that declines monotonically through `2/3` without ever plateauing, and fitting a single exponent to it returns whatever the fit window happens to select. Resolving a scaling range needs the dynamic range a grid provides. +### Grids with one uniform direction + +A lat-lon grid has no constant lag — a step in longitude is a different distance at every latitude — +but longitude is uniform, so every pair of latitude rows shares its geodesic frame around the whole +circle. The transform runs along longitude for each pair of rows, with the frame applied per lag, and +the same holds for a Cartesian grid with a stretched axis beside a uniform one. Nothing changes at the +call site: the grid's axis **types** decide the route (a range is uniform, a vector of coordinates is +not), the routes are exact, and `verbose = true` names the one chosen. + +```julia +using FlowGeometries: FlowGeometries as FG +using ComputationalBackends: ComputationalBackends as CB + +n_lon, n_lat = 1440, 720 +geo = FG.Geometry.SphericalGeometry(6.371e6) +grid = FG.Grids.StructuredGrid(geo, range(0.0, step = 2π / n_lon, length = n_lon), + range(-π / 2 + π / (2n_lat), π / 2 - π / (2n_lat); length = n_lat)) +u = randn(2, n_lon, n_lat) # (east, north) at every cell +bins = 6.371e6 .* collect(range(0.0, π; length = 41)) # metres, as the radius is + +sf = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, UInt64, + SB.FastFourierTransformSpectralBackend(); + backend = CB.ThreadedBackend()) +``` + +Separations come out in the unit of the geometry's radius on every route, the threaded backend +splits the row pairs across tasks, and a field of several fields (`Fields`) rides along, so a +scalar's odd moments and the mixed moments of a Yaglom-type relation come from the same transform. + +On eight dedicated cores the transform above bins `5.4 × 10¹¹` pairs in `10.5 s` (`54 s` on one core). +Against the direct row-by-row sweep of the same grid at 180 latitude rows the transform is `62×` +faster for `L2` and `16×` for `L3`, with counts identical and sums agreeing to `10⁻¹⁵`; the gap +narrows at third order because the frame algebra per lag grows with the moment's rank while the +transforms do not. + +### The same engine on a device + +The transform engine takes the hardware from the same `backend` keyword the point entries use. With +`using KernelAbstractions` and a device package loaded, `backend = CB.GPUBackend(CUDA.CUDABackend())` +moves the masked monomials to the device, takes their transforms there through the device's own +AbstractFFTs implementation, and bins every lag of every slab pair in one kernel with a privatized +histogram. Nothing about the schedule changes: uniform, stretched and lat-lon grids, masks, field +multi-fields and every polynomial order run through the same code, and the counts are exactly the CPU +engine's. `CB.GPUBackend(KernelAbstractions.CPU())` runs the identical kernel on the host, which is +how the suite checks it without a device. + +### Tensors + +The transform forms the whole increment moment tensor at every lag before contracting it with an +operator, so the tensor itself is available on a grid, at any order, in the pair frame — and jointly +in separation and angle: + +```julia +T3 = SFC.calculate_structure_function_tensor(Val(3), grid, u, bins, SB.FastFourierTransformSpectralBackend()) +T3.values # (2, 2, 2, n_bins): ⟨δu_a δu_b δu_c⟩ per bin +T2θ = SFC.calculate_structure_function_tensor(Val(2), grid, u, bins, ang, SB.FastFourierTransformSpectralBackend(); + second_axis = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0))) +``` + +An odd-rank tensor changes sign when a pair is read from its other end, so in a fixed frame it takes +the canonical pair reading, as the odd scalar moments do; in the sphere's geodesic frame the +components are the same from either end and no sign enters. The point-list tensors follow the same +rule on every backend, and `MomentTensorOperator{P}` names the tensor to the transform engine. + +![Moment tensors](assets/sf_tensor.png) + +*The components carry the anisotropy the trace averages away, and the trace is the scalar +second-order entry.* + +### The transverse convention + +The signed transverse component that `T3SFType`, `L2T1SFType` and any odd `NT` read is defined by +the operator's basis convention, `ProjectedStructureFunctionType{0, 3}(basis)`. The default +`CanonicalTransverseBasis()` is `n̂ = ẑ × r̂` in two dimensions and the same rule normalised in three, +continued about `x̂` where the separation is along `ẑ`; `ReferenceAxisTransverseBasis(a)` turns about +an axis of the caller's choosing and refuses a pair whose separation is parallel to it. Every rule's +first vector is odd under `r̂ ↦ −r̂`, which is what makes the operator's value the same from either end +of a pair — and every result carries the convention that produced it, `res.operator.basis`. A rule of +your own is a subtype of `AbstractTransverseBasisConvention` with one `transverse_basis(rule, r̂)` +method obeying that contract; every route, the device kernels included, reads the sign through it. + +### Scattered points by non-uniform FFT + +A scattered point set has no lags, but placed in a padded box it has modes, and the type-1 +non-uniform FFT of its masked monomials is exactly the forward transform the gridded engine expects. +The inverse products are then pair sums with a periodic Dirichlet kernel in place of a delta at each +lag: **soft bins** of about one mode cell, sidelobes and all. + +```julia +using NonuniformFFTs: NonuniformFFTs # or FINUFFT, or both +s = SFC.ScatteredModesSchedule(x, 2.0, (128, 128); taper = GaussianTaper(0.05)) # r_max = 2, 128² modes +soft = SFC.calculate_structure_function(SFT.L2SFType(), s, u, bins, NonuniformFFTsSpectralBackend()) +soft.distance # a ModeBinEdges: soft-binned, not pair counts +``` + +Two libraries serve the route, each named by its own tag with the tolerance asked of its transforms: +`NonuniformFFTsSpectralBackend(tolerance = 1e-12)`, whose kernel half-support follows from the tolerance by +the Kaiser–Bessel aliasing rule (`nufft_half_support`), and `FINUFFTSpectralBackend(tolerance = 1e-12)`, +which runs cuFINUFFT for points on a CUDA device. The two agree to `1e-10`; SpectralBackends' generic +NUFFT tag names no library and is refused. + +This route is **not exact** and is selected only by passing the tag. Its statistic converges to the +hard-binned pair sum as the mode count grows; the tests pin it on a lattice, where it is exact, and +measure the convergence off one. The result carries `ModeBinEdges`, and its counts are a +kernel-weighted pair mass. It pays at size: 20 000 points onto 256×192 modes bin in `0.014 s` on +eight cores and `0.008 s` on an A100, independent of the pair count. + +![Scattered points by non-uniform FFT](assets/sf_scattered_modes.png) + +*The soft-binned statistic approaches the hard-binned pair sum as the mode count grows, and is not +equal to it at any finite count.* + +### The sphere by spherical harmonics + +A pair statistic on a sphere has a second exact route that never enumerates pairs or lags. For any +point set, weights and mask, the spherical harmonic **pseudo-coefficients** of the masked field's +monomials give, as an identity, the pair sum with a soft kernel in place of a hard bin: + +``` +Σ_ij w_i w_j (θ_j − θ_i)^p K_L(γ_ij, β) = Σ_{l ≤ L} (2l+1)/(4π) b_l X_l P_l(cos β), +K_L(γ, β) = (1/16π²) Σ_l (2l+1) b_l P_l(cos γ) P_l(cos β) → (1/8π²) δ(cos γ − cos β). +``` + +Vectors ride the same identity through their spin-1 quantity `u_θ + i u_φ`, with Wigner `d^l_{ss′}` +kernels for the spin-weighted monomials the operator's polynomial expands into. The "bin" is the node +set: separations, the truncation degree and a taper on the series. + +```julia +nodes = HarmonicNodes(32, 64; taper = GaussianTaper(0.02)) # 32 Gauss–Legendre nodes, lmax = 64 +res = SFC.calculate_structure_function(SFT.L3SFType(), x, u, nodes, SB.NUFSHTSpectralBackend(); + distance_metric = DI.SphericalAngle()) +res.values # the kernel-binned ⟨δu_L³⟩ at the nodes +``` + +`SB.DirectSumSpectralBackend()` computes the same coefficients by direct summation, `O(N lmax²)`, and +is the reference; `using NUFSHT` supplies the fast transform. On a Gauss–Legendre grid with exact +quadrature weights the pseudo-coefficients are the coefficients, the series of a band-limited field +terminates, and the route returns the continuous rotation-averaged structure function exactly — the +tests hold every polynomial operator through fourth order to `10⁻⁹` against an independent quadrature +over pairs. The same coefficients give the field's `E`/`B` spectra, `SFC.harmonic_spectra`, and a +kernel-binned result inverts to `C_l` through `isotropic_spectrum(res, g, lmax)` by the nodes' own +quadrature weights: on a masked field that ratio of kernel-binned sums to kernel-binned counts follows +the spectrum of the complete field where the pseudo-spectrum of the masked field does not. + ## Act 3 — into spectral space A structure function and a spectrum carry the same second-order information, and the package @@ -265,6 +456,25 @@ complete-field spectrum on a 48² grid: ![Spectrum with missing data](assets/sf_missing_data.png) +### Bounded directions, tapers and missing lags + +A direction that does not wrap has no Fourier basis of its own, so its spectrum is an estimate: the +transform, on a padded lag grid, of the unbiased autocovariance `C(h) = σ² − D(h)/2` that the pair +counts give at every lag `|h| < n`. The same call serves it; `wavenumbers` has the padded length along +a bounded direction, and the density still integrates to the variance of the held cells. + +```julia +kaxes, density = SFC.gridded_spectrum(u, sched, Val(2), SB.FastFourierTransformSpectralBackend(); + taper = SFC.Bartlett()) +``` + +`taper` weights the lags before the transform: the far lags of a bounded domain are averaged over +few pairs, and `Bartlett()` (linear to zero at the largest lag) or `GaussianTaper(σ)` trades +resolution in wavenumber for a steadier estimate; `NoTaper()` is the default. With cells missing, a +lag that no pair of held cells names has no structure function at all; the default +`missing_lags = SFC.RefuseMissingLags()` throws, naming the lag, and +`missing_lags = SFC.ZeroDeviationAtMissingLags()` takes its covariance as zero instead. + ### From scattered points: isotropic, and one assumption Scattered data has no lag grid, so the transform integrates against a dimension-appropriate kernel — @@ -299,3 +509,66 @@ Because `D_rot + D_div = D_LL + D_TT` exactly and the transform is linear, the t spectrum of the trace — an identity that holds whatever the field is, and the one the tests assert. ![Helmholtz spectra](assets/sf_helmholtz_spectra.png) + +The same split follows directly from the two projections, without the real-space decomposition and +its cumulative integral: the sum `D_LL + D_TT` transforms with `J₀` as the trace does, and the +difference `D_LL − D_TT` with `J₂`, so + +```julia +spec = SFC.helmholtz_spectra(res.L2, res.T2, kq) # (rotational, divergent), by J₀ and J₂ +``` + +carries only the truncation error of the two Hankel integrals. On a sphere the counterpart is a +Legendre inversion: a scalar's or the trace's structure function binned in `R·σ` gives `C_l` by +`SFC.isotropic_spectrum(sf, geometry, lmax)`, and the two projections give the gradient and curl +spectra `C^E_l`, `C^B_l` by `SFC.helmholtz_spectra(L2, T2, geometry, lmax; variance)` — the sum of the +two needs the field's mean square, which no structure function carries, while their difference does +not. + +## Act 4 — fitting instead of inverting + +The transforms above are the exact relations. On sparse or noisy data — drifters, a short record — +an oscillatory Bessel kernel amplifies the noise and the finite range truncates the integral, and the +estimator of choice in the recent literature is a **fit**: a forward model from values on wavenumber +bins to the structure function at the measured separations, inverted with a stated prior. The +package carries three forward models and three inversions, and holds the models to the transforms: +the flux fitted from a synthetic `S3` is the flux the `J₂` transform recovers from the same `S3`. + +```julia +using LsqFit # only the segmented power law needs it +k_edges = exp.(range(log(0.5), log(20.0); length = 13)) # 12 log-spaced wavenumber bins + +# the spectral energy flux from S3 = ⟨δu_L‖δu‖²⟩ (Gutierrez-Villanueva et al. 2026): regularised +# least squares needs the data covariance — here the per-bin variance of the mean under independent +# pairs, read from a value-binned joint histogram — and a prior on (ε, ξ₁…ξ₁₂) +vbins = collect(range(-3.0, 3.0; length = 121)) +joint = SFC.calculate_structure_function(SFT.S3SFType(), x, u, bins, vbins) # value-binned joint histogram +W = SFC.independent_pair_variance(joint) +fit = SFC.fit_flux(res.S3, k_edges, SFC.RegularizedLeastSquares(vcat(1e-7, fill(1e-10, 12))); W) +fit.F, fit.ε, fit.ξ # the flux at the bin centres, its large-scale value, the injection density +fit.flux_covariance # G C_xx Gᵀ + +# the monotone-flux variant (Balwada et al. 2022): non-negative least squares, no covariance +nn = SFC.fit_flux(res.S3, k_edges, SFC.NonNegativeLeastSquares()) + +# a segmented power-law spectrum from S2 (Bhattacharjee et al. 2026), on the relative residual +seg = SFC.fit_spectrum(res.S2, [0.5, 20.0], SFC.SegmentedPowerLaw(2), Val(2)) +seg.parameters, seg.breakpoints # (b₁, α₁, α₂) and the log-uniform break +sel = SFC.select_segments(res.S2, [0.5, 20.0], 1:4, Val(2)) # the segment count minimising the relative misfit + +# the gradient/curl spectra from the L2/T2 pair on bins, and the trade-off curve a prior is chosen from +hb = SFC.fit_helmholtz_spectra(res.L2, res.T2, k_edges, SFC.NonNegativeLeastSquares()) +curve = SFC.tradeoff_curve(SFC.FluxForwardModel(SF.midpoints(res.S3.distance), k_edges), res.S3.values, W, + 10.0 .^ range(-12, -4; length = 17)) # (misfit, norm) per prior; nothing is chosen for you +``` + +Every fit returns what it fitted and, where the method gives one, the posterior covariance. The +forward models themselves are exposed (`forward_matrix(model)`), so a different prior, a different +solver or a bootstrap over `W` is a few lines on top. These are estimators with stated priors; the +transforms of Act 3 are the exact relations they approximate. + +![Fitting instead of inverting](assets/sf_fits.png) + +*A `SegmentedPowerLaw` recovers the spectral slope from `S₂`. For the flux from `S₃` the prior is +what makes the problem well posed: below `π/r_max` a wavenumber bin is not resolved by the sampled +separations, and the unregularised inversion swings there while the non-negative solver does not.* diff --git a/ext/StructureFunctionsAbstractFFTsExt.jl b/ext/StructureFunctionsAbstractFFTsExt.jl new file mode 100644 index 0000000..9b70930 --- /dev/null +++ b/ext/StructureFunctionsAbstractFFTsExt.jl @@ -0,0 +1,794 @@ +module StructureFunctionsAbstractFFTsExt + +using AbstractFFTs: AbstractFFTs +using LinearAlgebra: LinearAlgebra as LA +using StaticArrays: StaticArrays as SA +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, HelperFunctions as SFH +using SpectralBackends: SpectralBackends as SB + +const CB = SFC.CB + +"""Bytes of monomial scratch the forward stage holds while it transforms a batch of them.""" +const FORWARD_BATCH_BYTES = Ref(1 << 28) + +""" + _pad_dims(schedule, r_max) -> NTuple{Du, Int} + +Transform length per uniform direction. A periodic direction needs none — the circular correlation +is the sum wanted. A bounded one is padded to at least `n + h_max`, with `h_max` the largest lag any +slab pair reads within `r_max`, so the circular correlation equals the linear one at every lag that +is read; rounded up to a length the transform factors well. +""" +_pad_dims(s::SFC.AbstractSeparableSchedule, r_max) = _pad_dims(SFC.uniform_axes(s), SFC.lag_limits(s, r_max)) + +@inline function _pad_dims(su::SFC.UniformLagSchedule{Dg}, lims::NTuple{Dg, Int}) where {Dg} + return ntuple(Val(Dg)) do d + n = @inbounds su.dims[d] + @inbounds(su.periodic[d]) && return n + nextprod((2, 3, 5), n + min(n - 1, lims[d])) + end +end + +"""Embed `src` at the origin of a zero array of size `P`, in `src`'s array family.""" +function _embed(src::AbstractArray{FT, Dg}, P::NTuple{Dg, Int}) where {FT, Dg} + out = fill!(similar(src, P), zero(FT)) + view(out, map(n -> 1:n, size(src))...) .= src + return out +end + +""" + MonomialTransforms(data, valid, weights, uniform, P, plan, ::Val{Pm}) + MonomialTransforms(data, uniform, P, valid, weights = NoWeights()) + +Forward transforms of the masked, weighted monomials of one slab of a packed field, built on first use +and kept, in the array family of `data`. A monomial is named by the sorted components it multiplies, +zero-padded to `Pm` entries; the all-zero key is the mask (times the weights), transformed at +construction. `hits` and `misses` count the lookups that found and built a transform. +""" +mutable struct MonomialTransforms{FT, Dg, T, Pm, DT <: AbstractMatrix, VT, WT, PL, AT <: AbstractArray{Complex{FT}, Dg}} + data::DT + valid::VT + weights::WT + schedule::SFC.UniformLagSchedule{Dg, T} + P::NTuple{Dg, Int} + plan::PL + cache::Dict{NTuple{Pm, Int}, AT} + hits::Int + misses::Int +end + +function MonomialTransforms( + data::AbstractMatrix, valid, weights, s::SFC.UniformLagSchedule{Dg, T}, P::NTuple{Dg, Int}, plan, ::Val{Pm}, +) where {Dg, T, Pm} + FT = float(eltype(data)) + mask = ntuple(_ -> 0, Val(Pm)) + F0 = plan * _embed(_held_monomial(data, valid, weights, s.dims, mask, FT), P) + cache = Dict{NTuple{Pm, Int}, typeof(F0)}(mask => F0) + return MonomialTransforms{FT, Dg, T, Pm, typeof(data), typeof(valid), typeof(weights), typeof(plan), typeof(F0)}( + data, valid, weights, s, P, plan, cache, 0, 1, + ) +end + +MonomialTransforms(data::AbstractMatrix, s::SFC.UniformLagSchedule, P::Tuple, valid, weights = SFC.NoWeights()) = + MonomialTransforms(data, valid, weights, s, P, AbstractFFTs.plan_rfft(_zeros_like(data, P)), Val(2)) + +"""A zero array of shape `P` in `data`'s array family, in its float type.""" +_zeros_like(data::AbstractArray, P::Tuple) = + fill!(similar(parent(data), float(eltype(data)), P), zero(float(eltype(data)))) + +# The masked, weighted monomial of one slab, shaped as its cells. +_held_monomial(data::AbstractMatrix, valid, weights, dims::NTuple{Dg, Int}, key::NTuple{Pm, Int}, + ::Type{FT}) where {Dg, Pm, FT} = + reshape(SFC._held_monomial_vector(data, valid, weights, key, FT), dims) + +"""The forward transform of the masked, weighted monomial `key`, from the cache or built once.""" +function monomial_transform!(mt::MonomialTransforms{FT, Dg, T, Pm}, key::Tuple) where {FT, Dg, T, Pm} + k = SFC._padded_key(Val(Pm), key) + cached = get(mt.cache, k, nothing) + if cached !== nothing + mt.hits += 1 + return cached + end + mt.misses += 1 + F = mt.plan * _embed(_held_monomial(mt.data, mt.valid, mt.weights, mt.schedule.dims, k, FT), mt.P) + mt.cache[k] = F + return F +end + +"""Pairs with both ends held, at every lag of the padded grid: the two masks' cross-correlation.""" +pair_counts(mtI::MonomialTransforms, mtJ::MonomialTransforms) = + AbstractFFTs.irfft(conj.(monomial_transform!(mtI, ())) .* monomial_transform!(mtJ, ()), mtI.P[1]) + +pair_counts(mt::MonomialTransforms) = pair_counts(mt, mt) + +""" + moment_component(mtI, mtJ, j::NTuple{P, Int}) -> Array + +`Σ_x m(x) m(x+h) Π_k δu[j_k]` at every lag `h` of the padded grid, for the sorted multi-index `j`, +with `x` in the first slab and `x + h` in the second. + +Expanding each factor `δu = u(x+h) − u(x)` gives `2^P` cross-correlations of masked monomials, one per +choice of which factors sit at `x + h`; each is a product in the transform domain, and the whole sum +is inverted once. +""" +function moment_component( + mtI::MonomialTransforms{FT, Dg}, mtJ::MonomialTransforms{FT, Dg}, j::NTuple{P, Int}, +) where {FT, Dg, P} + spec = fill!(similar(monomial_transform!(mtI, ())), zero(Complex{FT})) + for mask in 0:((1 << P) - 1) + primed = Tuple(j[k] for k in 1:P if (mask >> (k - 1)) & 1 == 1) + unprimed = Tuple(j[k] for k in 1:P if (mask >> (k - 1)) & 1 == 0) + sign = isodd(P - length(primed)) ? -one(FT) : one(FT) + Fu = monomial_transform!(mtI, unprimed) + Fp = monomial_transform!(mtJ, primed) + @. spec += sign * conj(Fu) * Fp + end + return AbstractFFTs.irfft(spec, mtI.P[1]) +end + +moment_component(mt::MonomialTransforms, j::NTuple) = moment_component(mt, mt, j) + +# --------------------------------------------------------------------------------------------------- +# The moments one slab pair needs, as columns of one batched inverse transform +# --------------------------------------------------------------------------------------------------- + +# Fill the columns for slab pair (I, J) from the two slabs' forward transforms and invert them all at +# once; returns the `(lags, columns)` matrix of raw moments. +function _pair_inverse!(scratch, fwdI::AbstractVector, fwdJ::AbstractVector, columns::AbstractVector, iplan) + specf = scratch.specf + n = size(specf, 1) + @inbounds for (c, terms) in enumerate(columns) + for lin in 1:n + specf[lin, c] = 0 + end + for (sign, ki, kj) in terms + FI = fwdI[ki] + FJ = fwdJ[kj] + @simd for lin in 1:n + specf[lin, c] += sign * conj(FI[lin]) * FJ[lin] + end + end + end + LA.mul!(scratch.out, iplan, scratch.spec) + return scratch.outf +end + +# --------------------------------------------------------------------------------------------------- +# The engine +# --------------------------------------------------------------------------------------------------- + +SFC.transform_engine(sf, data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, vD::Val, vV::Val, vK::Val, + valid, weights, tag; to = identity) = + _transform_prepare(sf, data, s, dist_be, vD, vV, vK, valid, weights, tag; to) + +function _transform_prepare( + sf, data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + valid, weights, tag; to = identity, +) where {D, V, K} + SFT.is_polynomial_operator(sf) || throw(ArgumentError( + "$(typeof(sf)) is not a polynomial in the increment, so the transform cannot produce it. " * + "Omit the spectral backend for the lag sweep, which evaluates any pairwise operator exactly.", + )) + SFC._check_grid_field(sf, data, s, Val(D), Val(V), Val(K)) + su = SFC.uniform_axes(s) + T = eltype(su.spacing) + r_max = SFC._cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) + P = _pad_dims(s, r_max) + W = V * D + K + p = SFT.order(sf) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + dp0, vp0, wp0 = SFC.separable_layout(s, data, valid, w) + dp = to(dp0) + vp = vp0 isa SFC.AllValid ? vp0 : to(Vector{Bool}(vp0)) + wp = wp0 isa SFC.NoWeights ? wp0 : to(wp0) + fwd, keys, flat = _slab_transforms(tag, s, dp, vp, wp, su, P, Val(W), Val(p); to) + key_index = Dict(k => i for (i, k) in enumerate(keys)) + transport = SFC.lag_transport(s) + columns = SFC._columns(transport, Val(W), Val(p), key_index) + # the count column: the two masks' correlation, the weighted pair mass, or a soft-binned kernel mass + soft = SFC._soft_binned(s) + masked = !(valid isa SFC.AllValid) || !(wp isa SFC.NoWeights) || soft + masked && push!(columns, [(1, key_index[keys[1]], key_index[keys[1]])]) + N = SFC._inverse_count(transport, W, p) + weighted = (wp isa SFC.NoWeights && !soft) ? Val(false) : Val(true) + return (; s, su, P, r_max, fwd, flat, columns, masked, weighted, transport, vW = Val(W), vP = Val(p), + vN = Val(N)) +end + +# Every monomial of degree ≤ Pm of every slab, transformed; the first key is the mask. Each monomial is +# built for all slabs in one broadcast and all slabs are transformed in one batch, so the launch count +# scales with the monomials alone. A scattered schedule's single slab is transformed by the non-uniform +# FFT provider. +function _slab_transforms( + ::SB.AbstractFastFourierTransformSpectralBackend, s::SFC.AbstractSeparableSchedule, dp, vp, wp, su, P, + ::Val{W}, ::Val{Pm}; to, +) where {W, Pm} + keys = SFC._monomial_keys(Val(W), Val(Pm)) + FT = float(eltype(dp)) + Dg = length(P) + nslabs = SFC.n_slabs(s) + nkeys = length(keys) + half = (P[1] ÷ 2 + 1, Base.tail(P)...) + colons = ntuple(_ -> Colon(), Dg) + cells = map(n -> 1:n, su.dims) + # The sweep reads the spectra at every slab pair, so they are all kept; the monomials are scratch and + # are held one bounded batch of slabs at a time. + per_slab = prod(P) * sizeof(FT) + prod(half) * sizeof(Complex{FT}) + chunk = clamp(FORWARD_BATCH_BYTES[] ÷ max(per_slab, 1), 1, nslabs) + spec = similar(parent(dp), Complex{FT}, half..., nkeys * nslabs) + held = similar(parent(dp), FT, P..., chunk) + plan = AbstractFFTs.plan_rfft(held, 1:Dg) + # Scratch for a last batch shorter than the plan, which transforms full width and is copied across; + # a whole batch writes its spectra in place. Empty when the batches divide the slabs. + short = similar(spec, half..., nslabs % chunk == 0 ? 0 : chunk) + for k in 1:nkeys + m = reshape(SFC._held_monomial_vector(dp, vp, wp, keys[k], FT), su.dims..., nslabs) + base = (k - 1) * nslabs + for lo in 1:chunk:nslabs + hi = min(lo + chunk - 1, nslabs) + nb = hi - lo + 1 + fill!(held, zero(FT)) # the padding, and the unused slabs of a short last batch + view(held, cells..., 1:nb) .= view(m, colons..., lo:hi) + if nb == chunk + LA.mul!(view(spec, colons..., (base + lo):(base + hi)), plan, held) + else + LA.mul!(short, plan, held) + view(spec, colons..., (base + lo):(base + hi)) .= view(short, colons..., 1:nb) + end + end + end + fwd = map(1:nslabs) do I + [view(spec, colons..., (k - 1) * nslabs + I) for k in 1:nkeys] + end + return fwd, keys, spec +end + +function _slab_transforms( + tag::SB.AbstractNonUniformFastFourierTransformSpectralBackend, s::SFC.ScatteredModesSchedule, dp, vp, wp, su, P, + ::Val{W}, ::Val{Pm}; to, +) where {W, Pm} + keys = SFC._monomial_keys(Val(W), Val(Pm)) + return [SFC.nufft_monomial_transforms(tag, s, dp, vp, wp, keys, Val(Pm); to)], keys, nothing +end + +# The batched inverse plan over `ncols` columns and the per-task scratch it fills, in the transforms' +# array family. +function _inverse_plan(eng, ncols::Int) + F1 = eng.fwd[1][1] + CT = eltype(F1) + FT = real(CT) + P = eng.P + Ph = size(F1) + proto = fill!(similar(F1, Ph..., ncols), zero(CT)) + iplan = AbstractFFTs.plan_irfft(proto, P[1], 1:length(P)) + make_scratch = () -> begin + spec = fill!(similar(F1, Ph..., ncols), zero(CT)) + out = fill!(similar(F1, FT, P..., ncols), zero(FT)) + (spec = spec, specf = reshape(spec, :, ncols), out = out, outf = reshape(out, :, ncols)) + end + return iplan, make_scratch +end + +function _transform_item!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf, eng, iplan, item::NTuple{4, Int}, scratch, plan, + nb, ::Val{D}, ::Val{V}, ::Val{K}, ::Val{W}, ::Val{Po}, ::Val{N}, +) where {OT, CT, D, V, K, W, Po, N} + I, J = item[1], item[2] + out = _pair_inverse!(scratch, eng.fwd[I], eng.fwd[J], eng.columns, iplan) + s, su, P = eng.s, eng.su, eng.P + T = eltype(su.spacing) + strides = SFC._lag_strides(P) + tr = eng.transport + @inbounds for H in SFC._pair_lags(s, su, I, J, eng.r_max) + h = Tuple(H) + v = SFC._lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(V), Val(K)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + idx = SFC._lag_index(h, P, strides) + n_pairs = SFC._named_pairs(eng.weighted, eng.masked, out, idx, size(out, 2), su, h, self_reverse) + scale = self_reverse ? T(0.5) : one(T) + inv_r = inv(sqrt(r2)) + val = SFC.with_frames(tr, geometry) do frames + SFC._lag_value(tr, sf, out, idx, scale, frames, inv_r, Val(W), Val(Po), Val(N), Val(V), Val(K)) + end + sums[b] += OT(factor * val) + counts[b] += CT(n_pairs) + end + return nothing +end + +function _transform_item!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, sf, eng, iplan, item::NTuple{4, Int}, scratch, plan, + nb, axis_edges, na, second_axis, ::Val{D}, ::Val{V}, ::Val{K}, ::Val{W}, ::Val{Po}, ::Val{N}, +) where {OT, CT, D, V, K, W, Po, N} + I, J = item[1], item[2] + out = _pair_inverse!(scratch, eng.fwd[I], eng.fwd[J], eng.columns, iplan) + s, su, P = eng.s, eng.su, eng.P + T = eltype(su.spacing) + strides = SFC._lag_strides(P) + tr = eng.transport + @inbounds for H in SFC._pair_lags(s, su, I, J, eng.r_max) + h = Tuple(H) + v = SFC._lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(V), Val(K)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + idx = SFC._lag_index(h, P, strides) + n_pairs = SFC._named_pairs(eng.weighted, eng.masked, out, idx, size(out, 2), su, h, self_reverse) + scale = self_reverse ? T(0.5) : one(T) + inv_r = inv(sqrt(r2)) + Mo = SFC._lag_moments(tr, out, idx, scale, nothing, nothing, Val(W), Val(Po), Val(N)) + SFC.with_frames(tr, geometry) do frames + Mi = length(frames) + Mi > 1 && CT <: Integer && throw(ArgumentError( + "a lag that half-turns a periodic direction splits each pair between its two " * + "directions, so a joint histogram over angle needs a floating-point count type; got $CT", + )) + for f in frames + bθ = SFH.digitize(SFC.axis_quantity(second_axis, f.dir, r2), axis_edges) + 1 <= bθ <= na || continue + sums[b, bθ] += OT(factor * SFT.moment_contract(sf, Mo, f.dir * inv_r, Val(V), Val(K)) / Mi) + counts[b, bθ] += CT(n_pairs / Mi) + end + end + end + return nothing +end + +function SFC.gridded_sweep!( + sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + tag::SB.AbstractFastFourierTransformSpectralBackend; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {D, V, K} + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + length(sums) == nb && length(counts) == nb || throw(DimensionMismatch( + "sums and counts must have length $nb; got $(length(sums)) and $(length(counts))", + )) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + SFC._check_weighted_counts(w, eltype(counts)) + _transform_sweep!(sums, counts, backend, sf, data, s, dist_be, plan, nb, Val(D), Val(V), Val(K), valid, w, tag, + nothing) + return sums, counts +end + +function SFC.gridded_sweep!( + sums::AbstractMatrix, counts::AbstractMatrix, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}, + tag::SB.AbstractFastFourierTransformSpectralBackend; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SFC.SeparationAngleAxis, +) where {D, V, K} + SFC._require_directional(s) + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + axis_edges = SFC.BinEdges(axis_be) + na = SFC.n_histogram_bins(axis_edges) + size(sums) == (nb, na) && size(counts) == (nb, na) || throw(DimensionMismatch( + "sums and counts must be ($nb, $na); got $(size(sums)) and $(size(counts))", + )) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + SFC._check_weighted_counts(w, eltype(counts)) + _transform_sweep!(sums, counts, backend, sf, data, s, dist_be, plan, nb, Val(D), Val(V), Val(K), valid, w, tag, + (axis_edges, na, second_axis)) + return sums, counts +end + +# --------------------------------------------------------------------------------------------------- +# The non-uniform FFT route: the same engine on a ScatteredModesSchedule, its forward transforms from +# a NUFFT provider. Counts are a kernel-weighted pair mass and need a floating-point type. +# --------------------------------------------------------------------------------------------------- + +_soft_counts(::Type{CT}) where {CT} = CT <: AbstractFloat ? nothing : throw(ArgumentError( + "the non-uniform FFT route's counts are a kernel-weighted pair mass; pass Float64 counts", +)) + +function SFC.gridded_sweep!( + sums::AbstractVector, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.ScatteredModesSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + tag::SB.AbstractNonUniformFastFourierTransformSpectralBackend; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {CT, D, V, K} + _soft_counts(CT) + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + length(sums) == nb && length(counts) == nb || throw(DimensionMismatch( + "sums and counts must have length $nb; got $(length(sums)) and $(length(counts))", + )) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + _transform_sweep!(sums, counts, backend, sf, data, s, dist_be, plan, nb, Val(D), Val(V), Val(K), valid, w, tag, + nothing) + return sums, counts +end + +function SFC.gridded_sweep!( + sums::AbstractMatrix, counts::AbstractMatrix{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.ScatteredModesSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}, + tag::SB.AbstractNonUniformFastFourierTransformSpectralBackend; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SFC.SeparationAngleAxis, +) where {CT, D, V, K} + _soft_counts(CT) + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + axis_edges = SFC.BinEdges(axis_be) + na = SFC.n_histogram_bins(axis_edges) + size(sums) == (nb, na) && size(counts) == (nb, na) || throw(DimensionMismatch( + "sums and counts must be ($nb, $na); got $(size(sums)) and $(size(counts))", + )) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + _transform_sweep!(sums, counts, backend, sf, data, s, dist_be, plan, nb, Val(D), Val(V), Val(K), valid, w, tag, + (axis_edges, na, second_axis)) + return sums, counts +end + +_scattered_needs_nufft(tag) = throw(ArgumentError( + "a ScatteredModesSchedule sums its pairs by non-uniform FFT, which $(nameof(typeof(tag))) does not name; pass " * + "NonuniformFFTsSpectralBackend() or FINUFFTSpectralBackend(). Auto never selects the soft-binned route.", +)) +_nufft_needs_scattered(s) = throw(ArgumentError( + "a non-uniform FFT tag is for a ScatteredModesSchedule; a $(nameof(typeof(s))) transforms with " * + "FastFourierTransformSpectralBackend().", +)) + +for tagT in (:(SB.AbstractFastFourierTransformSpectralBackend), :(SB.AutoSpectralBackend)) + @eval begin + SFC.gridded_sweep!(::AbstractVector, ::AbstractVector, ::SFT.AbstractPairwiseStructureFunctionType, + ::AbstractMatrix, ::SFC.ScatteredModesSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + tag::$tagT; kwargs...) where {D, V, K} = _scattered_needs_nufft(tag) + SFC.gridded_sweep!(::AbstractMatrix, ::AbstractMatrix, ::SFT.AbstractPairwiseStructureFunctionType, + ::AbstractMatrix, ::SFC.ScatteredModesSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, + ::Val{K}, tag::$tagT; kwargs...) where {D, V, K} = _scattered_needs_nufft(tag) + end +end + +SFC.gridded_sweep!(::AbstractVector, ::AbstractVector, ::SFT.AbstractPairwiseStructureFunctionType, ::AbstractMatrix, + s::SFC.AbstractSeparableSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + ::SB.AbstractNonUniformFastFourierTransformSpectralBackend; kwargs...) where {D, V, K} = + _nufft_needs_scattered(s) +SFC.gridded_sweep!(::AbstractMatrix, ::AbstractMatrix, ::SFT.AbstractPairwiseStructureFunctionType, ::AbstractMatrix, + s::SFC.AbstractSeparableSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}, + ::SB.AbstractNonUniformFastFourierTransformSpectralBackend; kwargs...) where {D, V, K} = + _nufft_needs_scattered(s) + +# --------------------------------------------------------------------------------------------------- +# Tensors on grids: the same engine, with each lag's symmetric moment store binned in place of the +# contraction, and the dense tensor assembled once at the end. +# --------------------------------------------------------------------------------------------------- + +# The transform a tensor sweep runs with: `Auto` is the FFT on a grid, and a tag must match its schedule. +_tensor_tag(tag::SB.AbstractFastFourierTransformSpectralBackend, ::SFC.AbstractSeparableSchedule) = tag +_tensor_tag(tag::SB.AbstractFastFourierTransformSpectralBackend, ::SFC.ScatteredModesSchedule) = _scattered_needs_nufft(tag) +_tensor_tag(tag::SB.AbstractNonUniformFastFourierTransformSpectralBackend, ::SFC.ScatteredModesSchedule) = tag +_tensor_tag(::SB.AbstractNonUniformFastFourierTransformSpectralBackend, s::SFC.AbstractSeparableSchedule) = _nufft_needs_scattered(s) +_tensor_tag(::SB.AbstractAutoSpectralBackend, ::SFC.AbstractSeparableSchedule) = SB.FastFourierTransformSpectralBackend() +_tensor_tag(tag::SB.AbstractAutoSpectralBackend, ::SFC.ScatteredModesSchedule) = _scattered_needs_nufft(tag) + +const TensorTag = Union{SB.AbstractFastFourierTransformSpectralBackend, SB.AbstractNonUniformFastFourierTransformSpectralBackend, + SB.AbstractAutoSpectralBackend} + +function _tensor_engine(order::Val{P}, data, s, dist_be, ::Val{D}, valid, weights, counts, tag) where {P, D} + tag = _tensor_tag(tag, s) + w = SFC._pair_weights(weights, size(data, 2), float(eltype(data))) + SFC._check_weighted_counts(w, eltype(counts)) + SFC._soft_binned(s) && _soft_counts(eltype(counts)) + eng = _transform_prepare(SFT.MomentTensorOperator{P}(), data, s, dist_be, Val(D), Val(1), Val(0), valid, w, tag) + return eng, binomial(D + P - 1, P) +end + +function SFC.gridded_tensor_sweep!( + sums::AbstractArray{OT}, counts::AbstractVector{CT}, order::Val{P}, data::AbstractMatrix, + s::SFC.AbstractSeparableSchedule, dist_be, ::Val{D}, tag::TensorTag; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {OT, CT, P, D} + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + size(sums) == (ntuple(_ -> D, P)..., nb) && length(counts) == nb || throw(DimensionMismatch( + "sums must be $((ntuple(_ -> D, P)..., nb)) and counts of length $nb; got $(size(sums)) and $(length(counts))", + )) + eng, Ns = _tensor_engine(order, data, s, dist_be, Val(D), valid, weights, counts, tag) + iplan, make_scratch = _inverse_plan(eng, length(eng.columns)) + items = SFC.sweep_items(s, eng.r_max, SFC.sweep_tasks(backend), false) + sf = SFT.MomentTensorOperator{P}() + sym = zeros(OT, Ns, nb) + body! = (ls, lc, it, scratch) -> _transform_tensor_item!(ls, lc, sf, eng, iplan, it, scratch, plan, nb, nothing, + Val(D), eng.vW, eng.vP, eng.vN, Val(Ns)) + SFC.sweep_reduce!(sym, counts, backend, items, make_scratch, body!) + SFC._expand_symmetric!(sums, sym, Val(D), Val(P)) + return sums, counts +end + +function SFC.gridded_tensor_sweep!( + sums::AbstractArray{OT}, counts::AbstractMatrix{CT}, order::Val{P}, data::AbstractMatrix, + s::SFC.AbstractSeparableSchedule, dist_be, axis_be, ::Val{D}, tag::TensorTag; + valid = SFC.AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SFC.SeparationAngleAxis, +) where {OT, CT, P, D} + SFC._require_directional(s) + plan = SFC.squared_digitize_plan(dist_be) + nb = SFC.n_histogram_bins(plan) + axis_edges = SFC.BinEdges(axis_be) + na = SFC.n_histogram_bins(axis_edges) + size(sums) == (ntuple(_ -> D, P)..., nb, na) && size(counts) == (nb, na) || throw(DimensionMismatch( + "sums must be $((ntuple(_ -> D, P)..., nb, na)) and counts ($nb, $na); got $(size(sums)) and $(size(counts))", + )) + eng, Ns = _tensor_engine(order, data, s, dist_be, Val(D), valid, weights, counts, tag) + iplan, make_scratch = _inverse_plan(eng, length(eng.columns)) + items = SFC.sweep_items(s, eng.r_max, SFC.sweep_tasks(backend), false) + sf = SFT.MomentTensorOperator{P}() + sym = zeros(OT, Ns, nb, na) + body! = (ls, lc, it, scratch) -> _transform_tensor_item!(ls, lc, sf, eng, iplan, it, scratch, plan, nb, + (axis_edges, na, second_axis), Val(D), eng.vW, eng.vP, + eng.vN, Val(Ns)) + SFC.sweep_reduce!(sym, counts, backend, items, make_scratch, body!) + SFC._expand_symmetric!(sums, sym, Val(D), Val(P)) + return sums, counts +end + +function _transform_tensor_item!( + sym::AbstractMatrix{OT}, counts::AbstractVector{CT}, sf, eng, iplan, item::NTuple{4, Int}, scratch, plan, nb, + ::Nothing, ::Val{D}, ::Val{W}, ::Val{Po}, ::Val{N}, ::Val{Ns}, +) where {OT, CT, D, W, Po, N, Ns} + I, J = item[1], item[2] + out = _pair_inverse!(scratch, eng.fwd[I], eng.fwd[J], eng.columns, iplan) + s, su, P = eng.s, eng.su, eng.P + T = eltype(su.spacing) + strides = SFC._lag_strides(P) + tr = eng.transport + @inbounds for H in SFC._pair_lags(s, su, I, J, eng.r_max) + h = Tuple(H) + v = SFC._lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(1), Val(0)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + idx = SFC._lag_index(h, P, strides) + n_pairs = SFC._named_pairs(eng.weighted, eng.masked, out, idx, size(out, 2), su, h, self_reverse) + scale = self_reverse ? T(0.5) : one(T) + m = SFC._lag_tensor(tr, out, idx, scale, geometry, Val(W), Val(Po), Val(N)) + f = SFC._tensor_factor(tr, factor) + for n in 1:Ns + sym[n, b] += OT(f * m[n]) + end + counts[b] += CT(n_pairs) + end + return nothing +end + +function _transform_tensor_item!( + sym::AbstractArray{OT, 3}, counts::AbstractMatrix{CT}, sf, eng, iplan, item::NTuple{4, Int}, scratch, plan, nb, + axis::Tuple, ::Val{D}, ::Val{W}, ::Val{Po}, ::Val{N}, ::Val{Ns}, +) where {OT, CT, D, W, Po, N, Ns} + axis_edges, na, second_axis = axis + I, J = item[1], item[2] + out = _pair_inverse!(scratch, eng.fwd[I], eng.fwd[J], eng.columns, iplan) + s, su, P = eng.s, eng.su, eng.P + T = eltype(su.spacing) + strides = SFC._lag_strides(P) + tr = eng.transport + @inbounds for H in SFC._pair_lags(s, su, I, J, eng.r_max) + h = Tuple(H) + v = SFC._lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(1), Val(0)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + idx = SFC._lag_index(h, P, strides) + n_pairs = SFC._named_pairs(eng.weighted, eng.masked, out, idx, size(out, 2), su, h, self_reverse) + scale = self_reverse ? T(0.5) : one(T) + m = SFC._lag_tensor(tr, out, idx, scale, geometry, Val(W), Val(Po), Val(N)) + fac = SFC._tensor_factor(tr, factor) + SFC.with_frames(tr, geometry) do frames + Mi = length(frames) + Mi > 1 && CT <: Integer && throw(ArgumentError( + "a lag that half-turns a periodic direction splits each pair between its two " * + "directions, so a joint histogram over angle needs a floating-point count type; got $CT", + )) + for f in frames + bθ = SFH.digitize(SFC.axis_quantity(second_axis, f.dir, r2), axis_edges) + 1 <= bθ <= na || continue + for n in 1:Ns + sym[n, b, bθ] += OT(fac * m[n] / Mi) + end + counts[b, bθ] += CT(n_pairs / Mi) + end + end + end + return nothing +end + +# The CPU engine: one inverse per slab pair, the lags of each read on the host. +function _transform_sweep!( + sums, counts, backend::CB.AbstractExecutionBackend, sf, data, s, dist_be, plan, nb, ::Val{D}, ::Val{V}, + ::Val{K}, valid, weights, tag, axis, +) where {D, V, K} + eng = _transform_prepare(sf, data, s, dist_be, Val(D), Val(V), Val(K), valid, weights, tag) + iplan, make_scratch = _inverse_plan(eng, length(eng.columns)) + items = SFC.sweep_items(s, eng.r_max, SFC.sweep_tasks(backend), false) + body! = _item_body(sf, eng, iplan, plan, nb, axis, Val(D), Val(V), Val(K), eng.vW, eng.vP, eng.vN) + SFC.sweep_reduce!(sums, counts, backend, items, make_scratch, body!) + return nothing +end + +_item_body(sf, eng, iplan, plan, nb, ::Nothing, vD, vV, vK, vW, vP, vN) = + (ls, lc, it, scratch) -> _transform_item!(ls, lc, sf, eng, iplan, it, scratch, plan, nb, vD, vV, vK, vW, vP, vN) + +_item_body(sf, eng, iplan, plan, nb, axis::Tuple, vD, vV, vK, vW, vP, vN) = + (ls, lc, it, scratch) -> _transform_item!(ls, lc, sf, eng, iplan, it, scratch, plan, nb, axis[1], axis[2], + axis[3], vD, vV, vK, vW, vP, vN) + +# A device runs the engine through the KernelAbstractions extension. +_transform_sweep!( + sums, counts, backend::CB.AbstractGPUBackend, sf, data, s, dist_be, plan, nb, vD::Val, vV::Val, vK::Val, + valid, weights, tag, axis, +) = SFC.device_transform_sweep!(sums, counts, backend, sf, data, s, dist_be, plan, nb, vD, vV, vK, valid, weights, + tag, axis) + +# `Auto` is answered here because only this extension knows what a transform would cost: the sweep +# visits every lag of every slab pair over the slab's cells, the transform pays one forward transform +# per monomial per slab and one inverse per raw moment per slab pair, however few lags are wanted. +# Dispatching on the concrete tag out-specialises the core method. +_auto_transform(sf, s, dist_be, W::Int, valid, weights, ::CB.AbstractExecutionBackend) = + _prefers_transform(sf, s, dist_be, W, valid, weights) + +# A device runs only the transform. +_auto_transform(sf, s, dist_be, W::Int, valid, weights, ::CB.AbstractGPUBackend) = true + +function _prefers_transform(sf, s::SFC.AbstractSeparableSchedule, dist_be, W::Int, valid, weights) + SFT.is_polynomial_operator(sf) || return false + su = SFC.uniform_axes(s) + Dg = SFC.grid_dimension(su) + T = eltype(su.spacing) + r_max = SFC._cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) + lims = SFC.lag_limits(s, r_max) + n_lags = prod(ntuple(d -> length(SFC.lag_range(su, d, lims[d])), Dg)) + n = prod(_pad_dims(s, r_max)) + p = SFT.order(sf) + n_pairs = length(SFC.sweep_items(s, r_max, 1, false)) + count_column = (valid isa SFC.AllValid && weights === nothing) ? 0 : 1 + per_pair = SFC._inverse_count(SFC.lag_transport(s), W, p) + count_column + transforms = SFC.n_slabs(s) * binomial(W + p, p) + n_pairs * per_pair + return transforms * n * log2(max(2, n)) < n_pairs * n_lags * SFC.n_cells(su) +end + +function SFC.gridded_sweep!( + sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}, + ::SB.AutoSpectralBackend; valid = SFC.AllValid(), weights = nothing, + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {D, V, K} + return _auto_transform(sf, s, dist_be, V * D + K, valid, weights, backend) ? + SFC.gridded_sweep!(sums, counts, sf, data, s, dist_be, Val(D), Val(V), Val(K), + SB.FastFourierTransformSpectralBackend(); valid, weights, backend) : + SFC.gridded_lag_sweep!(sums, counts, sf, data, s, dist_be, Val(D), Val(V), Val(K); valid, weights, backend) +end + +function SFC.gridded_sweep!( + sums::AbstractMatrix, counts::AbstractMatrix, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::SFC.AbstractSeparableSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}, + ::SB.AutoSpectralBackend; valid = SFC.AllValid(), weights = nothing, + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SFC.SeparationAngleAxis, +) where {D, V, K} + return _auto_transform(sf, s, dist_be, V * D + K, valid, weights, backend) ? + SFC.gridded_sweep!(sums, counts, sf, data, s, dist_be, axis_be, Val(D), Val(V), Val(K), + SB.FastFourierTransformSpectralBackend(); valid, weights, backend, second_axis) : + SFC.gridded_lag_sweep!(sums, counts, sf, data, s, dist_be, axis_be, Val(D), Val(V), Val(K); + valid, weights, backend, second_axis) +end + +# --------------------------------------------------------------------------------------------------- +# Spectra from the lag-space structure function +# --------------------------------------------------------------------------------------------------- + +""" + _trace_lags(mt, ::Val{D}) -> (trace, counts) + +`Σ_pairs ‖δu‖²` and the pair count at every lag of the padded grid, both weighted when the transforms +are. Only the diagonal moment components are formed, so the monomials transformed are the mask, each +component and each square; with every cell held and no weights the count is the box overlap and no +mask transform is taken. +""" +function _trace_lags(mt::MonomialTransforms{FT, Dg}, ::Val{D}) where {FT, Dg, D} + trace = moment_component(mt, (1, 1)) + for d in 2:D + trace .+= moment_component(mt, (d, d)) + end + complete = mt.valid isa SFC.AllValid && mt.weights isa SFC.NoWeights + pc = complete ? nothing : pair_counts(mt) + counts = _count_array(trace, mt.weights) + P = mt.P + @inbounds for I in CartesianIndices(trace) + h = _lag_of_index(Tuple(I), P) + counts[I] = pc === nothing ? _padded_pair_count(mt.schedule, h) : _count_value(pc[I], mt.weights) + end + return trace, counts +end + +_count_array(trace, ::SFC.NoWeights) = similar(trace, Int) +_count_array(trace, ::AbstractVector) = similar(trace) +_count_value(c, ::SFC.NoWeights) = round(Int, c) +_count_value(c, ::AbstractVector) = c + +# The signed lag a position of the padded transform holds. +@inline _lag_of_index(I::NTuple{Dg, Int}, P::NTuple{Dg, Int}) where {Dg} = + ntuple(d -> (m = I[d] - 1; m > P[d] ÷ 2 ? m - P[d] : m), Val(Dg)) + +# Pairs a lag of the padded grid names on a complete field: zero beyond the cells of a bounded direction. +@inline function _padded_pair_count(s::SFC.UniformLagSchedule{Dg}, h::NTuple{Dg, Int}) where {Dg} + n = 1 + @inbounds for d in 1:Dg + n *= s.periodic[d] ? s.dims[d] : max(0, s.dims[d] - abs(h[d])) + end + return n +end + +"""Weighted variance of the held cells about their weighted mean, summed over the field's components.""" +function _held_variance(data::AbstractMatrix, valid, weights) + W, n = size(data) + T = float(eltype(data)) + acc = zero(T) + for c in 1:W + m = zero(T) + k = zero(T) + @inbounds for i in 1:n + valid[i] || continue + w = _cell_weight(weights, i) + m += w * data[c, i] + k += w + end + k > 0 || throw(ArgumentError("no held cell carries weight")) + m /= k + @inbounds for i in 1:n + valid[i] && (acc += _cell_weight(weights, i) * (data[c, i] - m)^2 / k) + end + end + return acc +end + +@inline _cell_weight(::SFC.NoWeights, i) = true +@inline _cell_weight(w::AbstractVector, i) = @inbounds w[i] + +function SFC.gridded_spectrum( + u::AbstractArray, s::SFC.UniformLagSchedule{Dg, T}, ::Val{D}, + ::SB.AbstractFastFourierTransformSpectralBackend; valid = SFC.AllValid(), weights = nothing, + taper::SFC.AbstractTaper = SFC.NoTaper(), + missing_lags::SFC.AbstractMissingLagPolicy = SFC.RefuseMissingLags(), +) where {Dg, T, D} + size(u, 1) == D || throw(DimensionMismatch("field has $(size(u, 1)) components, declared $D")) + data = reshape(u, D, :) + SFC._check_grid_field(SFT.S2SFType(), data, s, Val(D), Val(1), Val(0)) + w = SFC._pair_weights(weights, size(data, 2), T) + # every lag of a bounded direction, |h| < n, transformed linearly: P ≥ 2n − 1; a periodic one needs + # no padding + P = _pad_dims(s, T(Inf)) + mt = MonomialTransforms(data, s, P, valid, w) + trace, counts = _trace_lags(mt, Val(D)) + σ2 = _held_variance(data, valid, w) + r_max = sqrt(sum(d -> (s.periodic[d] ? (s.dims[d] ÷ 2) * s.spacing[d] : (s.dims[d] - 1) * s.spacing[d])^2, + 1:Dg)) + + # C(h) = C(0) − D(h)/2 with C(0) the held cells' variance, weighted by the taper; a lag no held pair + # names is structurally absent beyond a bounded direction's cells and a missing datum within them + cov = similar(trace) + @inbounds for I in CartesianIndices(trace) + h = _lag_of_index(Tuple(I), P) + n = counts[I] + if n > 0 + r = sqrt(sum(d -> (h[d] * s.spacing[d])^2, 1:Dg)) + cov[I] = SFC.taper_weight(taper, r, r_max) * (σ2 - trace[I] / (2n)) + elseif all(d -> s.periodic[d] || abs(h[d]) < s.dims[d], 1:Dg) + cov[I] = _missing_lag_value(missing_lags, h, T) + else + cov[I] = zero(T) + end + end + + density = real.(AbstractFFTs.fft(cov)) .* (prod(abs, s.spacing) / T(2π)^Dg) + wavenumbers = ntuple(d -> T(2π) .* AbstractFFTs.fftfreq(P[d], 1 / abs(s.spacing[d])), Val(Dg)) + return wavenumbers, density +end + +_missing_lag_value(::SFC.RefuseMissingLags, h, ::Type{T}) where {T} = throw(ArgumentError( + "lag $h is named by no pair of held cells, so its structure function is undefined; pass " * + "`missing_lags = ZeroDeviationAtMissingLags()` to set its covariance to zero, or fill the field.", +)) +_missing_lag_value(::SFC.ZeroDeviationAtMissingLags, h, ::Type{T}) where {T} = zero(T) + +end # module diff --git a/ext/StructureFunctionsAbstractFFTsKernelAbstractionsExt.jl b/ext/StructureFunctionsAbstractFFTsKernelAbstractionsExt.jl new file mode 100644 index 0000000..48de798 --- /dev/null +++ b/ext/StructureFunctionsAbstractFFTsKernelAbstractionsExt.jl @@ -0,0 +1,294 @@ +module StructureFunctionsAbstractFFTsKernelAbstractionsExt + +using KernelAbstractions: KernelAbstractions as KA, @index, @atomic, @Const, @localmem, @synchronize +using AbstractFFTs: AbstractFFTs +using LinearAlgebra: LinearAlgebra as LA +using StaticArrays: StaticArrays as SA +using SpectralBackends: SpectralBackends as SB +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, HelperFunctions as SFH + + +"""Bytes of inverse-transform scratch one batch of slab pairs may hold on the device.""" +const DEVICE_BATCH_BYTES = 1 << 30 + +const WORKGROUP = 256 + +# The lag `lin` of the box `lo .+ (0:len-1)`, column-major with the given strides. +@inline _decode_lag(lin::Int, lo::NTuple{Dg, Int}, len::NTuple{Dg, Int}, strides::NTuple{Dg, Int}) where {Dg} = + ntuple(d -> @inbounds(lo[d] + ((lin - 1) ÷ strides[d]) % len[d]), Val(Dg)) + +# The slab pair in `lo:hi` owning work item `item`, from `off`, the exclusive prefix sum of every +# pair's lag-box volume: pair `b` owns `off[b] + 1 : off[b + 1]`. +@inline function _pair_of_item(off, item::Int, lo::Int, hi::Int) + while lo < hi + mid = (lo + hi + 1) >>> 1 + if @inbounds(off[mid]) < item + lo = mid + else + hi = mid - 1 + end + end + return lo +end + +# Column `c` of slab pair `base + b`: the signed products of the two slabs' forward transforms its +# terms name, written to the batch-local column `b`. +KA.@kernel unsafe_indices = true function _spec_kernel!( + specf::AbstractArray{CT}, @Const(F), @Const(terms), @Const(col_ptr), @Const(pairs), base::Int, n::Int, + ncols::Int, total::Int, workgroup_size::Int, +) where {CT} + lid = @index(Local, Linear) + bid = @index(Group, Linear) + gid = (bid - 1) * workgroup_size + lid + if gid <= total + b = (gid - 1) ÷ (n * ncols) + 1 + rem = (gid - 1) - (b - 1) * n * ncols + c = rem ÷ n + 1 + lin = rem - (c - 1) * n + 1 + @inbounds begin + I = Int(pairs[base + b][1]) + J = Int(pairs[base + b][2]) + acc = zero(CT) + for t in Int(col_ptr[c]):(Int(col_ptr[c + 1]) - 1) + sign, ki, kj = terms[t] + acc += sign * conj(F[lin, I, Int(ki)]) * F[lin, J, Int(kj)] + end + specf[lin, c, b] = acc + end + end +end + +# One work item per (lag, slab pair) over the pairs `first_pair:last_pair`: the lag's moment row is +# read from the inverted columns, the operator contracted in the lag's frames and the value binned. A +# distance histogram accumulates in shared memory when it fits and is flushed once per block; the +# joint histogram uses global atomics. Under `UB` every pair carries the same lag box and a work item +# names its pair by division; otherwise the boxes are per pair and `pair_off` indexes them. +KA.@kernel unsafe_indices = true function _lag_kernel!( + sums::AbstractArray{OT}, counts::AbstractArray{CT}, @Const(out), @Const(pairs), sf, s, su, plan, second_axis, + axis_edges, @Const(pair_off), @Const(pair_lo), @Const(pair_len), @Const(pair_str), first_pair::Int, + last_pair::Int, n_box::Int, box_lo, box_len, box_strides, + P, strides, masked::Bool, weighted::Val{WEIGHTED}, ncols::Int, + nb::Int, na::Int, total::Int, workgroup_size::Int, ::Val{D}, ::Val{V}, ::Val{K}, ::Val{W}, ::Val{Po}, ::Val{N}, + ::Val{Dg}, ::Val{UB}, ::Val{NC}, ::Val{SHARED}, +) where {OT, CT, WEIGHTED, D, V, K, W, Po, N, Dg, UB, NC, SHARED} + shared_s = @localmem OT (NC,) + shared_c = @localmem CT (NC,) + lid = @index(Local, Linear) + if SHARED + k = lid + while k <= NC + @inbounds shared_s[k] = zero(OT) + @inbounds shared_c[k] = zero(CT) + k += workgroup_size + end + end + @synchronize + lid = @index(Local, Linear) + bid = @index(Group, Linear) + gid = (bid - 1) * workgroup_size + lid + if gid <= total + if UB + g = first_pair + (gid - 1) ÷ n_box + lin = gid - (g - first_pair) * n_box + h = _decode_lag(lin, box_lo, box_len, box_strides) + else + item = gid + @inbounds(pair_off[first_pair]) + g = _pair_of_item(pair_off, item, first_pair, last_pair) + lin = item - @inbounds(pair_off[g]) + blo = @inbounds pair_lo[g] + blen = @inbounds pair_len[g] + bstr = @inbounds pair_str[g] + h = _decode_lag(lin, ntuple(d -> Int(blo[d]), Val(Dg)), ntuple(d -> Int(blen[d]), Val(Dg)), + ntuple(d -> Int(bstr[d]), Val(Dg))) + end + b = g - first_pair + 1 + I = Int(@inbounds pairs[g][1]) + J = Int(@inbounds pairs[g][2]) + v = SFC._lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(V), Val(K)) + if v !== nothing + bin, r2, factor, geometry, self_reverse = v + idx = SFC._lag_index(h, P, strides) + outb = view(out, :, :, b) + T = eltype(su.spacing) + n_pairs = SFC._named_pairs(weighted, masked, outb, idx, ncols, su, h, self_reverse) + scale = self_reverse ? T(0.5) : one(T) + inv_r = inv(sqrt(r2)) + tr = SFC.lag_transport(s) + if second_axis === nothing + val = SFC.with_frames(tr, geometry) do frames + SFC._lag_value(tr, sf, outb, idx, scale, frames, inv_r, Val(W), Val(Po), Val(N), Val(V), Val(K)) + end + if SHARED + @atomic shared_s[bin] += OT(factor * val) + @atomic shared_c[bin] += CT(n_pairs) + else + @atomic sums[bin] += OT(factor * val) + @atomic counts[bin] += CT(n_pairs) + end + else + Mo = SFC._lag_moments(tr, outb, idx, scale, nothing, nothing, Val(W), Val(Po), Val(N)) + SFC.with_frames(tr, geometry) do frames + Mi = length(frames) + for f in frames + bθ = SFH.digitize(SFC.axis_quantity(second_axis, f.dir, r2), axis_edges) + if 1 <= bθ <= na + cell = bin + (bθ - 1) * nb + value = OT(factor * SFT.moment_contract(sf, Mo, f.dir * inv_r, Val(V), Val(K)) / Mi) + @atomic sums[cell] += value + @atomic counts[cell] += CT(n_pairs / Mi) + end + end + end + end + end + end + @synchronize + lid = @index(Local, Linear) + if SHARED + k = lid + while k <= NC + @inbounds begin + sv = shared_s[k] + cv = shared_c[k] + if !iszero(cv) || !iszero(sv) + @atomic sums[k] += sv + @atomic counts[k] += cv + end + end + k += workgroup_size + end + end +end + +# Every column's terms as one flat table with per-column offsets. +function _term_table(columns) + terms = NTuple{3, Int32}[] + col_ptr = Int32[1] + for col in columns + for (sign, ki, kj) in col + push!(terms, (Int32(sign), Int32(ki), Int32(kj))) + end + push!(col_ptr, Int32(length(terms) + 1)) + end + return terms, col_ptr +end + +_axis_parts(::Nothing) = (nothing, nothing, 1) +_axis_parts(axis::Tuple) = (axis[1], SFC.SeparationAngleAxis(SA.SVector{length(axis[3].reference_axis)}(axis[3].reference_axis)), axis[2]) + +# Inverse scratch for `Bb` slab pairs and the plan that fills it, in the transforms' array family. +function _batch_buffers(F1, P, ncols::Int, Bb::Int) + CF = eltype(F1) + spec = fill!(similar(F1, size(F1)..., ncols * Bb), zero(CF)) + out = fill!(similar(F1, real(CF), P..., ncols * Bb), zero(real(CF))) + return (spec = spec, out = out, iplan = AbstractFFTs.plan_irfft(spec, P[1], 1:length(P))) +end + +function SFC.device_transform_sweep!( + sums::AbstractArray{OT}, counts::AbstractArray{CT}, backend::SFC.CB.AbstractGPUBackend, sf, data, s, dist_be, plan, + nb::Int, ::Val{D}, ::Val{V}, ::Val{K}, valid, weights, tag, axis, +) where {OT, CT, D, V, K} + dev = backend.backend + to = x -> KA.adapt(dev, x) + eng = SFC.transform_engine(sf, data, s, dist_be, Val(D), Val(V), Val(K), valid, weights, tag; to) + su, P, r_max = eng.su, eng.P, eng.r_max + Dg = length(P) + F1 = eng.fwd[1][1] + CF = eltype(F1) + FT = real(CF) + nlin = length(F1) + nkeys = length(eng.fwd[1]) + nslabs = length(eng.fwd) + # The forward stage holds every spectrum in one array, slab-fastest within a monomial, which is the + # layout this kernel reads, so it is reshaped. Separate transforms from a provider are gathered. + F = if eng.flat === nothing + G = similar(F1, nlin, nslabs, nkeys) + for I in 1:nslabs, k in 1:nkeys + view(G, :, I, k) .= vec(eng.fwd[I][k]) + end + G + else + reshape(eng.flat, nlin, nslabs, nkeys) + end + terms, col_ptr = _term_table(eng.columns) + d_terms, d_ptr = to(terms), to(col_ptr) + ncols = length(eng.columns) + items = SFC.sweep_items(s, r_max, 1, false) + pairs = [(Int32(it[1]), Int32(it[2])) for it in items] + n_items = length(pairs) + lims = SFC.lag_limits(s, r_max) + box_lo = ntuple(d -> first(SFC.lag_range(su, d, lims[d])), Dg) + box_len = ntuple(d -> length(SFC.lag_range(su, d, lims[d])), Dg) + n_box = prod(box_len) + box_strides = SFC._lag_strides(box_len) + # A schedule whose pairs do not share one lag box gets a box each, the same one the host loop + # takes from `_pair_lags`: a parallel spans less distance the nearer it lies to a pole, so the box + # over all row pairs stays as wide as the equator's however small `r_max` is. The tables are built + # and moved once per call and the kernel finds a work item's pair in the prefix sum of the volumes. + UB = SFC.uniform_lag_box(s) + pair_off, d_off, d_plo, d_plen, d_pstr = if UB + nothing, nothing, nothing, nothing, nothing + else + boxes = [SFC.lag_limits(s, it[1], it[2], r_max) for it in items] + lens = NTuple{Dg, Int}[ntuple(d -> length(SFC.lag_range(su, d, L[d])), Dg) for L in boxes] + los = NTuple{Dg, Int32}[ntuple(d -> Int32(first(SFC.lag_range(su, d, L[d]))), Dg) for L in boxes] + offs = Vector{Int}(undef, n_items + 1) + offs[1] = 0 + for k in 1:n_items + offs[k + 1] = offs[k] + prod(lens[k]) + end + offs, to(offs), to(los), + to(NTuple{Dg, Int32}[ntuple(d -> Int32(l[d]), Dg) for l in lens]), + to(NTuple{Dg, Int32}[ntuple(d -> Int32(st[d]), Dg) for st in map(SFC._lag_strides, lens)]) + end + strides = SFC._lag_strides(P) + Pn = prod(P) + axis_edges, second_axis, na = _axis_parts(axis) + if axis !== nothing && CT <: Integer && + any(d -> su.periodic[d] && iseven(su.dims[d]) && lims[d] >= su.dims[d] ÷ 2, 1:Dg) + throw(ArgumentError( + "a lag that half-turns a periodic direction splits each pair between its two directions, so a " * + "joint histogram over angle needs a floating-point count type; got $CT", + )) + end + d_axis_edges = axis_edges === nothing ? nothing : to(axis_edges) + s_dev = to(s) + plan_dev = to(plan) + cells = nb * na + shared = axis === nothing && cells * (sizeof(OT) + sizeof(CT)) <= SFC.GPU_SMEM_STATIC_MAX ÷ 2 + NC = shared ? cells : 1 + dsums = KA.zeros(dev, OT, size(sums)...) + dcounts = KA.zeros(dev, CT, size(counts)...) + per_pair = nlin * ncols * sizeof(CF) + Pn * ncols * sizeof(FT) + # Equal batches no larger than the budget, sharing one buffer set: both kernels are launched over the + # pairs their batch holds, so a short last batch leaves the trailing columns untouched. + n_batches = cld(n_items, clamp(DEVICE_BATCH_BYTES ÷ per_pair, 1, n_items)) + B = cld(n_items, n_batches) + spec_k = _spec_kernel!(dev, WORKGROUP) + lag_k = _lag_kernel!(dev, WORKGROUP) + spec, out, iplan = _batch_buffers(F1, P, ncols, B) + specf = reshape(spec, nlin, ncols, B) + out3 = reshape(out, Pn, ncols, B) + d_pairs = to(pairs) + for lo in 1:B:n_items + hi = min(lo + B - 1, n_items) + Bb = hi - lo + 1 + total_spec = nlin * ncols * Bb + spec_k(specf, F, d_terms, d_ptr, d_pairs, lo - 1, nlin, ncols, total_spec, WORKGROUP; + ndrange = cld(total_spec, WORKGROUP) * WORKGROUP) + KA.synchronize(dev) + LA.mul!(out, iplan, spec) + total_lag = UB ? n_box * Bb : pair_off[hi + 1] - pair_off[lo] + lag_k(dsums, dcounts, out3, d_pairs, sf, s_dev, su, plan_dev, second_axis, d_axis_edges, + d_off, d_plo, d_plen, d_pstr, lo, hi, n_box, box_lo, box_len, box_strides, + P, strides, eng.masked, eng.weighted, ncols, nb, na, total_lag, WORKGROUP, Val(D), + Val(V), Val(K), eng.vW, eng.vP, eng.vN, Val(Dg), Val(UB), Val(NC), Val(shared); + ndrange = cld(total_lag, WORKGROUP) * WORKGROUP) + KA.synchronize(dev) + end + sums .+= Array(dsums) + counts .+= Array(dcounts) + return nothing +end + +end # module diff --git a/ext/StructureFunctionsBesselsExt.jl b/ext/StructureFunctionsBesselsExt.jl index 566bdaf..ff2037b 100644 --- a/ext/StructureFunctionsBesselsExt.jl +++ b/ext/StructureFunctionsBesselsExt.jl @@ -3,8 +3,7 @@ module StructureFunctionsBesselsExt using Bessels: Bessels using StructureFunctions: Calculations as SFC -# Each order is its own method, so every one is strictly more specific than the core fallback and -# adds to it rather than replacing it. +# Each order is its own method, strictly more specific than the core fallback, so it adds to it. @inline SFC.bessel_kernel(::Val{0}, x) = Bessels.besselj0(x) @inline SFC.bessel_kernel(::Val{1}, x) = Bessels.besselj1(x) @inline SFC.bessel_kernel(::Val{2}, x) = Bessels.besselj(2, x) diff --git a/ext/StructureFunctionsCUDAExt.jl b/ext/StructureFunctionsCUDAExt.jl index adb4b07..8172658 100644 --- a/ext/StructureFunctionsCUDAExt.jl +++ b/ext/StructureFunctionsCUDAExt.jl @@ -2,10 +2,9 @@ CUDA-specialized fast structure-function kernels. Loaded automatically when **both** `KernelAbstractions` and `CUDA` are present. -Provides the settled-optimal GPU kernels (N-body broadcast + privatized / -dynamic-shared histograms) for NVIDIA GPUs, overriding the portable -KernelAbstractions tiled kernels in `StructureFunctionsKernelAbstractionsExt` (which remain the -CPU/AMD reference). See `gpu/OPTIMAL_KERNEL_DESIGN.md`. +Provides N-body broadcast kernels with privatized or dynamic-shared histograms for NVIDIA GPUs, +overriding the portable KernelAbstractions tiled kernels in +`StructureFunctionsKernelAbstractionsExt`, which remain the CPU and GPU reference. These kernels use CUDA-only intrinsics not exposed by KernelAbstractions: `CuDynamicSharedArray` (>48 KB dynamic shared via the opt-in attribute), @@ -63,8 +62,8 @@ function SFC.gpu_fast_launch_1d_batch!( Int(N), Int(NB), Int(B), Int(D), Int(nmom), fixed_x, geom, cull) end -# Real device numbers instead of the universal floor. Reached only through the CUDABackend hook, so -# a device exists by construction and a query failure is a genuine driver fault, not a fallback. +# The real device numbers. Reached only through the CUDABackend hook, so a device exists by +# construction and a query failure is a driver fault. function SFC.gpu_device_caps(::CUDA.CUDABackend) dev = CUDA.device() return SFC.GPUDeviceCaps( diff --git a/ext/StructureFunctionsCairoMakieExt.jl b/ext/StructureFunctionsCairoMakieExt.jl deleted file mode 100644 index 1b07d63..0000000 --- a/ext/StructureFunctionsCairoMakieExt.jl +++ /dev/null @@ -1,7 +0,0 @@ -module StructureFunctionsCairoMakieExt - -using CairoMakie: CairoMakie -using StructureFunctions: StructureFunctions as SF - - -end # module diff --git a/ext/StructureFunctionsDistributedExt.jl b/ext/StructureFunctionsDistributedExt.jl index b5038b8..8c9a62d 100644 --- a/ext/StructureFunctionsDistributedExt.jl +++ b/ext/StructureFunctionsDistributedExt.jl @@ -135,8 +135,8 @@ function SFC._dispatch_execution_backend( chunks = _dist_batch_chunks(B, Distributed.nworkers()) # Each worker computes its contiguous b-chunk locally via the inner backend, requesting the raw # accumulator so partials can be concatenated; the public boundary finalizes. The b-slice is the - # pmap ITEM, not a closure capture: `pmap` re-serializes the closure on every `remotecall`, so - # capturing `u_flat` would ship the whole batch to every worker instead of its own 1/nw share. + # pmap ITEM, not a closure capture: `pmap` re-serializes the closure on every `remotecall`, so a + # captured `u_flat` ships the whole batch to every worker, not its own 1/nw share. items = [(fixed_x ? x_flat : x_flat[:, :, bc], u_flat[:, :, bc]) for bc in chunks] parts = Distributed.pmap(items) do xu r = SFC.calculate_structure_function( @@ -461,20 +461,20 @@ end # --- Tensor structure functions --- # Each worker takes a balanced share of the outer index and returns its own accumulators, which add -# because a histogram is order-independent. `pmap` over the chunk list rather than a closure capture, -# so the inputs are serialised once per item rather than per remotecall. +# because a histogram is order-independent. `pmap` takes the chunk list as items, so the inputs are +# serialised once per item; a closure capture would re-serialise them on every remotecall. function SFC.distributed_calculate_structure_function_tensor!( sums::AbstractArray, counts::AbstractArray, order::Val{P}, shape::SFC.AbstractFieldShape{D}, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; - distance_metric::DI.PreMetric = DI.Euclidean(), + distance_metric::DI.PreMetric = DI.Euclidean(), axis = nothing, ) where {P, D} N = size(u, 2) chunks = SFC._balanced_index_chunks(N, max(Distributed.nworkers(), 1)) CT = eltype(counts) partials = Distributed.pmap(chunks) do chunk SFC.tensor_partial(order, shape, x, u, distance_bins, chunk; - distance_metric, count_eltype = CT) + distance_metric, count_eltype = CT, axis) end for (ps, pc) in partials sums .+= ps @@ -484,21 +484,21 @@ function SFC.distributed_calculate_structure_function_tensor!( end -# --- Multi-channel (`Fields`) sweeps --- +# --- Multi-field (`Fields`) sweeps --- function SFC.distributed_calculate_structure_function!( sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::SFC.CH.Fields, distance_bins; + x::AbstractMatrix, f::SFC.MF.Fields, distance_bins; verbose::Bool = true, show_progress::Bool = true, kwargs..., ) _ = show_progress - verbose && @info("calculating multi-channel structure function (distributed)") - N = size(SFC.CH.packed(f), 2) + verbose && @info("calculating multi-field structure function (distributed)") + N = size(SFC.MF.packed(f), 2) chunks = SFC._balanced_index_chunks(N - 1, max(Distributed.nworkers(), 1)) CT = eltype(counts) partials = Distributed.pmap(chunks) do chunk - SFC.channel_partial(sf, x, f, distance_bins, chunk; count_eltype = CT, kwargs...) + SFC.field_partial(sf, x, f, distance_bins, chunk; count_eltype = CT, kwargs...) end for (ps, pc) in partials sums .+= ps diff --git a/ext/StructureFunctionsFFTExt.jl b/ext/StructureFunctionsFFTExt.jl deleted file mode 100644 index 52db0c7..0000000 --- a/ext/StructureFunctionsFFTExt.jl +++ /dev/null @@ -1,234 +0,0 @@ -module StructureFunctionsFFTExt - -using AbstractFFTs: AbstractFFTs, plan_rfft, irfft -using StaticArrays: StaticArrays as SA -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT -using SpectralBackends: SpectralBackends as SB - -""" - _pad_dims(schedule) -> NTuple{Dg, Int} - -Transform length per direction. A periodic direction needs none — the circular correlation is the -sum wanted. A bounded one is padded past `2n - 1` so the circular correlation equals the linear one, -rounded up to a length the transform factors well. -""" -@inline _pad_dims(s::SFC.UniformLagSchedule{Dg}) where {Dg} = - ntuple(d -> @inbounds(s.periodic[d]) ? @inbounds(s.dims[d]) : - nextprod((2, 3, 5), 2 * @inbounds(s.dims[d]) - 1), Val(Dg)) - -"""Embed `src` at the origin of a zero array of size `P`.""" -function _embed(src::AbstractArray{FT, Dg}, P::NTuple{Dg, Int}) where {FT, Dg} - out = zeros(FT, P) - out[map(n -> 1:n, size(src))...] = src - return out -end - -"""Column-major index of the pair `(a, b)`, `a ≤ b`, among the `D(D+1)/2` distinct components.""" -@inline function _tri_index(D::Int, a::Int, b::Int) - i, j = minmax(a, b) - return (i - 1) * D - ((i - 1) * i) ÷ 2 + j -end - -""" - _increment_tensor_spectra(u, schedule, P) -> (tensor_arrays, D) - -`T[a,b]` for every lag at once, as one array per distinct `(a, b)`. - -`Σ_x δu_a δu_b` expands into four correlations of the padded field — `⟨m, u_a u_b⟩`, its reverse, -and the two `⟨u_a, u_b⟩` — each a product in the transform domain, so the whole tensor for all lags -costs `1 + D + D(D+1)/2` forward transforms and `D(D+1)/2` inverse ones. The mask is what makes the -padding inert: outside the real region it is zero, so no padded cell enters a sum. -""" -function _increment_tensor_spectra( - u::AbstractArray{FT}, s::SFC.UniformLagSchedule{Dg}, P::NTuple{Dg, Int}, valid, -) where {FT, Dg} - D = size(u, 1) - cells = ntuple(d -> s.dims[d], Val(Dg)) - n = prod(cells) - uf = reshape(u, D, n) - F = plan_rfft(zeros(FT, P)) - - # An empty cell contributes to nothing, so its field is replaced by zero rather than multiplied - # by the mask: it may hold NaN, and NaN * 0 is NaN, which one transform would spread everywhere. - w = reshape([valid[k] ? one(FT) : zero(FT) for k in 1:n], cells) - held(a) = reshape([valid[k] ? uf[a, k] : zero(FT) for k in 1:n], cells) - - m̂ = F * _embed(w, P) - p̂ = ntuple(a -> F * _embed(held(a), P), D) - q̂ = [F * _embed(held(a) .* held(b), P) for a in 1:D for b in a:D] - - tensors = Vector{Array{FT, Dg}}(undef, D * (D + 1) ÷ 2) - for a in 1:D, b in a:D - k = _tri_index(D, a, b) - spec = @. conj(m̂) * q̂[k] + conj(q̂[k]) * m̂ - conj(p̂[a]) * p̂[b] - conj(p̂[b]) * p̂[a] - tensors[k] = irfft(spec, P[1]) - end - # Pairs with both ends held, for every lag at once. Only needed where cells are missing: with a - # complete field the count is exact arithmetic, and a transform would need rounding. - pair_counts = valid isa SFC.AllValid ? nothing : irfft(@.(conj(m̂) * m̂), P[1]) - return tensors, pair_counts, D -end - -"""Pairs a lag names, exactly: every cell on a wrapping direction, the overlap on a bounded one.""" -@inline _lag_pair_count(s::SFC.UniformLagSchedule{Dg}, h::NTuple{Dg, Int}) where {Dg} = - prod(ntuple(d -> @inbounds(s.periodic[d]) ? @inbounds(s.dims[d]) : - @inbounds(s.dims[d]) - abs(h[d]), Val(Dg))) - -"""Position of lag `h` in a transform of size `P`, wrapping the negative offsets.""" -@inline _lag_index(h::NTuple{Dg, Int}, P::NTuple{Dg, Int}) where {Dg} = - CartesianIndex(ntuple(d -> mod(h[d], P[d]) + 1, Val(Dg))) - -function SFC.gridded_sweep!( - sums::AbstractVector{OT}, counts::AbstractVector{CT}, - sf::SFT.AbstractPairwiseStructureFunctionType, - u::AbstractArray, s::SFC.UniformLagSchedule{Dg, T}, dist_be, ::Val{D}, - ::SB.AbstractFastFourierTransformSpectralBackend; valid = SFC.AllValid(), -) where {OT, CT, Dg, T, D} - SFC.is_quadratic_operator(sf) || throw(ArgumentError( - "$(typeof(sf)) is not a quadratic form in δu, so it is not a contraction of the " * - "second-order increment tensor the transform produces. Omit the spectral backend for " * - "the lag sweep, which evaluates any pairwise operator exactly.", - )) - size(u)[2:end] == s.dims || throw(DimensionMismatch( - "field cells $(size(u)[2:end]) do not match the schedule's dims $(s.dims)", - )) - - plan = SFC.squared_digitize_plan(dist_be) - nb = SFC.n_histogram_bins(plan) - P = _pad_dims(s) - tensors, pair_counts, Du = _increment_tensor_spectra(u, s, P, valid) - Du == D || throw(DimensionMismatch("field has $Du components, declared $D")) - - r_max = SFC._cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) - lags = ntuple(d -> SFC.lag_range(s, d, r_max), Val(Dg)) - - for H in CartesianIndices(lags) - h = Tuple(H) - all(iszero, h) && continue - hn = ntuple(d -> SFC._lag_negate(s, d, h[d]), Val(Dg)) - h < hn && continue - dx = SA.SVector{D, T}(ntuple(d -> d <= Dg ? T(h[d]) * s.spacing[d] : zero(T), Val(D))) - r2 = sum(abs2, dx) - b = SFC.squared_digitize(plan, r2) - 1 <= b <= nb || continue - - idx = _lag_index(h, P) - Tm = SA.SMatrix{D, D, T}( - (a <= D && bb <= D ? tensors[_tri_index(D, a, bb)][idx] : zero(T) - for a in 1:D, bb in 1:D)..., - ) - n_pairs = pair_counts === nothing ? _lag_pair_count(s, h) : - round(Int, pair_counts[idx]) - # A self-reverse lag's tensor sums each pair twice; `δu` flips between the two visits and the - # tensor is even in it, so the sum is exactly doubled. - if h == hn - Tm = Tm / 2 - n_pairs ÷= 2 - end - - amb = SFC._ambiguous_dirs(s, h) - val = _mean_over_images(sf, Tm, dx, r2, amb, Val(Dg)) - sums[b] += OT(val) - counts[b] += CT(n_pairs) - end - return sums, counts -end - -# The separation direction is not unique where a lag half-turns a periodic direction, so the -# contraction is averaged over the equal-length images, exactly as the lag sweep does. -@inline function _mean_over_images(sf, Tm, dx, r2, amb::NTuple{Dg, Bool}, ::Val{Dg}) where {Dg} - go(vk) = begin - images = SFC._lag_images(dx, amb, vk) - acc = SFC.increment_tensor_value(sf, Tm, images[1] / sqrt(r2)) - for m in 2:length(images) - acc += SFC.increment_tensor_value(sf, Tm, images[m] / sqrt(r2)) - end - acc / length(images) - end - K = count(amb) - K == 0 && return go(Val(0)) - K == 1 && return go(Val(1)) - K == 2 && return go(Val(2)) - K == 3 && return go(Val(3)) - return go(Val(K)) -end - -# `Auto` is answered here because only this extension knows what a transform would cost: the sweep -# visits `n_lags` lags over `M` cells, the transform pays `O(M_padded log M_padded)` per component -# pair however few lags are wanted. Dispatching on the concrete tag out-specialises the core method. -function SFC.gridded_sweep!( - sums, counts, sf, u, s::SFC.UniformLagSchedule{Dg, T}, dist_be, ::Val{D}, - ::SB.AutoSpectralBackend; valid = SFC.AllValid(), -) where {Dg, T, D} - SFC.is_quadratic_operator(sf) || - return SFC.gridded_lag_sweep!(sums, counts, sf, u, s, dist_be, Val(D); valid) - r_max = SFC._cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) - n_lags = prod(ntuple(d -> length(SFC.lag_range(s, d, r_max)), Val(Dg))) - P = _pad_dims(s) - transforms = 1 + D + D * (D + 1) # forward and inverse together - sweep_cost = n_lags * prod(s.dims) - fft_cost = transforms * prod(P) * log2(max(2, prod(P))) - return fft_cost < sweep_cost ? - SFC.gridded_sweep!(sums, counts, sf, u, s, dist_be, Val(D), - SB.FastFourierTransformSpectralBackend(); valid) : - SFC.gridded_lag_sweep!(sums, counts, sf, u, s, dist_be, Val(D); valid) -end - -""" - _lag_space_second_order(u, schedule, P, valid) -> Array - -`⟨‖δu‖²⟩` at every lag, as an average over the pairs that lag actually holds. - -The tensor arrays hold sums, so each is divided by its own pair count: with cells missing that count -is the mask autocorrelation and varies from lag to lag. -""" -function _lag_space_second_order(u, s::SFC.UniformLagSchedule{Dg, T}, P, valid) where {Dg, T} - tensors, pair_counts, D = _increment_tensor_spectra(u, s, P, valid) - trace = zeros(T, size(first(tensors))) - for a in 1:D - trace .+= tensors[_tri_index(D, a, a)] - end - out = similar(trace) - @inbounds for I in CartesianIndices(trace) - h = ntuple(d -> let m = Tuple(I)[d] - 1 - m > P[d] ÷ 2 ? m - P[d] : m - end, Val(Dg)) - n = pair_counts === nothing ? _lag_pair_count(s, h) : round(Int, pair_counts[I]) - n <= 0 && throw(ArgumentError( - "lag $h is named by no pair, so its structure function is undefined; the mask is too " * - "sparse for a lag-space transform.", - )) - out[I] = trace[I] / n - end - return out -end - -function SFC.gridded_spectrum( - u::AbstractArray, s::SFC.UniformLagSchedule{Dg, T}, ::Val{D}, - ::SB.AbstractFastFourierTransformSpectralBackend; valid = SFC.AllValid(), -) where {Dg, T, D} - all(s.periodic) || throw(ArgumentError( - "a lag-space transform needs every direction periodic; a bounded direction has no natural " * - "Fourier basis and its spectrum depends on a windowing choice this does not make.", - )) - size(u)[2:end] == s.dims || throw(DimensionMismatch( - "field cells $(size(u)[2:end]) do not match the schedule's dims $(s.dims)", - )) - P = _pad_dims(s) # every direction periodic, so this is `dims` - s2 = _lag_space_second_order(u, s, P, valid) - - # C(h) = C(0) - S₂(h)/2, and a constant transforms to k = 0 alone, so every other wavenumber - # follows from S₂ by itself. - ncells = prod(ntuple(d -> s.dims[d], Val(Dg))) - modes = real.(AbstractFFTs.fft(s2)) .* (-inv(2 * ncells)) - - dk = ntuple(d -> T(2π) / (s.dims[d] * s.spacing[d]), Val(Dg)) - density = modes ./ prod(dk) - # k = 0 carries the mean and the variance, neither of which a structure function knows - density[ntuple(_ -> 1, Val(Dg))...] = zero(T) - - wavenumbers = ntuple(d -> T(2π) .* AbstractFFTs.fftfreq(s.dims[d], 1 / s.spacing[d]), Val(Dg)) - return wavenumbers, density -end - -end # module diff --git a/ext/StructureFunctionsFINUFFTExt.jl b/ext/StructureFunctionsFINUFFTExt.jl new file mode 100644 index 0000000..0231417 --- /dev/null +++ b/ext/StructureFunctionsFINUFFTExt.jl @@ -0,0 +1,66 @@ +module StructureFunctionsFINUFFTExt + +using FINUFFT: FINUFFT +using StructureFunctions: StructureFunctions as SF, Calculations as SFC + +# FINUFFT's type-1 transform of complex strengths with `iflag = -1` is `Σ_j c_j e^{-i k·θ_j}` on the +# mode grid, in FFT order under `modeord = 1`. Two real monomials ride in one complex transform, +# `c = μ₁ + i μ₂`, and their half spectra are read off it as `F₁(k) = (F(k) + conj F(−k))/2` and +# `F₂(k) = (F(k) − conj F(−k))/2i`; every transform of the point set is one batched plan. +function SFC.nufft_monomial_transforms( + tag::SFC.FINUFFTSpectralBackend, s::SFC.ScatteredModesSchedule{Dg, T}, + data::AbstractMatrix, valid, weights, keys, ::Val{Pm}; to = identity, +) where {Dg, T, Pm} + FT = float(eltype(data)) + θ = ntuple(d -> to(FT.(SFC.mode_coordinates(s, d))), Val(Dg)) + N = size(data, 2) + nkeys = length(keys) + ntrans = cld(nkeys, 2) + strengths = similar(θ[1], Complex{FT}, N, ntrans) + for j in 1:ntrans + a = SFC._held_monomial_vector(data, valid, weights, keys[2j - 1], FT) + if 2j <= nkeys + b = SFC._held_monomial_vector(data, valid, weights, keys[2j], FT) + view(strengths, :, j) .= complex.(a, b) + else + view(strengths, :, j) .= complex.(a) + end + end + # Unpacking a mode needs its negation, so the transform is taken on the mode set closed under + # negation, `−⌊M/2⌋ … ⌊M/2⌋`: the schedule's own set when a direction holds an odd number of modes, + # one mode more when it holds an even number, whose `−M/2` the schedule's set lacks. + grid = ntuple(d -> 2 * (s.modes[d] ÷ 2) + 1, Val(Dg)) + full = similar(θ[1], Complex{FT}, grid..., ntrans) + SFC.nufft_type1!(tag, full, strengths, θ, grid) + half = ntuple(d -> d == 1 ? s.modes[1] ÷ 2 + 1 : s.modes[d], Val(Dg)) + pos = ntuple(d -> to([_grid_index(SFC._mode_integer(i, s.modes[d], d == 1), grid[d]) for i in 1:half[d]]), + Val(Dg)) + neg = ntuple(d -> to([_grid_index(-SFC._mode_integer(i, s.modes[d], d == 1), grid[d]) for i in 1:half[d]]), + Val(Dg)) + taper = SFC.mode_taper_weights(s, FT, half, to) + return map(1:nkeys) do n + F = view(full, ntuple(_ -> Colon(), Val(Dg))..., cld(n, 2)) + Fp = F[pos...] + Fm = conj.(F[neg...]) + û = isodd(n) ? (Fp .+ Fm) ./ 2 : (Fp .- Fm) ./ (2im) + taper === nothing || (û .*= taper) + û + end +end + +"""Position of mode `k` in a grid of `n` modes in FFT order.""" +@inline _grid_index(k::Int, n::Int) = k >= 0 ? k + 1 : k + n + 1 + +function SFC.nufft_type1!(tag::SFC.FINUFFTSpectralBackend, full::Array, strengths::Array, θ::Tuple{Vararg{Array}}, modes) + plan = FINUFFT.finufft_makeplan(1, collect(Int64, modes), -1, size(strengths, 2), tag.tolerance; + dtype = eltype(θ[1]), modeord = 1) + try + FINUFFT.finufft_setpts!(plan, θ...) + FINUFFT.finufft_exec!(plan, strengths, full) + finally + FINUFFT.finufft_destroy!(plan) + end + return full +end + +end # module diff --git a/ext/StructureFunctionsFINUFFTKernelAbstractionsExt.jl b/ext/StructureFunctionsFINUFFTKernelAbstractionsExt.jl new file mode 100644 index 0000000..0e49ee4 --- /dev/null +++ b/ext/StructureFunctionsFINUFFTKernelAbstractionsExt.jl @@ -0,0 +1,32 @@ +module StructureFunctionsFINUFFTKernelAbstractionsExt + +using FINUFFT: FINUFFT +using KernelAbstractions: KernelAbstractions as KA +using StructureFunctions: Calculations as SFC + +SFC.nufft_type1!(tag::SFC.FINUFFTSpectralBackend, full::AbstractArray, strengths::AbstractArray, θ::Tuple, modes) = + _type1!(KA.get_backend(full), tag, full, strengths, θ, modes) + +# cuFINUFFT's names exist once `using CUDA` has loaded FINUFFT's device interface, so they are looked up +# here and never named in a signature. +function _type1!(backend::KA.GPU, tag, full, strengths, θ, modes) + isdefined(FINUFFT, :cufinufft_makeplan) || throw(ArgumentError( + "FINUFFT's device transform is cuFINUFFT, loaded by `using CUDA`; the points live on " * + "$(nameof(typeof(backend))).", + )) + plan = FINUFFT.cufinufft_makeplan(1, collect(Int64, modes), -1, size(strengths, 2), tag.tolerance; + dtype = eltype(θ[1]), modeord = 1) + try + FINUFFT.cufinufft_setpts!(plan, θ...) + FINUFFT.cufinufft_exec!(plan, strengths, full) + finally + FINUFFT.cufinufft_destroy!(plan) + end + return full +end + +_type1!(::KA.CPU, tag, full, strengths, θ, modes) = throw(ArgumentError( + "FINUFFT's host transform takes `Array`s; got $(typeof(full)).", +)) + +end # module diff --git a/ext/StructureFunctionsFlowGeometriesExt.jl b/ext/StructureFunctionsFlowGeometriesExt.jl index 410fe7a..6123fd5 100644 --- a/ext/StructureFunctionsFlowGeometriesExt.jl +++ b/ext/StructureFunctionsFlowGeometriesExt.jl @@ -2,31 +2,24 @@ module StructureFunctionsFlowGeometriesExt using FlowGeometries: FlowGeometries as FG using Distances: Distances as DI +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, - HelperFunctions as SFH, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT - -""" - _grid_spacing(grid) -> NTuple{N, T} - -Constant spacing of each direction. Only called once every direction is known to be uniform. -""" -function _grid_spacing(grid::FG.Grids.AbstractGrid{G, T}) where {G, T} - return ntuple(Val(length(FG.Grids.coordinates(grid)))) do d - FG.Grids.spacing(grid, d) - end -end + HelperFunctions as SFH, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT, + MultiFields as MF """ _grid_metric(grid) -> Distances metric The metric a grid's geometry measures with. -A spherical grid's coordinates are `(λ, φ)` in **radians**, which is `Distances.SphericalAngle` — -never `Haversine`, which reads degrees and would scale every separation by 180/π. +A spherical grid's coordinates are `(λ, φ)` in **radians** on a sphere of the geometry's radius, +which is [`SphericalDistance`](@ref SFH.SphericalDistance) — never `Haversine`, which reads degrees +and would scale every separation by 180/π. """ _grid_metric(::FG.Grids.AbstractGrid{<:FG.Geometry.AbstractCartesianGeometry}) = DI.Euclidean() -_grid_metric(::FG.Grids.AbstractGrid{<:FG.Geometry.AbstractSphericalGeometry}) = DI.SphericalAngle() +_grid_metric(grid::FG.Grids.AbstractGrid{<:FG.Geometry.AbstractSphericalGeometry}) = + SFH.SphericalDistance(FG.Geometry.radius(FG.Grids.grid_geometry(grid))) _grid_metric(grid::FG.Grids.AbstractGrid) = throw(ArgumentError( "no distance metric is defined for $(nameof(typeof(FG.Grids.grid_geometry(grid)))); structure " * @@ -42,14 +35,16 @@ _grid_geometry(grid::FG.Grids.AbstractGrid, D::Int) = SFH.pair_geometry_for(_grid_metric(grid), Val(D)) """ - _lag_schedule(grid) -> UniformLagSchedule | ZonalLagSchedule | ScatteredPairs + _lag_schedule(grid) -> UniformLagSchedule | RectilinearLagSchedule | ZonalLagSchedule | ScatteredPairs -The enumeration a grid supports. +The enumeration a grid supports, read from the **types** of its axes: a range is uniform, a vector of +coordinates is not, and no coordinate value is inspected to decide. -A uniform rectilinear grid shares a separation along each lag; a lat-lon grid shares a geodesic frame -around each circle of longitude; anything else — a stretched axis, a curvilinear mesh, a pixelized -sphere, a node set — shares nothing between pairs, and its pairs are enumerated. All three are exact; -they differ only in what can be hoisted. +A Cartesian grid whose every axis is uniform shares a separation along each lag; one with some +uniform axes shares it along those, between every pair of positions on the rest; a lat-lon grid with +uniform longitude shares a geodesic frame around each circle of longitude; anything else — a +curvilinear mesh, a pixelized sphere, a node set, a grid with no uniform axis — shares nothing +between pairs, and its pairs are enumerated. All are exact; they differ only in what can be hoisted. """ function _lag_schedule(grid::FG.Grids.AbstractGrid) _grid_metric(grid) # refuses a geometry with no metric, before any work @@ -58,13 +53,33 @@ end function _lag_schedule(grid::FG.Grids.AbstractStructuredGrid{<:FG.Geometry.AbstractCartesianGeometry}) c = FG.Grids.coordinates(grid) - all(d -> FG.Grids.isuniform(grid, d), 1:length(c)) || return _scattered(grid) - dims = ntuple(d -> length(c[d]), Val(length(c))) - return SFC.UniformLagSchedule(dims, _grid_spacing(grid), FG.Grids.periodic_flags(grid)) + N = length(c) + uniform = ntuple(d -> FG.Grids.isuniform(grid, d), Val(N)) + periodic = FG.Grids.periodic_flags(grid) + for d in 1:N + (periodic[d] && !uniform[d]) && throw(ArgumentError( + "direction $d wraps but its axis is a coordinate list, and a straight-line separation " * + "cannot be wrapped without a constant spacing to wrap by. Give the direction a range " * + "axis, or build the grid without its periodic flag.", + )) + end + all(uniform) && return SFC.UniformLagSchedule( + ntuple(d -> length(c[d]), Val(N)), _grid_spacing(grid), periodic, + ) + any(uniform) || return _scattered(grid) + order = (findall(uniform)..., findall(!, uniform)...) + Du = count(uniform) + su = SFC.UniformLagSchedule( + Tuple(length(c[order[k]]) for k in 1:Du), + Tuple(FG.Grids.spacing(grid, order[k]) for k in 1:Du), + Tuple(periodic[order[k]] for k in 1:Du), + ) + return SFC.RectilinearLagSchedule(su, Tuple(c[order[k]] for k in (Du + 1):N), order) end # A lat-lon grid's lags are not constant separations, so it gets the zonal schedule instead: the -# geodesic frame is shared around a circle of longitude, not along a lag. +# geodesic frame is shared around a circle of longitude, not along a lag. A stretched longitude axis +# enumerates pairs; the great-circle metric wraps of itself, so a periodic flag on it is no obstacle. function _lag_schedule(grid::FG.Grids.AbstractStructuredGrid{<:FG.Geometry.AbstractSphericalGeometry}) c = FG.Grids.coordinates(grid) (length(c) == 2 && FG.Grids.isuniform(grid, 1)) || return _scattered(grid) @@ -73,6 +88,13 @@ function _lag_schedule(grid::FG.Grids.AbstractStructuredGrid{<:FG.Geometry.Abstr FG.Grids.isperiodic(grid, 1)) end +"""Constant spacing of each direction; only called once every direction is known to be uniform.""" +function _grid_spacing(grid::FG.Grids.AbstractGrid{G, T}) where {G, T} + return ntuple(Val(length(FG.Grids.coordinates(grid)))) do d + FG.Grids.spacing(grid, d) + end +end + """Every cell's coordinates, as the schedule that simply enumerates pairs.""" function _scattered(grid::FG.Grids.AbstractGrid) coords = FG.Grids.materialize(grid) @@ -85,93 +107,294 @@ function _scattered(grid::FG.Grids.AbstractGrid) return SFC.ScatteredPairs(pts, _grid_metric(grid)) end +const GriddedField = Union{AbstractArray, MF.Fields} + """ - _gridded_setup(grid, u, distance_bins, count_eltype, kwargs) -> (schedule, D, sums, counts, valid) + cell_measure(grid) -> Vector -Validate a gridded call, allocate its histogram, and settle which cells hold a datum: the grid must -be one the lag enumeration describes, and the field must match it. +The measure of every cell of a FlowGeometries grid, in the gridded entries' cell order. """ -function _gridded_setup(grid, u, distance_bins, ::Type{CT}, kwargs) where {CT} +SFC.cell_measure(grid::FG.Grids.AbstractGrid) = vec(FG.Grids.measure_array(grid)) + +""" + _gridded_setup(grid, u, distance_bins, count_eltype, kwargs, verbose; weights) + -> (schedule, data, vD, vV, vK, valid, weights) + +Validate a gridded call and settle which cells hold a datum: the grid must be one the lag +enumeration describes, the field must cover it, and the weights, if any, must be one finite value +per cell with a floating-point count type to hold their pair mass. +""" +function _gridded_setup(grid, u::GriddedField, distance_bins, ::Type{CT}, kwargs, verbose::Bool; + weights = nothing) where {CT} isempty(kwargs) || throw(ArgumentError( "unsupported keyword(s) $(join(keys(kwargs), ", ")) for a gridded calculation", )) sched = _lag_schedule(grid) - D = size(u, 1) - length(u) == D * _schedule_cells(sched) || throw(DimensionMismatch( - "u must be (component, cells...) covering the grid's $(_schedule_cells(sched)) cells; got " * - "$(size(u))", + data, vD, vV, vK = SFC._packed(u) + D = SFC.SFC_val_int(vD) + V = SFC.SFC_val_int(vV) + cells = SFC.n_cells(sched) + size(data, 2) == cells || throw(DimensionMismatch( + "u must be (component, cells...) covering the grid's $cells cells; got $(size(data, 2)) cells", )) - SFC._validate_spatial_dimension(D) - _grid_geometry(grid, D) # refuses a geometry the schedules do not describe - SFC._assert_counts_representable(CT, _schedule_cells(sched)) - nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + if V > 0 + SFC._validate_spatial_dimension(D) + _grid_geometry(grid, D) # refuses a geometry the schedules do not describe + end + SFC._assert_counts_representable(CT, cells) # The grid says which cells exist and the field says which hold a datum; a pair needs both ends. cm = FG.Grids.mask(grid) - valid = SFC.field_validity(u, Val(D), cm isa FG.Grids.AllActive ? nothing : vec(cm)) - return sched, D, zeros(float(eltype(u)), nb), zeros(CT, nb), valid + valid = SFC.field_validity(data, cm isa FG.Grids.AllActive ? nothing : vec(cm)) + w = SFC._pair_weights(weights, cells, float(eltype(data))) + SFC._check_weighted_counts(w, CT) + verbose && @info "gridded structure function: $(nameof(typeof(sched))) over $cells cells" + return sched, data, vD, vV, vK, valid, w end -@inline _schedule_cells(s::SFC.UniformLagSchedule) = prod(s.dims) -@inline _schedule_cells(s::SFC.ZonalLagSchedule) = SFC.n_zonal_cells(s) -@inline _schedule_cells(s::SFC.ScatteredPairs) = SFC.n_scattered_cells(s) - -@inline _gridded_result(sf_type, distance_bins, sums, counts, ::Type{OT}) where {OT} = +@inline _gridded_result(sf_type, distance_bins, sums::AbstractVector, counts::AbstractVector, + ::Type{OT}) where {OT} = SFC._finalize(SFO.StructureFunctionSumsAndCounts(sf_type, distance_bins, sums, counts), OT) +@inline _gridded_result(sf_type, distance_bins, axis_bins, sums::AbstractMatrix, counts::AbstractMatrix, + ::Type{OT}) where {OT} = + SFC._finalize(SFO.StructureFunction2DSumsAndCounts(sf_type, distance_bins, axis_bins, sums, counts), + OT) + """ - calculate_structure_function(sf_type, grid, u, distance_bins[, count_eltype]; kwargs...) + calculate_structure_function(sf_type, grid, u, distance_bins[, count_eltype]; backend, kwargs...) -Structure function of the field `u` sampled on `grid`, computed by sweeping lag vectors rather than -pairs: on a uniform grid every pair sharing a lag shares its separation, direction and distance bin. +Structure function of the field `u` sampled on `grid`, computed by sweeping lag vectors wherever the +grid has a uniform direction: every pair sharing a lag shares its separation, direction and distance +bin. Which enumeration the grid gets is decided by the types of its axes (see +[`_lag_schedule`](@ref)) and reported when `verbose = true`. `u` is `(component, cells...)` with its trailing axes matching the grid, and its component count may -exceed the grid's dimension — a lag then lies in the grid's directions and is zero along the rest. +exceed the grid's dimension — a lag then lies in the grid's directions and is zero along the rest. A +a multi-field built from grid-shaped fields is taken the same way. On a spherical grid the +components are `(east, north[, radial])` and separations are in the unit of the geometry's radius. -The result is the one the array entry returns; `output_type` selects its representation. +`weights`, one per cell, weights each pair by `w_k · w_kp` in sums and counts, so the bin average is +`Σ w w v / Σ w w`; `weights = cell_measure(grid)` makes it the area average, and the counts, then a +weighted pair mass, need a floating-point `count_eltype`. `backend` names the hardware, as on the +unstructured entry: `AutoBackend()` threads over the pairs of slabs — rows of a lat-lon grid, positions +along a stretched axis — when threads and the OhMyThreads extension are available. The result is the +one the array entry returns; `output_type` selects its representation. """ function SFC.calculate_structure_function( sf_type::SFT.AbstractPairwiseStructureFunctionType, grid::FG.Grids.AbstractGrid, - u::AbstractArray, + u::GriddedField, distance_bins::AbstractVector, count_eltype::Type{CT} = UInt32; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction, + weights = nothing, verbose::Bool = true, show_progress::Bool = true, kwargs..., ) where {OT, CT} - sched, D, sums, counts, valid = _gridded_setup(grid, u, distance_bins, CT, kwargs) - SFC.gridded_lag_sweep!(sums, counts, sf_type, u, sched, distance_bins, Val(D); valid) + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, CT, kwargs, verbose; weights) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + sums = zeros(float(eltype(data)), nb) + counts = zeros(CT, nb) + SFC.gridded_lag_sweep!(sums, counts, sf_type, data, sched, distance_bins, vD, vV, vK; + valid, weights = w, backend) return _gridded_result(sf_type, distance_bins, sums, counts, OT) end """ - calculate_structure_function(sf_type, grid, u, distance_bins, count_eltype, spectral_backend; kwargs...) + calculate_structure_function(sf_type, grid, u, distance_bins, count_eltype, spectral_backend; backend, kwargs...) As above, summing the pairs by the algorithm `spectral_backend` names — a `SpectralBackends` tag. Which algorithm sums the pairs is an axis of its own, orthogonal to which hardware runs it. Sweeping the lags is exact for every pairwise operator and is what the shorter form does; a transform produces -the second-order increment tensor for **every** lag at once, so its cost does not grow with the -number of lags, and it serves the operators that are quadratic forms in `δu`. Both are exact, and -`AutoSpectralBackend` weighs the two costs. +the increment moment tensor for **every** lag at once, so its cost does not grow with the number of +lags, and it serves the operators that are polynomials in `δu` on every grid with a uniform +direction. Both are exact, and `AutoSpectralBackend` weighs the two costs. """ function SFC.calculate_structure_function( sf_type::SFT.AbstractPairwiseStructureFunctionType, grid::FG.Grids.AbstractGrid, - u::AbstractArray, + u::GriddedField, distance_bins::AbstractVector, count_eltype::Type{CT}, spectral_backend; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction, + weights = nothing, verbose::Bool = true, show_progress::Bool = true, kwargs..., ) where {OT, CT} - sched, D, sums, counts, valid = _gridded_setup(grid, u, distance_bins, CT, kwargs) - SFC.gridded_sweep!(sums, counts, sf_type, u, sched, distance_bins, Val(D), spectral_backend; - valid) + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, CT, kwargs, verbose; weights) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + sums = zeros(float(eltype(data)), nb) + counts = zeros(CT, nb) + SFC.gridded_sweep!(sums, counts, sf_type, data, sched, distance_bins, vD, vV, vK, spectral_backend; + valid, weights = w, backend) return _gridded_result(sf_type, distance_bins, sums, counts, OT) end +""" + calculate_structure_function(sf_type, grid, u, distance_bins, axis_bins[, spectral_backend]; second_axis, backend, kwargs...) + +The joint histogram in separation and the angle `second_axis` reads from each lag's direction, on a +Cartesian grid: `S(r, θ)` from the same lags as the 1-D result, with `sums` and `counts` of shape +`(n_distance, n_angle)`. + +Counts are floating point: a lag that half-turns a periodic direction has two directions of equal +length, and its pairs are split between the two angle bins in equal halves. +""" +function SFC.calculate_structure_function( + sf_type::SFT.AbstractPairwiseStructureFunctionType, + grid::FG.Grids.AbstractGrid, + u::GriddedField, + distance_bins::AbstractVector, + axis_bins::AbstractVector; + second_axis::SFC.SeparationAngleAxis, + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunction2DSumsAndCounts, + weights = nothing, + verbose::Bool = true, + show_progress::Bool = true, + kwargs..., +) where {OT} + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, Float64, kwargs, verbose; weights) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + na = SFC.n_histogram_bins(SF.BinEdges(axis_bins)) + sums = zeros(float(eltype(data)), nb, na) + counts = zeros(Float64, nb, na) + SFC.gridded_lag_sweep!(sums, counts, sf_type, data, sched, distance_bins, axis_bins, vD, vV, vK; + valid, weights = w, backend, second_axis) + return _gridded_result(sf_type, distance_bins, axis_bins, sums, counts, OT) +end + +function SFC.calculate_structure_function( + sf_type::SFT.AbstractPairwiseStructureFunctionType, + grid::FG.Grids.AbstractGrid, + u::GriddedField, + distance_bins::AbstractVector, + axis_bins::AbstractVector, + spectral_backend; + second_axis::SFC.SeparationAngleAxis, + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunction2DSumsAndCounts, + weights = nothing, + verbose::Bool = true, + show_progress::Bool = true, + kwargs..., +) where {OT} + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, Float64, kwargs, verbose; weights) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + na = SFC.n_histogram_bins(SF.BinEdges(axis_bins)) + sums = zeros(float(eltype(data)), nb, na) + counts = zeros(Float64, nb, na) + SFC.gridded_sweep!(sums, counts, sf_type, data, sched, distance_bins, axis_bins, vD, vV, vK, + spectral_backend; valid, weights = w, backend, second_axis) + return _gridded_result(sf_type, distance_bins, axis_bins, sums, counts, OT) +end + +""" + calculate_structure_function_tensor(order, grid, u, distance_bins[, axis_bins], spectral_backend; second_axis, weights, backend, output_type, count_eltype, verbose, kwargs...) + +The rank-`P` increment moment tensor of the vector field `u` on `grid`, by the transform +`spectral_backend` names — `AutoSpectralBackend()` or `FastFourierTransformSpectralBackend()` on a +grid with a uniform direction — with `sums` of shape `(D, …, D, n_bins)`; with `axis_bins` the joint +tensor over separation and the angle `second_axis` reads, `(D, …, D, n_bins, n_axis)`. The grid +rules, `weights` and `backend` are those of [`calculate_structure_function`](@ref) on a grid. +""" +function SFC.calculate_structure_function_tensor( + order::Val{P}, + grid::FG.Grids.AbstractGrid, + u::GriddedField, + distance_bins::AbstractVector, + spectral_backend; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunctionTensor, + count_eltype::Type{CT} = UInt32, + weights = nothing, + verbose::Bool = true, + kwargs..., +) where {P, OT, CT} + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, CT, kwargs, verbose; weights) + _one_vector_field(vV, vK) + D = SFC.SFC_val_int(vD) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + sums = zeros(float(eltype(data)), ntuple(_ -> D, P)..., nb) + counts = zeros(CT, nb) + SFC.gridded_tensor_sweep!(sums, counts, order, data, sched, distance_bins, vD, spectral_backend; + valid, weights = w, backend) + return SFC._finalize(SFO.StructureFunctionTensorSumsAndCounts(order, distance_bins, sums, counts), OT) +end + +function SFC.calculate_structure_function_tensor( + order::Val{P}, + grid::FG.Grids.AbstractGrid, + u::GriddedField, + distance_bins::AbstractVector, + axis_bins::AbstractVector, + spectral_backend; + second_axis::SFC.SeparationAngleAxis, + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunctionTensor2DSumsAndCounts, + weights = nothing, + verbose::Bool = true, + kwargs..., +) where {P, OT} + sched, data, vD, vV, vK, valid, w = _gridded_setup(grid, u, distance_bins, Float64, kwargs, verbose; weights) + _one_vector_field(vV, vK) + D = SFC.SFC_val_int(vD) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(distance_bins)) + na = SFC.n_histogram_bins(SF.BinEdges(axis_bins)) + sums = zeros(float(eltype(data)), ntuple(_ -> D, P)..., nb, na) + counts = zeros(Float64, nb, na) + SFC.gridded_tensor_sweep!(sums, counts, order, data, sched, distance_bins, axis_bins, vD, spectral_backend; + valid, weights = w, backend, second_axis) + return SFC._finalize(SFO.StructureFunctionTensor2DSumsAndCounts(order, distance_bins, axis_bins, sums, counts), OT) +end + +_one_vector_field(::Val{1}, ::Val{0}) = nothing +_one_vector_field(::Val{V}, ::Val{K}) where {V, K} = throw(ArgumentError( + "a tensor structure function is of one vector field; got a multi-field of $V vector and $K scalar fields", +)) + +""" + calculate_structure_function(sf_type, grid, u, nodes::HarmonicNodes, spectral_backend; kwargs...) + +The kernel-binned structure function of a field on a spherical grid by spherical harmonic +pseudo-coefficients (see [`harmonic_sweep!`](@ref SFC.harmonic_sweep!)), the cells' measure serving as +the quadrature weights so that the statistic is an area average. The grid's own mask and the field's +finiteness decide which cells are held. +""" +function SFC.calculate_structure_function( + sf_type::SFT.AbstractPairwiseStructureFunctionType, + grid::FG.Grids.AbstractGrid{<:FG.Geometry.AbstractSphericalGeometry}, + u::GriddedField, + nodes::SF.HarmonicNodes, + spectral_backend; + output_type::Type{OT} = SFO.StructureFunction, + verbose::Bool = true, + show_progress::Bool = true, +) where {OT} + coords = FG.Grids.materialize(grid) + length(coords) == 2 || throw(ArgumentError( + "the harmonic route takes a sphere's surface, (λ, φ); this grid has $(length(coords)) coordinates", + )) + N = length(coords[1]) + x = Matrix{eltype(coords[1])}(undef, 2, N) + x[1, :] .= coords[1] + x[2, :] .= coords[2] + data, vD, vV, vK = SFC._packed(u) + size(data, 2) == N || throw(DimensionMismatch( + "u must cover the grid's $N cells; got $(size(data, 2))", + )) + cm = FG.Grids.mask(grid) + valid = SFC.field_validity(data, cm isa FG.Grids.AllActive ? nothing : vec(cm)) + weights = SFC.cell_measure(grid) + verbose && @info "harmonic structure function on the grid: $(length(nodes)) nodes, lmax = $(nodes.lmax)" + return SFC.calculate_structure_function(sf_type, x, u, nodes, spectral_backend; + distance_metric = _grid_metric(grid), weights, valid, output_type = OT, verbose = false, show_progress) +end + end # module diff --git a/ext/StructureFunctionsKernelAbstractionsExt.jl b/ext/StructureFunctionsKernelAbstractionsExt.jl index 40c4f6e..f0bbb6b 100644 --- a/ext/StructureFunctionsKernelAbstractionsExt.jl +++ b/ext/StructureFunctionsKernelAbstractionsExt.jl @@ -16,10 +16,9 @@ single-pass 2D uses tiled128 pair traversal with **HTP-EJ** when `n_dist ≤ SF_ and distance bins are typed (`LinearBinEdges` / `LogBinEdges`): - **On-chip** (`:shared`, `:typeplane`): shared histogram during the pair loop, - block-end `@atomic` flush into final output (same pattern as joint 2D) — no private partition, no merge. -- **Direct** (`:direct`): block-private global atomics during one pair pass, then merge kernel. - -See [`gpu/SP2D_HTP_EJ.md`](../gpu/SP2D_HTP_EJ.md) for strategy, routing, benchmarks, and known perf gaps. + block-end `@atomic` flush into final output (the joint 2D pattern), with no private partition and + no merge. +- **Direct** (`:direct`): block-private global atomics during one pair pass, then a merge kernel. Pass `force_global_atomic=true` to bypass HTP-EJ and use the global-atomic path. @@ -262,22 +261,21 @@ include(joinpath(@__DIR__, "gpu", "kernels_2d_single_pass.jl")) include(joinpath(@__DIR__, "gpu", "kernels_2d_value_axis.jl")) include(joinpath(@__DIR__, "gpu", "kernels_2d_direct.jl")) include(joinpath(@__DIR__, "gpu", "kernels_batch.jl")) -# Unified parametric kernel core (building blocks) + the two tiled kernels that -# replace the per-variant kernels above. See gpu/OPTIMAL_KERNEL_DESIGN.md. +# Unified parametric kernel core (building blocks) and the two tiled kernels built on it. include(joinpath(@__DIR__, "gpu", "sf_core.jl")) include(joinpath(@__DIR__, "gpu", "sf_tiled.jl")) include(joinpath(@__DIR__, "gpu", "workspace.jl")) include(joinpath(@__DIR__, "gpu", "launch.jl")) include(joinpath(@__DIR__, "gpu", "tensor.jl")) -include(joinpath(@__DIR__, "gpu", "channels.jl")) +include(joinpath(@__DIR__, "gpu", "multifields.jl")) # The kernels compute Euclidean geometry inline, so every GPU entry types its `distance_metric` # keyword as `DI.Euclidean`: asking for another metric is a TypeError naming the keyword, and the -# constraint lives in the signature rather than in a trait table and a runtime branch. +# constraint lives in the signature. """`true` when `a` is an array living on `backend`. Only a missing `KA.get_backend` method (i.e. `a` -is not a recognized device array) counts as "not on this backend" — every other failure is a real -fault and propagates rather than silently degrading to a host round-trip.""" +is not a recognized device array) counts as "not on this backend"; every other failure is a real +fault and propagates.""" function _array_on_backend(a, backend::KA.Backend) a_backend = try KA.get_backend(a) @@ -933,9 +931,9 @@ function _gpu_calculate_structure_function_core( nb = SFC.n_histogram_bins(distance_bins) sums = zeros(promote_type(float(FT), Float64), nb) counts = zeros(CT, nb) - SFC.gpu_calculate_structure_function_channels!( + SFC.gpu_calculate_structure_function_fields!( CB.GPUBackend(backend), sums, counts, sf_type, x_mat, - SFC.CH.Fields(vectors = (u_mat,)), distance_bins; + SFC.MF.Fields(vectors = (u_mat,)), distance_bins; distance_metric, culling, verbose, show_progress, ) return SF.StructureFunctionSumsAndCounts(sf_type, distance_bins, sums, counts) @@ -1073,8 +1071,7 @@ end U2 = _gpu_ld_col(u_mat, j, Val(2), FT) ok, dist, frame = SFH.pair_frame(geom, X1, X2) du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - return ok, dist, du_L, du_L2, du_n2 - du_L2 + return ok, dist, du_L, du_n2 end @inline function _gpu_single_pass_pair_invariants( @@ -1092,8 +1089,7 @@ end U2 = _gpu_ld_col(u_mat, j, Val(3), FT) ok, dist, frame = SFH.pair_frame(geom, X1, X2) du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - return ok, dist, du_L, du_L2, du_n2 - du_L2 + return ok, dist, du_L, du_n2 end @inline function _gpu_accumulate_single_pass_global!( @@ -1101,17 +1097,11 @@ end output_counts, bin::Int, du_L, - du_L2, - du_T2, + du_n2, ) - @atomic output_sums[1, bin] += du_L2 + du_T2 - @atomic output_sums[2, bin] += du_L2 - @atomic output_sums[3, bin] += du_T2 - @atomic output_sums[4, bin] += du_L * (du_L2 + du_T2) - @atomic output_sums[5, bin] += du_L * du_L2 - @atomic output_sums[6, bin] += du_L * du_T2 - + vals = SFC.single_pass_invariants(du_L, du_n2) for t in 1:SF_GPU_SINGLE_PASS_N + @atomic output_sums[t, bin] += vals[t] @atomic output_counts[t, bin] += one(eltype(output_counts)) end return nothing @@ -1136,7 +1126,7 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel_linear!( j = I[2] if i < j - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_linear( @@ -1144,7 +1134,7 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel_linear!( ) if ok && 1 <= bin < N_bins - _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) + _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_n2) end end end @@ -1168,13 +1158,13 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel_log!( j = I[2] if i < j - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) if ok && 1 <= bin < N_bins - _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) + _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_n2) end end end @@ -1196,13 +1186,13 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel!( if i < j FT = eltype(x_mat) - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_general(dist, distance_bins, N_bins) if ok && 1 <= bin < N_bins - _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) + _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_n2) end end end @@ -1211,10 +1201,8 @@ end Offer a non-batch single-pass 1D launch to the batch dispatcher as `B=1`, which reaches the CUDA N-body kernel; `false` means the hook declined and the caller stays on the tiled128 path. -Measured on A100 (N=20000): 1.90× Float32, 1.32× Float64. The batch machinery is not a win at -`B=1` in general — 1D-individual measures 0.64× because its fixed-x path pays strip staging and two -merge kernels for a strip of one — so this is applied per regime, not globally. See -`gpu/SPEED_OF_LIGHT.md`. +The offer is made per regime, not globally: a fixed-x 1D-individual launch at `B=1` pays strip +staging and two merge kernels for a strip of one, so it stays on its own path. """ @inline function _sp1d_try_fast_batch!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_bins, @@ -1454,8 +1442,7 @@ end Offer a non-batch joint 2D launch to the batch dispatcher as `B=1` (`NMOM=1`, so `sf_type` is carried through and does the per-pair math); `false` means the hook declined and the caller continues unchanged. `(n_dist, n_val)` reshapes to `(1, n_dist, n_val, 1)` at no cost — column-major -layout is identical. Measured on A100 (N=20000): 1.48× Float32, 1.18× Float64. -See `gpu/SPEED_OF_LIGHT.md`. +layout is identical. """ @inline function _joint2d_try_fast_batch!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, dist_bins, vp, @@ -1807,20 +1794,10 @@ end value_edges, bin::Int, du_L, - du_T, - du_L2, - du_T2, + du_n2, N_val_edges::Int, ) - FT = eltype(output_sums) - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_general_col(vals[t], value_edges, t, N_val_edges) if 1 <= vbin < N_val_edges @@ -1850,7 +1827,7 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel_linear!( I = @index(Global, NTuple) i, j = I[1], I[2] if i < j - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_linear( @@ -1859,7 +1836,7 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel_linear!( if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, - du_L, zero(du_L), du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end end @@ -1884,14 +1861,14 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel_log!( I = @index(Global, NTuple) i, j = I[1], I[2] if i < j - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, - du_L, zero(du_L), du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end end @@ -1914,14 +1891,14 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel!( i, j = I[1], I[2] if i < j FT = eltype(x_mat) - ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + ok, dist, du_L, du_n2 = _gpu_single_pass_pair_invariants( x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_general(dist, distance_bins, N_bins) if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, - du_L, zero(du_L), du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end end @@ -2246,10 +2223,9 @@ function SFC.gpu_calculate_structure_function_batch!( throw(DimensionMismatch("sums must have shape ($NB, $T); got $(size(sums))")) size(counts) == (NB, T) || throw(DimensionMismatch("counts must have shape ($NB, $T); got $(size(counts))")) - N_dims == 2 || - error("GPUExt: slice batch requires N_dims=2 (got N_dims=$N_dims)") - # Fused varying-x batch (B = T) through the unified N-body path (measured - # ~1.9× the old per-slice varying kernel; single launch, no per-slice loop). + N_dims == 2 || N_dims == 3 || + error("GPUExt: slice batch requires N_dims ∈ {2,3} (got N_dims=$N_dims)") + # Fused varying-x batch (B = T) through the unified N-body path: one launch for every slice. # `size(u, 1)` is the velocity dimension only before the conversion. geom = SFH.pair_geometry_for(distance_metric, Val(size(u, 1))) x, u = SFH.prepare_pair_inputs(geom, x, u) @@ -2323,8 +2299,8 @@ function SFC.gpu_calculate_structure_functions_single_pass_batch!( throw(DimensionMismatch("sums must have shape ($(SFC.SINGLE_PASS_N), $n_bins, $T); got $(size(sums))")) size(counts) == size(sums) || throw(DimensionMismatch("counts must match sums shape $(size(sums))")) - N_dims == 2 || - error("GPUExt: single-pass slice batch requires N_dims=2 (got N_dims=$N_dims)") + N_dims == 2 || N_dims == 3 || + error("GPUExt: single-pass slice batch requires N_dims ∈ {2,3} (got N_dims=$N_dims)") # Fused varying-x batch (B = T) through the unified N-body single-pass path. # `size(u, 1)` is the velocity dimension only before the conversion. geom = SFH.pair_geometry_for(distance_metric, Val(size(u, 1))) @@ -2364,11 +2340,10 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d_batch!( throw(DimensionMismatch("sums must have shape ($(SFC.SINGLE_PASS_N), $n_bins, $n_val, $T); got $(size(sums))")) size(counts) == size(sums) || throw(DimensionMismatch("counts must match sums shape $(size(sums))")) - N_dims == 2 || - error("GPUExt: SP2D slice batch requires N_dims=2 (got N_dims=$N_dims)") - # Fused varying-x batch (B = T) through the unified single-pass-2D path - # (N-body + dynamic-shared privatized histogram; ~17× the old per-slice path - # at 50×50, one launch instead of T). + N_dims == 2 || N_dims == 3 || + error("GPUExt: SP2D slice batch requires N_dims ∈ {2,3} (got N_dims=$N_dims)") + # Fused varying-x batch (B = T) through the unified single-pass-2D path: N-body with a + # dynamic-shared privatized histogram, one launch for every slice. # `size(u, 1)` is the velocity dimension only before the conversion. geom = SFH.pair_geometry_for(distance_metric, Val(size(u, 1))) x, u = SFH.prepare_pair_inputs(geom, x, u) diff --git a/ext/StructureFunctionsLsqFitExt.jl b/ext/StructureFunctionsLsqFitExt.jl new file mode 100644 index 0000000..e8131c9 --- /dev/null +++ b/ext/StructureFunctionsLsqFitExt.jl @@ -0,0 +1,34 @@ +module StructureFunctionsLsqFitExt + +using LsqFit: LsqFit +using LinearAlgebra: LinearAlgebra as LA +using StructureFunctions: Calculations as SFC + +# The bounded Levenberg–Marquardt fit of a segmented power law: the kernel matrix over the quadrature +# nodes is fixed, so the model is that matrix times the spectrum at the nodes and the Jacobian comes +# from forward-mode differentiation of the spectrum alone. +function SFC._segmented_fit( + m::SFC.SegmentedPowerLaw, ::Val{D}, r::AbstractVector, y::AbstractVector, W, k_lo, k_hi, +) where {D} + S = m.segments + edges = SFC._segment_edges(k_lo, k_hi, S) + k, _, K = SFC._segmented_design(Val(D), r, edges) + model(_, p) = K * SFC.segmented_spectrum(p, k, edges) + lo, hi = m.slope_bounds + lower = vcat(0.0, fill(lo, S)) + upper = vcat(Inf, fill(hi, S)) + α0 = clamp(-5 / 3, lo, hi) + unit = model(r, vcat(1.0, fill(α0, S))) + b0 = max(sum(abs, y) / max(sum(abs, unit), eps()), eps()) + p0 = vcat(b0, fill(α0, S)) + fit = LsqFit.curve_fit(model, r, Vector{Float64}(y), _weights(W, y), p0; lower, upper) + return fit.param, Matrix(LsqFit.vcov(fit)), edges, fit.converged +end + +# No data covariance fits the relative residual (S₂ᶠⁱᵗ − S₂)/S₂; variances weigh each value by its +# own; a full covariance whitens by its inverse. +_weights(::Nothing, y) = LsqFit.PrecisionWeights(1 ./ abs2.(Vector{Float64}(y))) +_weights(W::AbstractVector, y) = LsqFit.PrecisionWeights(1 ./ Vector{Float64}(W)) +_weights(W::AbstractMatrix, y) = LsqFit.PrecisionMatrix(inv(LA.Symmetric(Matrix{Float64}(W)))) + +end # module diff --git a/ext/StructureFunctionsNUFSHTExt.jl b/ext/StructureFunctionsNUFSHTExt.jl new file mode 100644 index 0000000..4734f87 --- /dev/null +++ b/ext/StructureFunctionsNUFSHTExt.jl @@ -0,0 +1,46 @@ +module StructureFunctionsNUFSHTExt + +using NUFSHT: NUFSHT +using SpectralBackends: SpectralBackends as SB +using StructureFunctions: Calculations as SFC + +# NUFSHT's spin-weighted analysis is the exact adjoint of its synthesis in the same convention the +# core's direct sum uses: `ₛY_lm = √((2l+1)/4π) d^l_{m,−s}(θ) e^{imφ}`, coefficients dense as +# `sf[l+1, m+lmax+1]`. So a provider is one spin plan per spin the operator's monomials need, built on +# the points once and reused for every monomial of that spin. +struct NUFSHTProvider{T, AV <: AbstractVector{T}, P} + θ::AV + φ::AV + lmax::Int + plans::Dict{Int, P} +end + +function (p::NUFSHTProvider{T, AV, P})(f::AbstractVector, s::Integer) where {T, AV, P} + plan = get!(p.plans, Int(s)) do + NUFSHT.make_spin_plan(ComplexF64, p.θ, p.φ, p.lmax, Int(s))::P + end + out = zeros(ComplexF64, p.lmax + 1, 2p.lmax + 1) + NUFSHT.nusht_type1_spin!(out, ComplexF64.(f), plan) + return out +end + +# The plan's type does not depend on the spin, and spin 0 is needed by every call (the mask), so it +# is built first and fixes the type of the rest. +function _nufsht_provider(θ, φ, lmax) + θf, φf = convert(AbstractVector{Float64}, θ), convert(AbstractVector{Float64}, φ) + p0 = NUFSHT.make_spin_plan(ComplexF64, θf, φf, Int(lmax), 0) + return NUFSHTProvider(θf, φf, Int(lmax), Dict{Int, typeof(p0)}(0 => p0)) +end + +SFC.harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes::SFC.HarmonicNodes, ::Val{D}, ::Val{V}, + ::Val{K}, ::SB.AbstractNonUniformFastSphericalHarmonicsTransformSpectralBackend; + valid = SFC.AllValid()) where {D, V, K} = + SFC._harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes, Val(D), Val(V), Val(K), valid, + _nufsht_provider) + +SFC.harmonic_spectra(x::AbstractMatrix, u::AbstractMatrix, lmax::Integer, + ::SB.AbstractNonUniformFastSphericalHarmonicsTransformSpectralBackend; + distance_metric = SFC.DI.SphericalAngle(), weights = nothing, valid = nothing) = + SFC._harmonic_spectra(x, u, lmax, distance_metric, weights, valid, _nufsht_provider) + +end # module diff --git a/ext/StructureFunctionsNonuniformFFTsExt.jl b/ext/StructureFunctionsNonuniformFFTsExt.jl new file mode 100644 index 0000000..2da36f9 --- /dev/null +++ b/ext/StructureFunctionsNonuniformFFTsExt.jl @@ -0,0 +1,36 @@ +module StructureFunctionsNonuniformFFTsExt + +using NonuniformFFTs: NonuniformFFTs as NU +using StructureFunctions: StructureFunctions as SF, Calculations as SFC + +# NonuniformFFTs' type-1 transform carries the minus sign and, for real data, the real-to-complex half +# spectrum `(M₁ ÷ 2 + 1, M₂, …)`; on uniform points it equals FFTW's `rfft`, so the engine reads these +# arrays exactly as it reads a slab's transforms. One plan serves every monomial of the point set, on +# the host or on the device the points live on. +function SFC.nufft_monomial_transforms( + tag::SFC.NonuniformFFTsSpectralBackend, s::SFC.ScatteredModesSchedule{Dg, T}, + data::AbstractMatrix, valid, weights, keys, ::Val{Pm}; to = identity, +) where {Dg, T, Pm} + m = SFC.nufft_half_support(tag) + all(M -> M >= m, s.modes) || throw(ArgumentError( + "every direction needs at least $m modes, the kernel half-support at tolerance $(tag.tolerance), for " * + "NonuniformFFTs' spreading kernel to fit its oversampled grid; got $(s.modes). Raise the modes or the tolerance.", + )) + FT = float(eltype(data)) + θ = ntuple(d -> to(FT.(SFC.mode_coordinates(s, d))), Val(Dg)) + plan = SFC.nufft_plan(tag, FT, s.modes, θ[1]) + NU.set_points!(plan, θ) + taper = SFC.mode_taper_weights(s, FT, size(plan), to) + return map(keys) do key + v = SFC._held_monomial_vector(data, valid, weights, key, FT) + û = similar(θ[1], Complex{FT}, size(plan)) + NU.exec_type1!(û, plan, v) + taper === nothing || (û .*= taper) + û + end +end + +SFC.nufft_plan(tag::SFC.NonuniformFFTsSpectralBackend, ::Type{FT}, modes, ::Array) where {FT} = + NU.PlanNUFFT(FT, modes; m = NU.HalfSupport(SFC.nufft_half_support(tag))) + +end # module diff --git a/ext/StructureFunctionsNonuniformFFTsKernelAbstractionsExt.jl b/ext/StructureFunctionsNonuniformFFTsKernelAbstractionsExt.jl new file mode 100644 index 0000000..50d0d40 --- /dev/null +++ b/ext/StructureFunctionsNonuniformFFTsKernelAbstractionsExt.jl @@ -0,0 +1,14 @@ +module StructureFunctionsNonuniformFFTsKernelAbstractionsExt + +using NonuniformFFTs: NonuniformFFTs as NU +using KernelAbstractions: KernelAbstractions as KA +using StructureFunctions: Calculations as SFC + +# The device plan pins the kernel and its evaluation: on CUDA the backend's default direct Kaiser–Bessel +# evaluation reaches only ~3e-6 in Float64 (its device Bessel I₀), while the piecewise-polynomial +# evaluation of the backwards kernel reaches ~1e-15. +SFC.nufft_plan(tag::SFC.NonuniformFFTsSpectralBackend, ::Type{FT}, modes, x::AbstractArray) where {FT} = + NU.PlanNUFFT(FT, modes; backend = KA.get_backend(x), m = NU.HalfSupport(SFC.nufft_half_support(tag)), + kernel = NU.BackwardsKaiserBesselKernel(), kernel_evalmode = NU.FastApproximation()) + +end # module diff --git a/ext/StructureFunctionsOhMyThreadsExt.jl b/ext/StructureFunctionsOhMyThreadsExt.jl index 3dd7b58..c7a4658 100644 --- a/ext/StructureFunctionsOhMyThreadsExt.jl +++ b/ext/StructureFunctionsOhMyThreadsExt.jl @@ -14,9 +14,8 @@ using StructureFunctions: BinEdges, n_histogram_bins -# Signal to AutoBackend that threading is genuinely available (see backends.jl). Set in -# __init__ (load time) via a Ref — overriding the method here would be an illegal -# method-overwrite during this extension's precompilation. +# Signal to AutoBackend that threading is available (see backends.jl). A Ref set in `__init__` at +# load time, because overwriting a method during this extension's precompilation is illegal. function __init__() SFC._OHMYTHREADS_LOADED[] = true return nothing @@ -53,46 +52,54 @@ already lie. """ threaded_calculate_structure_function!(sums, counts, sf, x, fields, distance_bins; kwargs...) -Multi-channel pair sweep across threads. +Multi-field pair sweep across threads. -The setup — widening the channels, sorting into the cull grid — happens **once**, above the task +The setup — widening the fields, sorting into the cull grid — happens **once**, above the task loop; each task then sweeps its own share of outer indices into private histograms, which are -reduced. A field of one vector channel forwards to the array path, so a bare `u` and a one-channel -bundle stay the same calculation on this backend too. +reduced. A field of one vector field forwards to the array path, so a bare `u` and a one-field +multi-field stay the same calculation on this backend too. """ function SFC.threaded_calculate_structure_function!( sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::SFC.CH.Fields{D, 1, 0}, distance_bins; kwargs..., + x::AbstractMatrix, f::SFC.MF.Fields{D, 1, 0}, distance_bins; kwargs..., ) where {D} - return SFC.threaded_calculate_structure_function!(sums, counts, sf, x, SFC.CH.packed(f), + return SFC.threaded_calculate_structure_function!(sums, counts, sf, x, SFC.MF.packed(f), distance_bins; kwargs...) end function SFC.threaded_calculate_structure_function!( sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::SFC.CH.Fields{D, V, K}, distance_bins; + x::AbstractMatrix, f::SFC.MF.Fields{D, V, K}, distance_bins; distance_metric::DI.PreMetric = DI.Euclidean(), culling::SFC.CullingPolicy = SFC.AutoCulling(), + weights = nothing, verbose::Bool = true, show_progress::Bool = true, ) where {OT, CT, D, V, K} - Np = size(SFC.CH.packed(f), 2) + Np = size(SFC.MF.packed(f), 2) size(x, 2) == Np || throw(DimensionMismatch( "x covers $(size(x, 2)) points and the field $Np", )) dist_be = BinEdges(distance_bins) + w = SFC._pair_weights(weights, Np, float(eltype(SFC.MF.packed(f)))) + SFC._check_weighted_counts(w, CT) + if SFC._on_a_line(SFC._field_geometry(distance_metric, Val(D), Val(V), x), sf) + SFC._cull_reject_unsupported(culling, "the sorted line route") + return SFC.sorted_line_sweep!(sums, counts, sf, SFC._line_coordinates(x), SFC.MF.packed(f), dist_be, + Val(D), Val(V), Val(K); weights = w, backend = CB.ThreadedBackend()) + end # Bound once and never reassigned: the tasks close over these, and reassigning a captured # variable boxes it, which OhMyThreads rejects outright. - geom, xk, data, vF, plan, grid = SFC.channel_setup(f, x, dist_be, distance_metric, culling) + geom, xk, data, vF, plan, grid, wk = SFC.field_setup(f, x, dist_be, distance_metric, culling, w) nb = n_histogram_bins(dist_be) vW = Val(SFC.SFC_val_int(SFH.coordinate_width(geom))) result = OMT.tmapreduce(+, _outer_chunks(grid, 1:(Np - 1), Threads.nthreads())) do chunk local_sums = zeros(OT, nb) local_counts = zeros(CT, nb) - SFC._channel_run_blocks!(local_sums, local_counts, sf, xk, data, geom, vF, Val(V), Val(K), - plan, nb, vW, chunk, Np, grid) + SFC._field_run_blocks!(local_sums, local_counts, sf, xk, data, geom, vF, Val(V), Val(K), + plan, nb, vW, chunk, Np, grid, wk) SFO.StructureFunctionSumsAndCounts(sf, dist_be, local_sums, local_counts) end sums .+= result.sums @@ -109,6 +116,7 @@ function SFC.threaded_calculate_structure_function!( u_vecs::Tuple, distance_bins::AbstractVector; geometry = SFH.FlatGeometry{length(u_vecs)}(), + weights = nothing, verbose = true, show_progress = true, ) where {OT, CT} @@ -116,8 +124,15 @@ function SFC.threaded_calculate_structure_function!( @info("calculating structure function (threaded reduction via OhMyThreads)") end _ = show_progress + w = SFC._pair_weights(weights, length(x_vecs[1]), OT) + SFC._check_weighted_counts(w, CT) + if SFC._on_a_line(geometry, structure_function_type) + return SFC.sorted_line_sweep!(output_sums, output_counts, structure_function_type, x_vecs[1], + reshape(collect(u_vecs[1]), 1, :), distance_bins, Val(1), Val(1), Val(0); + weights = w, backend = CB.ThreadedBackend()) + end - # Chunked tmapreduce: O(n_tasks) allocations instead of O(N_points) + # Chunked tmapreduce: O(n_tasks) allocations, not O(N_points) n_bins = n_histogram_bins(distance_bins) distance_bins = BinEdges(distance_bins) result = OMT.tmapreduce(+, _triangle_outer_chunks(eachindex(x_vecs[1]), Threads.nthreads())) do chunk @@ -133,6 +148,7 @@ function SFC.threaded_calculate_structure_function!( x_vecs, u_vecs, distance_bins, + w, ) end SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, local_output, local_counts) @@ -186,6 +202,7 @@ function SFC.threaded_calculate_structure_function!( distance_bins::AbstractVector; distance_metric::DI.PreMetric = DI.Euclidean(), culling::SFC.CullingPolicy = SFC.AutoCulling(), + weights = nothing, verbose = true, show_progress = true, ) where {OT, CT, FT1 <: Number, FT2 <: Number} @@ -193,6 +210,8 @@ function SFC.threaded_calculate_structure_function!( @info("calculating structure function (threaded reduction via OhMyThreads)") end _ = show_progress + w = SFC._pair_weights(weights, size(x_arr, 2), OT) + SFC._check_weighted_counts(w, CT) N3 = n_histogram_bins(distance_bins) distance_bins = BinEdges(distance_bins) @@ -204,14 +223,20 @@ function SFC.threaded_calculate_structure_function!( geom = SFH.pair_geometry_for(distance_metric, Val(size(u_arr, 1))) + if SFC._on_a_line(geom, structure_function_type) + SFC._cull_reject_unsupported(culling, "the sorted line route") + return SFC.sorted_line_sweep!(output_sums, output_counts, structure_function_type, + SFC._line_coordinates(x_arr), u_arr, distance_bins, Val(1), Val(1), Val(0); + weights = w, backend = CB.ThreadedBackend()) + end # Fast path: flat D ∈ (2,3) threads the SIMD compute/scatter-split kernel over round-robin # i-chunks (per-task buffers + local accumulators; contiguous components shared). if geom isa SFH.FlatGeometry && N == 2 return _threaded_pf_simd!(output_sums, output_counts, structure_function_type, x_arr, - u_arr, distance_bins, Val(2); geometry = geom, culling = culling) + u_arr, distance_bins, Val(2); geometry = geom, culling = culling, weights = w) elseif geom isa SFH.FlatGeometry && N == 3 return _threaded_pf_simd!(output_sums, output_counts, structure_function_type, x_arr, - u_arr, distance_bins, Val(3); geometry = geom, culling = culling) + u_arr, distance_bins, Val(3); geometry = geom, culling = culling, weights = w) end SFC._cull_reject_unsupported(culling, "the scalar per-point threaded kernel this geometry uses") @@ -225,7 +250,7 @@ function SFC.threaded_calculate_structure_function!( for i in chunk SFC.calculate_structure_function_i!( local_output, local_counts, geom, structure_function_type, i, - x_tuple, u_tuple, distance_bins, + x_tuple, u_tuple, distance_bins, w, ) end SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, local_output, local_counts) @@ -242,6 +267,7 @@ function _threaded_pf_simd!( output_sums::AbstractVector{OT}, output_counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, x_arr, u_arr, dist_be, ::Val{D}; geometry = SFH.FlatGeometry{D}(), culling::SFC.CullingPolicy = SFC.AutoCulling(), + weights = SFC.NoWeights(), ) where {OT, CT, D} x_raw = ntuple(d -> collect(view(x_arr, d, :)), Val(D)) u_raw = ntuple(d -> collect(view(u_arr, d, :)), Val(D)) @@ -249,12 +275,13 @@ function _threaded_pf_simd!( nb = n_histogram_bins(dist_be) FTx = eltype(x_raw[1]) plan = SF.squared_digitize_plan(dist_be) # built once; read-only, shared across tasks - # Sorted once and shared read-only, so every task sweeps the cells in the same order. `xc`/`uc` + # Sorted once and shared read-only, so every task sweeps the cells in the same order. `xc`/`uc`/`wc` # are bound once and never reassigned: the tasks close over them, and reassigning a captured # variable boxes it, which OhMyThreads rejects outright. grid = (culling isa SFC.NoCulling) ? nothing : SFC.cull_grid_for(x_raw, geometry, dist_be, culling) xc, uc = isnothing(grid) ? (x_raw, u_raw) : (SFC.apply_perm(x_raw, grid.perm), SFC.apply_perm(u_raw, grid.perm)) + wc = (isnothing(grid) || weights isa SFC.NoWeights) ? weights : weights[grid.perm] result = OMT.tmapreduce(+, _outer_chunks(grid, 1:(Np - 1), Threads.nthreads())) do chunk local_output = zeros(OT, nb) local_counts = zeros(CT, nb) @@ -262,7 +289,7 @@ function _threaded_pf_simd!( valbuf = Vector{OT}(undef, Np) idxbuf = Vector{Int32}(undef, Np) SFC._pf_run_blocks!(local_output, local_counts, sf, xc, uc, plan, Val(D), - r2buf, valbuf, idxbuf, chunk, Np, grid) + r2buf, valbuf, idxbuf, chunk, Np, grid, wc) SFO.StructureFunctionSumsAndCounts(sf, dist_be, local_output, local_counts) end output_sums .+= result.sums @@ -333,7 +360,7 @@ function SFC.threaded_calculate_structure_function!( return nothing end - # Chunked tmapreduce: O(n_tasks) allocations instead of O(N_points) + # Chunked tmapreduce: O(n_tasks) allocations, not O(N_points) result = OMT.tmapreduce(+, _triangle_outer_chunks(eachindex(x_vecs[1]), Threads.nthreads())) do chunk local_sums = zeros(OT, N3, N4) local_counts = zeros(CT, N3, N4) @@ -490,18 +517,14 @@ end # --- Threaded single-pass via OhMyThreads tmapreduce --- # -# IMPORTANT: We use `OMT.tmapreduce` with task-local buffers instead of -# `OMT.tforeach` + `Threads.threadid()` indexing. +# `OMT.tmapreduce` with one task-local buffer per chunk, reduced by summation. # -# Julia tasks are NON-STICKY: they can migrate between OS threads at any yield -# point. This means `Threads.threadid()` is NOT guaranteed to remain constant -# within a single task. Using it to index into shared per-thread buffers causes -# data races → glibc heap corruption (malloc_consolidate / corrupted size). +# Julia tasks are non-sticky: they may migrate between OS threads at any yield point, so +# `Threads.threadid()` is not constant within a task and indexing shared per-thread buffers with it +# is a data race. # -# The correct OhMyThreads pattern (used by all other threaded methods above) -# is to give each chunk its own task-local buffer, then reduce via summation. -# Outer `i` chunks use `_triangle_outer_chunks` (RoundRobin split) because -# contiguous equal-size blocks imbalance O(N²) triangle pair loops. +# Outer `i` chunks come from `_triangle_outer_chunks`, a round-robin split: contiguous equal-size +# blocks imbalance an O(N²) triangle pair loop. # # References: # - OhMyThreads thread-safe storage docs: @@ -846,22 +869,47 @@ function SFC._partial_sums_counts( end +# --- Gridded sweeps --- + +# Each task takes a round-robin share of the sweep's items into private histograms and its own +# scratch; the partials add because a histogram is order-independent. +function SFC.threaded_sweep_reduce!( + sums::AbstractArray{OT}, counts::AbstractArray{CT}, items::AbstractVector, make_scratch, body!, +) where {OT, CT} + isempty(items) && return nothing + n = min(Threads.nthreads(), length(items)) + part = OMT.tmapreduce(_hist_add, OMT.chunks(items; n, split = OMT.RoundRobin())) do chunk + ls = zeros(OT, size(sums)) + lc = zeros(CT, size(counts)) + scratch = make_scratch() + for it in chunk + body!(ls, lc, it, scratch) + end + (ls, lc) + end + sums .+= part[1] + counts .+= part[2] + return nothing +end + +@inline _hist_add(a, b) = (a[1] .+= b[1]; a[2] .+= b[2]; a) + # --- Tensor structure functions --- # Each task takes a round-robin share of the outer index and accumulates into its own buffers; the # partials add because a histogram is order-independent. The setup (widening, bin edges) happens -# once per task rather than once per pair, matching the 1-D threaded path. +# once per task, as on the 1-D threaded path. function SFC.threaded_calculate_structure_function_tensor!( sums::AbstractArray, counts::AbstractArray, order::Val{P}, shape::SFC.AbstractFieldShape{D}, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; - distance_metric::DI.PreMetric = DI.Euclidean(), + distance_metric::DI.PreMetric = DI.Euclidean(), axis = nothing, ) where {P, D} N = size(u, 2) chunks = _triangle_outer_chunks(1:N, Threads.nthreads()) part = OMT.tmapreduce(_tensor_add, chunks) do chunk SFC.tensor_partial(order, shape, x, u, distance_bins, chunk; - distance_metric, count_eltype = eltype(counts)) + distance_metric, count_eltype = eltype(counts), axis) end sums .+= part[1] counts .+= part[2] diff --git a/ext/StructureFunctionsSpectralBackendsExt.jl b/ext/StructureFunctionsSpectralBackendsExt.jl deleted file mode 100644 index 4fb9be2..0000000 --- a/ext/StructureFunctionsSpectralBackendsExt.jl +++ /dev/null @@ -1,27 +0,0 @@ -module StructureFunctionsSpectralBackendsExt - -using SpectralBackends: SpectralBackends as SB -using StructureFunctions: Calculations as SFC - -# The tags that name an algorithm needing no transform. `Auto` resolves here to the lag sweep because -# that is the only summation this session has; the transform extension answers `Auto` on the concrete -# tag, which out-specialises this, and weighs the two costs. - -SFC.gridded_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}, - ::SB.AbstractDirectSumSpectralBackend; valid = SFC.AllValid()) where {D} = - SFC.gridded_lag_sweep!(sums, counts, sf, u, schedule, distance_bins, Val(D); valid) - -SFC.gridded_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}, - ::SB.AbstractAutoSpectralBackend; valid = SFC.AllValid()) where {D} = - SFC.gridded_lag_sweep!(sums, counts, sf, u, schedule, distance_bins, Val(D); valid) - -function SFC.gridded_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}, - backend::SB.AbstractSpectralBackend; kwargs...) where {D} - throw(ArgumentError( - "$(typeof(backend)) needs a transform this session has not loaded: `using FFTW` on CPU, " * - "or another AbstractFFTs implementation. DirectSumSpectralBackend and AutoSpectralBackend " * - "need none.", - )) -end - -end # module diff --git a/ext/cuda/kernels_1d.jl b/ext/cuda/kernels_1d.jl index 1de8b27..718d7fc 100644 --- a/ext/cuda/kernels_1d.jl +++ b/ext/cuda/kernels_1d.jl @@ -1,17 +1,17 @@ # ============================================================================= # CUDA-specialized 1D structure-function kernel (distance histogram only). # -# Same N-body broadcast structure as the 2D kernel, but the histogram is tiny -# (NMOM·NB, NB ≤ 128) so it lives in STATIC shared memory (no dynamic-shared -# opt-in needed) and TILE = 256 (1D is geometry-bound, not occupancy-limited by -# the histogram — measured: N-body gives the ~2× win here, replication R=1). +# Same N-body broadcast structure as the 2D kernel. The histogram is small +# (NMOM·NB, NB ≤ 128), so it lives in STATIC shared memory, needing no +# dynamic-shared opt-in, and TILE = 256: this kernel is geometry-bound, so the +# histogram does not limit occupancy and the replication factor is 1. # Covers individual (NMOM=1) and single-pass (NMOM=6), fixed-x and varying-x, # D ∈ {2,3}. Output is (NMOM, NB, B); counts are per-bin (shared across moments). # ============================================================================= """Compiled-in cap on distance bins for the static shared 1D histogram.""" const CU_MAX_BINS = 128 -"""Block size for the 1D N-body kernel (settled design).""" +"""Block size for the 1D N-body kernel.""" const CU_TILE_1D = 256 function _cuda_sf_1d_kernel!( diff --git a/ext/cuda/kernels_2d.jl b/ext/cuda/kernels_2d.jl index 3e3f5b4..a6d18cf 100644 --- a/ext/cuda/kernels_2d.jl +++ b/ext/cuda/kernels_2d.jl @@ -1,20 +1,18 @@ # ============================================================================= # CUDA-specialized 2D structure-function kernel (distance × value histogram). # -# N-body broadcast structure + privatized DYNAMIC-shared histogram. This is the -# settled-optimal design (gpu/OPTIMAL_KERNEL_DESIGN.md): -# - each thread owns its point i (registers); loops j over the staged tile so -# all lanes read the SAME shared[j] each step (broadcast, no bank conflict, -# no per-pair pair-decode sqrt); -# - per-block histogram (sums + counts) lives in dynamic shared memory (A100 -# 163 KB opt-in) and is atomic-merged to the global output at block end; -# - TILE = block size = 1024 (50% occupancy beats 25% on the heavy 50×50 case, -# measured job 238806: 8.36 vs 6.39 bapps). Device-aware: the launcher drops -# TILE (1024→512→256) until staging + dynamic histogram fit the device -# opt-in max, and returns `false` (KA fallback) if even TILE=256 won't fit. +# N-body broadcast structure with a privatized dynamic-shared histogram: +# - each thread owns its point i in registers and loops j over the staged tile, +# so all lanes read the same shared[j] at each step: a broadcast, with no bank +# conflict and no per-pair pair-decode sqrt; +# - the per-block histogram (sums + counts) lives in dynamic shared memory and is +# atomic-merged into the global output at block end; +# - TILE = block size = 1024. The launcher drops TILE (1024→512→256) until the +# staging plus the dynamic histogram fit the device's opt-in maximum, and +# returns `false` for the KA fallback when even 256 will not fit. # # Covers joint 2D (NMOM=1) and single-pass 2D (NMOM=6), fixed-x and varying-x, -# D ∈ {2,3} — all via Val type params. Validated in proto_nbody2d / proto_settle. +# D ∈ {2,3}, all through Val type parameters. # ============================================================================= """ @@ -25,8 +23,7 @@ Row stride of the value axis in the privatized histogram, forced odd. Shared memory has 32 banks. With a power-of-two `n_val`, the flat index `(dbin-1)*n_val + vbin` puts every value-axis row into the same couple of banks, so lanes differing only in `dbin` serialize on bank conflicts even though they target different cells. An odd stride is coprime with 32 and spreads -them across banks, at the cost of one unused column per row. Measured 2.0–2.3× on the sibling -single-pass 2D kernel, which had identical indexing. +them across banks, at the cost of one unused column per row. """ @inline _cuda_val_stride(n_val::Int) = isodd(n_val) ? n_val : n_val + 1 @@ -152,15 +149,12 @@ end """Largest TILE ∈ (1024,512,256) whose staging + the full `NMOM`-plane dynamic histogram fit the device opt-in shared max; 0 if even 256 won't fit. -Returning 0 hands the call to the naive global-atomic kernel, which is the measured winner whenever -the histogram does not fit on chip: contention spreads over many cells, and it beats every on-chip -variant there (128×128 Float64: 5.95 vs 0.75 bapps). Splitting the histogram into moment planes to -force it on chip was implemented and measured — it is ~2× *slower* than going global, so the -all-or-nothing test below is deliberate. See `gpu/SPEED_OF_LIGHT.md`.""" +Returning 0 hands the call to the global-atomic kernel, which wins whenever the histogram does not +fit on chip: a histogram that large spreads its contention over many cells. The test is +all-or-nothing, so a histogram is either privatized whole or left in global memory.""" function _cuda_2d_pick_tile(::Type{FT}, D::Int, NMOM::Int, n_dist::Int, n_val::Int) where {FT} - # Queried, never assumed: this is only reached via the CUDABackend hook, so a device is present - # by construction and a failure here is a real driver fault. Defaulting to the 48 KB static cap - # instead would silently forfeit ~3.4× the shared budget on an A100 (163 KB opt-in). + # Queried, never assumed: this is reached only through the CUDABackend hook, so a device is + # present by construction and a failure here is a driver fault. optin = Int(CUDA.attribute(CUDA.device(), CUDA.DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN)) dynb = NMOM * n_dist * _cuda_val_stride(n_val) * (sizeof(FT) + sizeof(UInt32)) for TILE in (1024, 512, 256) diff --git a/ext/gpu/batch_dispatch.jl b/ext/gpu/batch_dispatch.jl index ad9201d..8134257 100644 --- a/ext/gpu/batch_dispatch.jl +++ b/ext/gpu/batch_dispatch.jl @@ -70,12 +70,10 @@ function _gpu_1d_unified_device( return Array(out_dev), Array(cnt_dev) end -"""Individual (NMOM=1) 1D batch device launch, routed to the measured-optimal -kernel per regime (job 239164, histograms verified equal): -- fixed-x + linear/log FMA bins → OLD global warp-replica + W-strip kernel - (tiny-histogram contention-bound regime: 147 vs 115 bapps for N-body). -- varying-x, or general (raw-vector) fixed-x bins → N-body broadcast (115 vs 61 - bapps for the old kernel on varying-x; also handles general bins). +"""Individual (NMOM=1) 1D batch device launch, routed per regime: +- fixed-x with linear or log FMA bins → global warp-replica kernel over W-strips, which wins where + the histogram is small enough to be contention-bound. +- varying-x, or general (raw-vector) bins → N-body broadcast. Returns host `(sums, counts)` of shape `(NB, B)`.""" function _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, NB::Int, B::Int, fixed_x::Bool, ::Type{OT}, geom) where {OT} diff --git a/ext/gpu/kernels_1d_single_pass.jl b/ext/gpu/kernels_1d_single_pass.jl index 2420ed5..755f8c3 100644 --- a/ext/gpu/kernels_1d_single_pass.jl +++ b/ext/gpu/kernels_1d_single_pass.jl @@ -6,20 +6,20 @@ Rows 3 (`T2`) and 6 (`L1T2`) are exact differences of the others (`T2 = S2 - L2`, `L1T2 = S3 - L3`) and a bin is a sum, so they are left zero here and reconstructed once at flush by -[`_sf_flush_moment`](@ref) — 4 shared atomics per pair instead of 6.""" +[`_sf_flush_moment`](@ref), leaving 4 shared atomics per pair.""" @inline function _gpu_accumulate_single_pass_1d_shared!( shared_sums, shared_cnts, bin::Int, du_L, - du_L2, du_norm2, NB::Int, ) - @atomic shared_sums[bin] += du_norm2 - @atomic shared_sums[NB + bin] += du_L2 - @atomic shared_sums[3NB + bin] += du_L * du_norm2 - @atomic shared_sums[4NB + bin] += du_L * du_L2 + vals = SFC.single_pass_invariants(du_L, du_norm2) + @atomic shared_sums[bin] += vals[1] + @atomic shared_sums[NB + bin] += vals[2] + @atomic shared_sums[3NB + bin] += vals[4] + @atomic shared_sums[4NB + bin] += vals[5] @atomic shared_cnts[bin] += UInt32(1) return nothing end @@ -127,9 +127,8 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_linear_ ) if ok && 1 <= bin < N_bins du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_norm2, NB, ) end p += workgroup_size @@ -264,9 +263,8 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_log_u32 bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) if ok && 1 <= bin < N_bins du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_norm2, NB, ) end p += workgroup_size @@ -399,9 +397,8 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_general bin = _gpu_digitize_general(dist, bins, N_bins) if ok && 1 <= bin < N_bins du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_norm2, NB, ) end p += workgroup_size diff --git a/ext/gpu/kernels_2d_direct.jl b/ext/gpu/kernels_2d_direct.jl index a638b3a..e067cbc 100644 --- a/ext/gpu/kernels_2d_direct.jl +++ b/ext/gpu/kernels_2d_direct.jl @@ -4,8 +4,7 @@ # via _sp2d_flush_*_to_output! (@atomic into out_sums/out_cnts, joint pattern). # Direct (:direct): global atomics into block-private partition; merge on host. # -# See gpu/SP2D_HTP_EJ.md for strategy, benchmarks, and future perf notes. -# Included from StructureFunctionsKernelAbstractionsExt.jl after TiledSinglePass2DValueKernels.jl. +# Included from StructureFunctionsKernelAbstractionsExt.jl. """Load point `k`'s D-vector from a tile buffer staged as `(d-1)*SF_GPU_TILE + k`.""" @inline _sp2d_ld_tile(buf, ::Val{2}, k) = @@ -141,14 +140,10 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_linear_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin, du_L, du_L2, du_T2, N_val_edges, + dbin, du_L, du_n2, N_val_edges, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, @@ -165,13 +160,9 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_linear_val_cols!( shared_sums, shared_cnts, n_dist, n_val, val_first, val_last, val_inv_step, val_step, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -188,15 +179,11 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_inflinear_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first, val_last, val_inv_step, val_step, @@ -214,13 +201,9 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_inflinear_val_cols!( shared_sums, shared_cnts, n_dist, n_val, val_first, val_last, val_inv_step, val_step, inner_last, - dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + dbin::Int, du_L, du_n2, n_inner_edges::Int, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -237,14 +220,10 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_log_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced( vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, @@ -260,14 +239,10 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_log_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first, val_last, val_inv_step, val_step, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced_col( vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges, @@ -283,14 +258,10 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_vector_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, value_edges, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_general_col(vals[t], value_edges, t, N_val_edges) if 1 <= vbin < N_val_edges @@ -385,14 +356,10 @@ end @inline function _gpu_accumulate_sp2d_typeplane_linear_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -412,13 +379,9 @@ end @inline function _gpu_accumulate_sp2d_typeplane_linear_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, val_first, val_last, val_inv_step, val_step, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -439,15 +402,11 @@ end @inline function _gpu_accumulate_sp2d_typeplane_inflinear_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -468,13 +427,9 @@ end @inline function _gpu_accumulate_sp2d_typeplane_inflinear_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, val_first, val_last, val_inv_step, val_step, inner_last, - dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + dbin::Int, du_L, du_n2, n_inner_edges::Int, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -495,14 +450,10 @@ end @inline function _gpu_accumulate_sp2d_typeplane_log_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -521,14 +472,10 @@ end @inline function _gpu_accumulate_sp2d_typeplane_log_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first, val_last, val_inv_step, val_step, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -548,14 +495,10 @@ end @inline function _gpu_accumulate_sp2d_typeplane_vector_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, value_edges, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi @@ -574,14 +517,10 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_linear_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, @@ -597,13 +536,9 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_linear_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, val_first, val_last, val_inv_step, val_step, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -619,15 +554,11 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_inflinear_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first, val_last, val_inv_step, val_step, @@ -644,13 +575,9 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_inflinear_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, val_first, val_last, val_inv_step, val_step, inner_last, - dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + dbin::Int, du_L, du_n2, n_inner_edges::Int, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -666,14 +593,10 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_log_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced( vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, @@ -688,14 +611,10 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_log_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, val_first, val_last, val_inv_step, val_step, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced_col( vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges, @@ -710,14 +629,10 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_vector_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_n2, N_val_edges::Int, value_edges, ) - vals = SA.SVector( - du_L2 + du_T2, du_L2, du_T2, - du_L * (du_L2 + du_T2), du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_general_col(vals[t], value_edges, t, N_val_edges) if 1 <= vbin < N_val_edges @@ -900,7 +815,7 @@ function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_linear_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -909,7 +824,7 @@ function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_linear_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -920,7 +835,7 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:shared}) _gpu_accumulate_sp2d_sharedhist_linear_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end end @@ -929,7 +844,7 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:direct}) _gpu_accumulate_sp2d_partitioned_direct_linear_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end end @@ -938,7 +853,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_inflinear_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end @@ -947,7 +862,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_inflinear_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end @@ -958,7 +873,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:shared}) _gpu_accumulate_sp2d_sharedhist_inflinear_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, val_first, val_last, val_inv_step, val_step, inner_last, - bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, + bin, du_L, du_n2, n_inner_edges, N_val_edges, ) end end @@ -967,7 +882,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:direct}) _gpu_accumulate_sp2d_partitioned_direct_inflinear_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, val_first, val_last, val_inv_step, val_step, inner_last, - bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, + bin, du_L, du_n2, n_inner_edges, N_val_edges, ) end end @@ -976,7 +891,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_log_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -985,7 +900,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_log_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -995,7 +910,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_log_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -1004,7 +919,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_log_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -1014,7 +929,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_vector_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_n2, N_val_edges, value_edges, ) end end @@ -1022,7 +937,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_vector_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_n2, N_val_edges, value_edges, ) end end @@ -1032,7 +947,7 @@ function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_linear_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -1042,7 +957,7 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:typeplane}) _gpu_accumulate_sp2d_typeplane_linear_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end end @@ -1050,7 +965,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_inflinear_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end @@ -1060,7 +975,7 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:typeplane}) _gpu_accumulate_sp2d_typeplane_inflinear_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, val_first, val_last, val_inv_step, val_step, inner_last, - bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, + bin, du_L, du_n2, n_inner_edges, N_val_edges, ) end end @@ -1068,7 +983,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_log_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -1077,7 +992,7 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_log_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -1086,7 +1001,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_vector_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_n2, N_val_edges, value_edges, ) end end @@ -1141,8 +1056,8 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo val_params = _sp2d_partition_val_params(Val(val)) accum = _sp2d_partition_val_accum(Val(val), Val(accum_mode)) uses_shared = accum_mode in (:shared, :typeplane) - # Width is a kernel type parameter, so one definition specializes per config instead of every - # config paying for the largest one the budget allows. + # Width is a kernel type parameter, so one definition specializes per config and no config pays + # for the largest one the budget allows. shared_hist_decl = uses_shared ? quote shared_sums = @localmem OT (HC,) shared_cnts = @localmem UInt32 (HC,) @@ -1175,13 +1090,10 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = $(dist_bin) if ok && 1 <= bin < N_bins - # |du_T|² from the norm rather than a transverse basis vector: the six invariants - # use only du_L, du_L², du_T², never the signed du_T, and building n̂ = (r̂₂, -r̂₁) - # is both wasted work and the kernel's only 2D-specific assumption. This is also - # exactly the CPU's formula, so the two agree to the last bit of the algorithm. + # |du_T|² from the norm: the six invariants use only du_L, du_L² and du_T², never + # the signed du_T, so n̂ = (r̂₂, -r̂₁) is never built and the kernel carries no + # 2-D-specific assumption. This is the CPU's formula, so the two sum one expression. du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 $(accum) end p += workgroup_size diff --git a/ext/gpu/kernels_2d_single_pass.jl b/ext/gpu/kernels_2d_single_pass.jl index 92fb428..193cc69 100644 --- a/ext/gpu/kernels_2d_single_pass.jl +++ b/ext/gpu/kernels_2d_single_pass.jl @@ -1,5 +1,5 @@ # Tiled128 six-invariant-type single-pass 2D joint histogram kernels (global-atomic path). -# Production fast path when eligible is HTP-EJ in kernels_2d_direct.jl (see gpu/SP2D_HTP_EJ.md). +# An eligible call takes HTP-EJ in kernels_2d_direct.jl instead. # This file: tile schedule matches 1D tiled128; non-HTP-EJ route uses global atomics. @inline function _gpu_accumulate_single_pass_2d_pair_global!( @@ -8,18 +8,10 @@ value_edges, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_general_col(vals[t], value_edges, t, N_val_edges) if 1 <= vbin < N_val_edges @@ -35,22 +27,14 @@ end output_counts, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, @@ -72,19 +56,11 @@ end val_step, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, ) FT = eltype(output_sums) - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -103,8 +79,7 @@ end output_counts, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, val_first::FT, val_last::FT, @@ -113,14 +88,7 @@ end n_inner_edges::Int, inner_last::FT, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first, val_last, val_inv_step, val_step, @@ -144,19 +112,11 @@ end inner_last, bin::Int, du_L, - du_L2, - du_T2, + du_n2, n_inner_edges::Int, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], @@ -179,18 +139,10 @@ end val_step::FT, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, ) where {FT} - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced(vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges) if 1 <= vbin < N_val_edges @@ -210,18 +162,10 @@ end val_step, bin::Int, du_L, - du_L2, - du_T2, + du_n2, N_val_edges::Int, ) - vals = SA.SVector( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) + vals = SA.SVector(SFC.single_pass_invariants(du_L, du_n2)) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced_col(vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges) if 1 <= vbin < N_val_edges @@ -326,11 +270,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line ) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val!( output_sums, output_counts, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end @@ -429,11 +371,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global!( output_sums, output_counts, value_edges, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -534,11 +474,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val!( output_sums, output_counts, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, ) end diff --git a/ext/gpu/kernels_2d_value_axis.jl b/ext/gpu/kernels_2d_value_axis.jl index acf2b99..afddfd5 100644 --- a/ext/gpu/kernels_2d_value_axis.jl +++ b/ext/gpu/kernels_2d_value_axis.jl @@ -87,11 +87,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -153,11 +151,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -220,10 +216,8 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val!( - output_sums, output_counts, bin, du_L, du_L2, du_T2, N_val_edges, + output_sums, output_counts, bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end @@ -287,10 +281,8 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val!( - output_sums, output_counts, bin, du_L, du_L2, du_T2, N_val_edges, + output_sums, output_counts, bin, du_L, du_n2, N_val_edges, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end @@ -354,11 +346,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, inner_last, - bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, + bin, du_L, du_n2, n_inner_edges, N_val_edges, ) end p += workgroup_size @@ -421,11 +411,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, inner_last, - bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, + bin, du_L, du_n2, n_inner_edges, N_val_edges, ) end p += workgroup_size @@ -487,11 +475,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -553,11 +539,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global!( output_sums, output_counts, value_edges, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -619,11 +603,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, bin, - du_L, du_L2, du_T2, N_val_edges, + du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -685,11 +667,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end p += workgroup_size @@ -751,11 +731,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) if ok && 1 <= bin < N_bins du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) - du_L2 = du_L * du_L - du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val_cols!( output_sums, output_counts, val_first, val_last, val_inv_step, val_step, - bin, du_L, du_L2, du_T2, N_val_edges, + bin, du_L, du_n2, N_val_edges, ) end p += workgroup_size diff --git a/ext/gpu/kernels_batch.jl b/ext/gpu/kernels_batch.jl index e00be13..bdebfde 100644 --- a/ext/gpu/kernels_batch.jl +++ b/ext/gpu/kernels_batch.jl @@ -77,14 +77,15 @@ end @inline _gpu_pow_int(x, ::Val{3}) = x * x * x @inline _gpu_pow_int(x, ::Val{N}) where {N} = x^N -@inline function _gpu_sf_value_2d(::SFT.ProjectedStructureFunctionType{NL, NT}, du_x, du_y, rx, ry) where {NL, NT} +@inline function _gpu_sf_value_2d(sf::SFT.ProjectedStructureFunctionType{NL, NT}, du_x, du_y, rx, ry) where {NL, NT} du_L = rx * du_x + ry * du_y - du_T = ry * du_x - rx * du_y val = one(du_L) if NL != 0 val *= _gpu_pow_int(du_L, Val(NL)) end if NT != 0 + e = SFH.transverse_basis_vector(SA.SVector(rx, ry), sf.basis) + du_T = e[1] * du_x + e[2] * du_y val *= _gpu_pow_int(du_T, Val(NT)) end return val diff --git a/ext/gpu/launch.jl b/ext/gpu/launch.jl index c446b3b..ccfd43a 100644 --- a/ext/gpu/launch.jl +++ b/ext/gpu/launch.jl @@ -216,7 +216,6 @@ end # _launch_sp2d_direct_partitioned! (private partition + merge) # # Kernel resolution cached on GPUSFWorkspace.sp2d_pair_kernel when using a workspace. -# See gpu/SP2D_HTP_EJ.md function _sp2d_val_variant(::GPUValueLinearShared) return :linear_shared @@ -1373,9 +1372,9 @@ function _launch_single_pass_2d_kernel!( value_edges_dev = workspace === nothing ? nothing : workspace.value_edges_dev if value_edges_dev === nothing # This kernel digitizes the value axis by binary search, so it needs the explicit edge - # vector. The linear plan carries `first`/`last`, so reconstruct it rather than demanding a - # workspace: this path is the only route when `n_dist > SF_GPU_MAX_BINS`, and requiring a - # workspace there made every large-bin call fail outright. + # vector, which is reconstructed from the linear plan's `first`/`last`. This path is the + # only route when `n_dist > SF_GPU_MAX_BINS`, so demanding a workspace here fails every + # large-bin call. VT = typeof(vp.first) value_edges_dev = KA.allocate(backend, VT, n_val_edges) copyto!(value_edges_dev, collect(range(vp.first, vp.last; length = n_val_edges))) @@ -1509,7 +1508,6 @@ end """ Offer a non-batch single-pass 2D launch to the batch dispatcher as `B=1`, reaching the CUDA N-body + dynamic-shared kernel; `false` means the hook declined and the caller continues unchanged. -Measured on A100 (N=20000): 1.24× Float32, 2.58× Float64. See `gpu/SPEED_OF_LIGHT.md`. """ @inline function _sp2d_try_fast_batch!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_bins, val_plan, diff --git a/ext/gpu/channels.jl b/ext/gpu/multifields.jl similarity index 72% rename from ext/gpu/channels.jl rename to ext/gpu/multifields.jl index 06e1646..1a55c70 100644 --- a/ext/gpu/channels.jl +++ b/ext/gpu/multifields.jl @@ -1,10 +1,10 @@ -# Multi-channel (`Fields`) sweeps on a device. +# Multi-field (`Fields`) sweeps on a device. # -# The bundle is already one packed `(V*F + K, N)` array, which is exactly what the scalar kernels -# stage, so the only new thing here is building the per-pair `ChannelIncrement` the operator reads. +# The multi-field is already one packed `(V*F + K, N)` array, which is exactly what the scalar kernels +# stage, so the only new thing here is building the per-pair `FieldIncrement` the operator reads. # One thread owns an `i` and walks every `j > i`, accumulating into a global histogram. -KA.@kernel unsafe_indices = true function _channel_kernel!( +KA.@kernel unsafe_indices = true function _field_kernel!( sums, counts, @Const(x_mat), @Const(data), sf, geom, plan, N_points::Int, N_bins::Int, ::Val{W}, ::Val{F}, ::Val{V}, ::Val{K}, ) where {W, F, V, K} @@ -18,8 +18,7 @@ KA.@kernel unsafe_indices = true function _channel_kernel!( if ok bin = SFC.squared_digitize(plan, r * r) if 1 <= bin <= N_bins - inc = SFC.channel_increment(Val(F), Val(V), Val(K), data, geom, frame, i, j) - val = sf(inc, SFH.pair_direction(geom, frame, r)) + val = SFC._field_value(sf, Val(F), Val(V), Val(K), data, geom, frame, r, i, j) @atomic sums[bin] += val @atomic counts[bin] += one(eltype(counts)) end @@ -28,11 +27,11 @@ KA.@kernel unsafe_indices = true function _channel_kernel!( end end -function SFC.gpu_calculate_structure_function_channels!( +function SFC.gpu_calculate_structure_function_fields!( backend::CB.AbstractGPUBackend, sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::SFC.CH.Fields{D, V, K}, distance_bins; + x::AbstractMatrix, f::SFC.MF.Fields{D, V, K}, distance_bins; distance_metric::DI.PreMetric = DI.Euclidean(), culling = SFC.AutoCulling(), verbose::Bool = true, show_progress::Bool = true, @@ -40,10 +39,10 @@ function SFC.gpu_calculate_structure_function_channels!( _ = (verbose, show_progress) # Culling reorders the points on the host; the device sweep enumerates the full triangle, and # a permutation does not change a histogram, so the request is honoured by declining to permute. - geom, xk, data, vF, plan, _ = SFC.channel_setup(f, x, distance_bins, distance_metric, + geom, xk, data, vF, plan, _ = SFC.field_setup(f, x, distance_bins, distance_metric, SFC.NoCulling()) culling isa SFC.AlwaysCulling && throw(ArgumentError( - "GPU multi-channel sweeps do not build a cell grid on device; use AutoCulling (which " * + "GPU multi-field sweeps do not build a cell grid on device; use AutoCulling (which " * "declines here) or a CPU backend to cull.", )) @@ -58,7 +57,7 @@ function SFC.gpu_calculate_structure_function_channels!( s_dev = KA.adapt(ka, zeros(eltype(sums), nb)) c_dev = KA.adapt(ka, zeros(eltype(counts), nb)) - kernel = _channel_kernel!(ka, 256) + kernel = _field_kernel!(ka, 256) kernel(s_dev, c_dev, x_dev, d_dev, sf, geom, plan, N, nb, Val(W), Val(F), Val(V), Val(K); ndrange = N) KA.synchronize(ka) diff --git a/ext/gpu/sf_core.jl b/ext/gpu/sf_core.jl index 17ec6d0..6df8b03 100644 --- a/ext/gpu/sf_core.jl +++ b/ext/gpu/sf_core.jl @@ -1,6 +1,5 @@ # ============================================================================= # Unified parametric GPU kernel core — building blocks -# See gpu/OPTIMAL_KERNEL_DESIGN.md for the full design rationale. # # These are the compile-time-specialized primitives shared by the two unified # tiled kernels (`sf_tiled_1d!`, `sf_tiled_2d!`). Everything here is `@inline`, @@ -18,11 +17,10 @@ # mirrors built host-side via `_sf_digitizer`. # * The shared histogram uses a "lane" axis of width `L` as its fastest index: # hist[((m-1)*NB + (bin-1)) * L + lane] -# For the non-fixed-x path `L = R` (replication factor → contention spreading; -# replicas are summed at flush). For the fixed-x batch path `L = W` (batch -# strip → each lane is a distinct velocity field; NOT summed, scattered to the -# B axis at flush). Same accumulate primitive, different flush. -# IMPORTANT: we rotate the *lane* (replica) index, never the *bin* index. +# For the non-fixed-x path `L = R`, the replication factor that spreads contention, and the +# replicas are summed at flush. For the fixed-x batch path `L = W`, the batch strip: each lane is +# a distinct velocity field, not summed but scattered to the B axis at flush. One accumulate +# primitive, two flushes. The rotation is applied to the lane index, never to the bin index. # ============================================================================= # ----------------------------------------------------------------------------- @@ -73,6 +71,29 @@ KA.Adapt.adapt_structure(to, d::SFGeneralDigitizer) = KA.Adapt.adapt_structure(to, s::TilePairWorkList) = TilePairWorkList(KA.Adapt.adapt(to, s.pairs), s.n_tiles) +# Bin edges, digitize plans and lag schedules reach a kernel with their vectors on the device. +KA.Adapt.adapt_structure(to, b::SF.BinEdges) = SF.BinEdges(KA.Adapt.adapt(to, b.edges)) +KA.Adapt.adapt_structure(to, b::SF.InfPaddedBinEdges) = SF.InfPaddedBinEdges(KA.Adapt.adapt(to, b.edges)) +function KA.Adapt.adapt_structure(to, p::SF.SquaredLogPlan{T}) where {T} + sq = KA.Adapt.adapt(to, p.sqedges) + return SF.SquaredLogPlan{T, typeof(sq)}(p.a, p.b, p.n_bins, sq) +end +function KA.Adapt.adapt_structure(to, p::SF.SquaredLinearPlan{T}) where {T} + sq = KA.Adapt.adapt(to, p.sqedges) + return SF.SquaredLinearPlan{T, typeof(p.edges), typeof(sq)}(p.edges, p.n_bins, sq) +end +function KA.Adapt.adapt_structure(to, p::SF.SquaredGeneralPlan{T}) where {T} + sq = KA.Adapt.adapt(to, p.sqedges) + return SF.SquaredGeneralPlan{T, typeof(sq)}(p.n_bins, sq) +end +KA.Adapt.adapt_structure(to, p::SF.SquaredInfPaddedPlan) = SF.SquaredInfPaddedPlan(KA.Adapt.adapt(to, p.inner)) +KA.Adapt.adapt_structure(to, s::SFC.RectilinearLagSchedule) = + SFC.RectilinearLagSchedule(s.uniform, map(v -> KA.Adapt.adapt(to, v), s.enumerated), s.axis_order) +KA.Adapt.adapt_structure(to, s::SFC.ZonalLagSchedule) = + SFC.ZonalLagSchedule(KA.Adapt.adapt(to, s.lats), s.n_lon, s.dlon, s.radius, s.lon_periodic) +KA.Adapt.adapt_structure(to, s::SFC.ScatteredModesSchedule) = + SFC.ScatteredModesSchedule(KA.Adapt.adapt(to, s.points), s.origin, s.box, s.modes, s.taper) + @inline (d::SFGeneralDigitizer)(r) = _gpu_digitize_general(r, d.edges, d.n_edges) # Number of bins (edges - 1) for a digitizer. @@ -112,13 +133,8 @@ end """Six single-pass invariants from a velocity difference `dU` and unit vector `rhat`. Computes one dot product (`du_L`) and one norm (`du_norm2`); transverse follows as `du_norm2 - du_L²` (no second projection).""" -@inline function _sf_moments6(dU::SA.SVector{D,T}, rhat::SA.SVector{D,T}) where {D,T} - du_L = _sf_dot(dU, rhat) - du_norm2 = _sf_dot(dU, dU) - du_L2 = du_L * du_L - du_T2 = du_norm2 - du_L2 - return (du_norm2, du_L2, du_T2, du_L * du_norm2, du_L * du_L2, du_L * du_T2) -end +@inline _sf_moments6(dU::SA.SVector{D,T}, rhat::SA.SVector{D,T}) where {D,T} = + SFC.single_pass_invariants(_sf_dot(dU, rhat), _sf_dot(dU, dU)) """Compute the moment tuple for a pair: - `Val{6}` → the six single-pass invariants (sf_type ignored). @@ -132,8 +148,8 @@ end """ Moments needing a per-pair atomic. `T2 = S2 - L2` and `L1T2 = S3 - L3` hold for every pair, and a -histogram bin is a sum, so both are recovered exactly at flush by [`_sf_flush_moment`](@ref) -rather than costing an atomic on each pair. +histogram bin is a sum, so both are recovered exactly at flush by [`_sf_flush_moment`](@ref) and +cost no atomic on any pair. """ @inline _sf_accum_moments(::Val{6}) = (1, 2, 4, 5) @inline _sf_accum_moments(::Val{1}) = (1,) @@ -155,10 +171,8 @@ end # shared_sums[(m-1)*NB*L + (bin-1)*L + ℓ] (L = R or W, compile-time) # shared_cnts[(bin-1)*L + ℓ] # -# All looped reads/writes/atomics on these `@localmem` buffers are written -# INLINE in the kernel bodies, NOT via helper functions. On the CUDA backend a -# `@localmem` array passed as a function argument and written in a loop fails to -# compile (GPUCompiler MethodError); inlining matches the proven pattern used by -# the existing tiled kernels. Single-element loads through a helper are fine -# (see `_sf_load_pt` / `_sf_load_field`). +# Every looped read, write and atomic on these `@localmem` buffers is written inline in the kernel +# bodies: on the CUDA backend a `@localmem` array passed as a function argument and written in a +# loop fails to compile with a GPUCompiler MethodError. Single-element loads through a helper +# compile (`_sf_load_pt`, `_sf_load_field`). # ----------------------------------------------------------------------------- diff --git a/ext/gpu/sf_tiled.jl b/ext/gpu/sf_tiled.jl index 7d40c97..e935238 100644 --- a/ext/gpu/sf_tiled.jl +++ b/ext/gpu/sf_tiled.jl @@ -1,6 +1,5 @@ # ============================================================================= -# Unified parametric tiled kernels (replace the per-variant 1D/2D kernels). -# See gpu/OPTIMAL_KERNEL_DESIGN.md. Building blocks in sf_core.jl. +# Unified parametric tiled kernels. Building blocks in sf_core.jl. # # sf_tiled_1d_varying! — non-batch (B=1) and varying-x batch (B>1). One # workgroup per (tile-pair, batch element). Privatized + R-replicated shared @@ -195,12 +194,10 @@ and silently corrupt the histogram. Must be called by every launcher of those ke return nothing end -"""Replication factor R for the 1D varying-x shared histogram, from the A100 R/W -sweep (gpu/benchmark_results/tune_*.md). Regime-dependent: -- Individual SF (NMOM=1): tiny histogram, extreme per-bin contention → R=2 helps - small NB (NB16: R2≈77 vs R1≈70); larger NB are flat. Beyond R=2 hurts (occupancy). -- Single-pass (NMOM=6): 6× bigger histogram → R=1 (R≥2 blows occupancy: R1≈35, - R4≈22, R8≈11). So R=1.""" +"""Replication factor R for the 1D varying-x shared histogram, by regime: +- individual (NMOM = 1): the histogram is small and per-bin contention high, so a second replica + pays for itself at small bin counts and a third costs more occupancy than it returns; +- single-pass (NMOM = 6): the histogram is six times larger, so any replication costs occupancy.""" @inline _sf_tiled_1d_replication(::Type{FT}, D::Int, NMOM::Int) where {FT} = NMOM == 1 ? 2 : 1 """Launch sf_tiled_1d_varying! for non-batch (B=1) or varying-x (B>1). @@ -241,11 +238,11 @@ end # of W fields (W is the privatization axis). Sums use lane = field (scatter to B # at flush, NOT summed). Counts are field-independent, so the W lanes are used as # contention replicas (one atomic/pair) and summed → broadcast to the strip's B. -# Host launches ⌈B/W⌉ strips (cheap, async, single sync); geometry is recomputed -# per strip (W-fold reuse — moments dominate, so this is near-optimal). -# W-strip shared index for field w, dim d, local point k: laid out -# `((w-1)*D + (d-1))*SF_GPU_TILE + k` (written inline at the use sites to match -# the proven inline-index staging pattern that compiles on CUDA). +# The host launches ⌈B/W⌉ strips asynchronously and synchronizes once; geometry is recomputed per +# strip, so each computation is reused W-fold. +# W-strip shared index for field w, dim d, local point k: +# `((w-1)*D + (d-1))*SF_GPU_TILE + k`, written inline at the use sites, as every looped `@localmem` +# index must be. # ============================================================================= KA.@kernel unsafe_indices = true function sf_tiled_1d_fixed!( @@ -430,12 +427,9 @@ end @inline _sf_load_field(::Val{3}, buf, w::Int, k::Int) = @inbounds SA.SVector{3}(buf[(w - 1) * 3 * SF_GPU_TILE + k], buf[((w - 1) * 3 + 1) * SF_GPU_TILE + k], buf[((w - 1) * 3 + 2) * SF_GPU_TILE + k]) -"""Strip width W for fixed-x 1D, from the A100 R/W sweep. Regime-dependent: -- Individual SF (NMOM=1): a 4-wide strip amortizes the (relatively expensive) - geometry over 4 fields → W=4 is the clear peak (~99–107 Gpairs/s vs 64 at W=1, - across NB=16/50/128); this also makes fixed-x beat varying-x as it should. -- Single-pass (NMOM=6): 6× histogram → striping blows occupancy → W=1 (W1≈40, - W2≈34, W4≈22). See gpu/benchmark_results/tune_*.md.""" +"""Strip width W for fixed-x 1D, by regime: +- individual (NMOM = 1): a 4-wide strip amortizes one pair's geometry over four fields; +- single-pass (NMOM = 6): the histogram is six times larger and striping costs occupancy, so W = 1.""" @inline _sf_tiled_1d_fixed_strip(::Type{FT}, D::Int, NMOM::Int) where {FT} = NMOM == 1 ? 4 : 1 """Launch fixed-x batch 1D over ⌈B/W⌉ strips. x_dev=(D,N), u_dev=(D,N,B), @@ -762,9 +756,8 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_shared!( end end -"""Does a shared NMOM×n_dist×n_val histogram (sums+counts) fit in ~44 KB -alongside the 4 staged coordinate tiles? If so the shared kernel is much faster -than direct global atomics.""" +"""Whether a shared NMOM×n_dist×n_val histogram (sums + counts) fits in 44 KiB alongside the four +staged coordinate tiles, which is the condition for taking the shared kernel.""" @inline function _sf_2d_shared_fits(::Type{FT}, D::Int, NMOM::Int, n_dist::Int, n_val::Int) where {FT} hist = NMOM * n_dist * n_val * (sizeof(FT) + sizeof(UInt32)) staging = 4 * D * SF_GPU_TILE * sizeof(FT) @@ -982,9 +975,8 @@ function _sf_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, # TILE=1024) when StructureFunctionsCUDAExt is active and it fits the device. SFC.gpu_fast_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, D, NMOM, fixed_x, geom, nothing) && return nothing - # Prefer the shared-histogram kernel (fixed or varying) when the histogram - # fits (~7× faster than direct global atomics); fall back to global for large - # bin counts that don't fit in shared memory. + # The shared-histogram kernel (fixed or varying) whenever the histogram fits; a bin count too + # large for shared memory goes to global atomics. use_shared = _sf_2d_shared_fits(eltype(out_dev), D, NMOM, n_dist, n_val) go(Dv) = use_shared ? diff --git a/ext/gpu/sp2d_accumulation_strategy.jl b/ext/gpu/sp2d_accumulation_strategy.jl index d10b43d..ce26a73 100644 --- a/ext/gpu/sp2d_accumulation_strategy.jl +++ b/ext/gpu/sp2d_accumulation_strategy.jl @@ -42,25 +42,17 @@ Joint-histogram bytes above which plain global atomics beat `:direct`, so `_laun routes past it. `:direct` gives up the on-chip histogram for block-private global partitions plus a merge pass, so -its cost grows with cells × tile-blocks; plain global atomics get *cheaper* as more cells spread the -contention. Measured on A100 at N=8000, `:direct` vs naive in bapps: - -| hist bytes | Float32 | Float64 | -|---|---|---| -| 253–307 KB | 3.85 vs 3.46 → `:direct` | 3.44 vs 3.47 → wash | -| 373–389 KB | 3.52 vs 4.33 → naive | 3.41 vs 4.21 → naive | -| 461–720 KB | 2.43 vs 6.22 → naive | 1.87 vs 6.70 → naive | - -The crossover falls between 307 and 373 KB for both element types, and naive's margin grows steeply -above it. `:shared` and `:typeplane` keep the histogram on chip and are unaffected. See -`gpu/SPEED_OF_LIGHT.md`. +its cost grows with cells × tile-blocks, while plain global atomics get cheaper as more cells spread +the contention. On an A100 the two cross between 307 and 373 KiB for both element types, and this +constant is the midpoint of that band. `:shared` and `:typeplane` keep the histogram on chip and are +unaffected. """ const SP2D_GLOBAL_ATOMIC_HIST_BYTES = 340 * 1024 """ _sp2d_prefers_global_atomics(n_dist, n_val, FT, caps) -> Bool -Whether SP2D should hand this shape to the plain global-atomic kernel instead of `:direct`. +Whether SP2D hands this shape to the plain global-atomic kernel in place of `:direct`. Consulted in **two** places that must agree: where the value plan is built (`_gpu_run_single_pass_2d!`, which must produce a `GPUValueVectorCols` because that is the plan the @@ -172,9 +164,9 @@ const SP2D_COMPILE_CELL_QUANTUM = 1024 _sp2d_sharedhist_compile_cells(config) -> Int Compile-time `@localmem` histogram width. Sized to what the config actually needs, rounded up to -[`SP2D_COMPILE_CELL_QUANTUM`] so nearby configs reuse one compiled kernel instead of each forcing -its own. Reserving the whole budget instead would cost residency: a config needing 3072 cells would -hold 5371 cells of shared and drop from 5 blocks per SM to 3. +[`SP2D_COMPILE_CELL_QUANTUM`] so nearby configs reuse one compiled kernel. Reserving the whole +budget costs residency: a config needing 3072 cells then holds 5371 cells of shared and drops from +5 blocks per SM to 3. """ @inline function _sp2d_sharedhist_compile_cells(config::SP2DAccumulationStrategy) # Both branches must use the PADDED extents: the kernel indexes and bounds its loops with the diff --git a/ext/gpu/tensor.jl b/ext/gpu/tensor.jl index ca0405b..9ab6008 100644 --- a/ext/gpu/tensor.jl +++ b/ext/gpu/tensor.jl @@ -2,8 +2,8 @@ # # One thread owns an `i` and walks every `j > i`, so the pair set is the same upper triangle the CPU # kernel enumerates. The accumulation is a global atomic per tensor component: a rank-`P` tensor has -# `D^P` of them per pair, which is why this is a separate kernel rather than a mode of the scalar -# ones — there is no shared-memory histogram small enough to stage it. +# `D^P` of them per pair, and no shared-memory histogram is small enough to stage that, so this is +# its own kernel and not a mode of the scalar ones. KA.@kernel unsafe_indices = true function _tensor_kernel!( sums, counts, @Const(x_mat), @Const(u_mat), geom, dist_be, @@ -19,10 +19,11 @@ KA.@kernel unsafe_indices = true function _tensor_kernel!( ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = SFH.digitize(dist, dist_be) if ok && 1 <= bin <= N_bins + sgn = SFC._tensor_reading(Val(P), geom, frame) for b in 1:B U1 = SA.SVector{F, UT}(ntuple(d -> @inbounds(u_mat[d, i, b]), Val(F))) U2 = SA.SVector{F, UT}(ntuple(d -> @inbounds(u_mat[d, j, b]), Val(F))) - du = SFH.pair_delta(geom, frame, X1, X2, U1, U2) + du = sgn * SFH.pair_delta(geom, frame, X1, X2, U1, U2) if P == 2 for a in 1:D, c in 1:D @atomic sums[(a - 1) * D + c, bin, b] += du[a] * du[c] @@ -45,8 +46,14 @@ function SFC.gpu_calculate_structure_function_tensor!( sums::AbstractArray, counts::AbstractArray, order::Val{P}, shape::SFC.AbstractFieldShape{D}, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; - distance_metric::DI.PreMetric = DI.Euclidean(), + distance_metric::DI.PreMetric = DI.Euclidean(), axis = nothing, ) where {P, D} + axis === nothing || throw(ArgumentError( + "the joint tensor over the separation angle runs on the CPU backends", + )) + 2 <= P <= 3 || throw(ArgumentError( + "the GPU tensor kernel accumulates orders 2 and 3; order $P runs on the CPU backends", + )) s = SFC._tensor_setup(order, shape, sums, counts, x, u, distance_bins, distance_metric) s.fixed_x || throw(ArgumentError( "the GPU tensor kernel takes one shared position set; `x` varying per auxiliary slice is a " * @@ -62,9 +69,10 @@ function SFC.gpu_calculate_structure_function_tensor!( u_dev = KA.adapt(ka, reshape(collect(s.uk), F, N, B)) sums_dev = KA.adapt(ka, zeros(OT, D^P, n_bins, B)) counts_dev = KA.adapt(ka, zeros(CT, n_bins, B)) + dist_dev = KA.adapt(ka, s.dist_be) kernel = _tensor_kernel!(ka, 256) - kernel(sums_dev, counts_dev, x_dev, u_dev, s.geom, s.dist_be, N, n_bins, B, + kernel(sums_dev, counts_dev, x_dev, u_dev, s.geom, dist_dev, N, n_bins, B, Val(W), Val(F), Val(D), order; ndrange = N) KA.synchronize(ka) diff --git a/ext/gpu/workspace.jl b/ext/gpu/workspace.jl index 47b17cb..2adaff2 100644 --- a/ext/gpu/workspace.jl +++ b/ext/gpu/workspace.jl @@ -64,7 +64,7 @@ end Workspace for 2D histograms. Routes on `kind`: - `kind=:joint2d` — single distance × value joint histogram (see [`joint2d_smem_max`](@ref)) -- `kind=:single_pass_2d` — six-invariant-type single-pass 2D (see [`gpu/SP2D_HTP_EJ.md`](../gpu/SP2D_HTP_EJ.md)) +- `kind=:single_pass_2d` — six-invariant-type single-pass 2D Typed `AbstractBinEdges` distance bins (`LogBinEdges`, etc.) subtype `AbstractVector`; routing on `kind` avoids constructor ambiguity between joint and SP2D paths. diff --git a/gpu/Project.toml b/gpu/Project.toml index 9042268..436b651 100644 --- a/gpu/Project.toml +++ b/gpu/Project.toml @@ -1,10 +1,15 @@ [deps] +AbstractFFTs = "621f4979-c628-5d54-868e-fcf4e3e8185c" +FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" +SpectralBackends = "289ded02-b044-41b2-8b2d-71f2a47755d1" ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" +FINUFFT = "d8beea63-0952-562e-9c6a-8e8ef7364055" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +NonuniformFFTs = "cd96f58b-6017-4a02-bb9e-f4d81626177f" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" @@ -14,9 +19,12 @@ Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" [sources] StructureFunctions = { path = ".." } +SpectralBackends = { url = "https://github.com/jbphyswx/SpectralBackends.jl" } [compat] +FINUFFT = "3.5" KernelAbstractions = "0.9" +NonuniformFFTs = "0.9" OhMyThreads = "0.8" StaticArrays = "1.9" julia = "1.12" diff --git a/gpu/bench_1d_old_vs_nbody.jl b/gpu/bench_1d_old_vs_nbody.jl index 5d0f0d7..8bc47a2 100644 --- a/gpu/bench_1d_old_vs_nbody.jl +++ b/gpu/bench_1d_old_vs_nbody.jl @@ -1,14 +1,12 @@ # ============================================================================= -# Head-to-head for the ONE 1D regime where the routing choice is still live: -# fixed-x individual SF, where the warp-replica strip kernel beats the CUDA -# N-body kernel (tiny-histogram, contention-bound). Verifies equal histograms. +# Head-to-head for the one 1D regime where the routing choice is live: fixed-x +# individual SF, where the warp-replica strip kernel beats the CUDA N-body +# kernel, the histogram being small enough to be contention-bound. Checks that +# the two fill equal histograms. # julia --project=gpu gpu/bench_1d_old_vs_nbody.jl # -# The other regimes were measured head-to-head and are no longer a choice — the -# losing launchers were unreachable from production and have been deleted: -# ind varying 61 vs 115 bapps, SP1D fixed 30 vs 43, SP1D varying 28 vs 43, -# SP2D fixed 5 vs 25, SP2D varying 1 vs 25 (all: N-body/unified wins). -# See gpu/OPTIMAL_KERNEL_DESIGN.md. +# Every other 1D and 2D regime takes the N-body or unified kernel, so it has one +# launcher and nothing to compare. # ============================================================================= using StructureFunctions import KernelAbstractions as KA diff --git a/gpu/benchmark_2d_grid_scaling.jl b/gpu/benchmark_2d_grid_scaling.jl index b7166fa..c13f9f8 100644 --- a/gpu/benchmark_2d_grid_scaling.jl +++ b/gpu/benchmark_2d_grid_scaling.jl @@ -15,8 +15,6 @@ Compare single-type joint 2D vs six-type single-pass 2D on GPU. Gate: e2e SP2D < `6 × joint_2d`. Logs `output=on-chip-flush` vs `partition+merge`. -Full design: `gpu/SP2D_HTP_EJ.md` - Run on GPU: julia --project=gpu gpu/benchmark_2d_grid_scaling.jl @@ -33,7 +31,7 @@ using Random: Random using StructureFunctions: StructureFunctions as SF using StructureFunctions.Calculations: Calculations as SFC using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges -using StructureFunctions: joint2d_smem_max +using StructureFunctions.Calculations: joint2d_smem_max using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT function _bench(f, warmup::Int, repeat_::Int) diff --git a/gpu/benchmark_joint2d_diagnose.jl b/gpu/benchmark_joint2d_diagnose.jl index ccc72ec..d65d7bc 100644 --- a/gpu/benchmark_joint2d_diagnose.jl +++ b/gpu/benchmark_joint2d_diagnose.jl @@ -17,7 +17,8 @@ using Random: Random using Statistics: Statistics using StructureFunctions: StructureFunctions as SF using StructureFunctions.Calculations: Calculations as SFC -using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges, joint2d_smem_max +using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges +using StructureFunctions.Calculations: joint2d_smem_max using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) diff --git a/gpu/benchmark_scaling_helpers.jl b/gpu/benchmark_scaling_helpers.jl index fbe4da7..269e3a0 100644 --- a/gpu/benchmark_scaling_helpers.jl +++ b/gpu/benchmark_scaling_helpers.jl @@ -9,6 +9,7 @@ Expects `CUDA` to be loaded by the including script when using `CUDA.CUDABackend using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: Calculations as SFC +using StructureFunctions: StructureFunctionSumsAndCounts using Statistics: Statistics """ @@ -151,6 +152,7 @@ function bench_cpu_serial_slice_loop!(x_batch, u_batch, bins, sft, sums, counts; res = SFC.calculate_structure_function( sft, @view(x_batch[:, :, t]), @view(u_batch[:, :, t]), bins; backend = CB.SerialBackend(), verbose = false, show_progress = false, + output_type = StructureFunctionSumsAndCounts, ) sums[:, t] .= res.sums counts[:, t] .= res.counts diff --git a/gpu/profile_joint2d_ncu.jl b/gpu/profile_joint2d_ncu.jl index e74b42f..aacfa37 100644 --- a/gpu/profile_joint2d_ncu.jl +++ b/gpu/profile_joint2d_ncu.jl @@ -22,7 +22,8 @@ using Printf: Printf using Random: Random using StructureFunctions: StructureFunctions as SF using StructureFunctions.Calculations: Calculations as SFC -using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges, joint2d_smem_max +using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges +using StructureFunctions.Calculations: joint2d_smem_max using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) diff --git a/gpu/run_cuda_gridded_parity.sh b/gpu/run_cuda_gridded_parity.sh new file mode 100644 index 0000000..0e2e348 --- /dev/null +++ b/gpu/run_cuda_gridded_parity.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#SBATCH --job-name=sf_cuda_gridded +#SBATCH --output=gpu/benchmark_results/cuda_gridded_parity_%j.out +#SBATCH --error=gpu/benchmark_results/cuda_gridded_parity_%j.out +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=00:30:00 +set -euo pipefail +cd "${SLURM_SUBMIT_DIR:-$(pwd)}"; mkdir -p gpu/benchmark_results +echo "host=$(hostname) job=${SLURM_JOB_ID:-local}"; nvidia-smi --query-gpu=name --format=csv,noheader | head -1 || true +"${JULIA:-julia}" --project=gpu -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()' +"${JULIA:-julia}" -t 8 --project=gpu gpu/test_cuda_gridded_parity.jl diff --git a/gpu/runtests.jl b/gpu/runtests.jl index 0f2ec18..fbec4f7 100644 --- a/gpu/runtests.jl +++ b/gpu/runtests.jl @@ -7,6 +7,9 @@ functional CUDA device is present. Run from the repository root (GPU allocation / SLURM): julia --project=gpu gpu/runtests.jl + +The testset files run in this process; the script-style parity files each run in their own +process, so their top-level constants never collide, and pass when they exit cleanly. """ using CUDA: CUDA @@ -19,9 +22,26 @@ end println("CUDA device: ", CUDA.name(CUDA.device())) +const GPU_DIR = @__DIR__ +const SCRIPT_SUITES = ( + "test_cuda_1d_parity.jl", + "test_cuda_2d_parity.jl", + "test_e2e_2d_cuda.jl", + "test_slices_e2e.jl", + "test_cuda_gridded_parity.jl", +) + Test.@testset "StructureFunctions GPU" begin include("test_cuda_parity.jl") include("test_workspace_cuda.jl") + Test.@testset "script suites" begin + for file in SCRIPT_SUITES + cmd = `$(Base.julia_cmd()) --project=$(GPU_DIR) --threads=$(Threads.nthreads()) $(joinpath(GPU_DIR, file))` + Test.@testset "$file" begin + Test.@test success(pipeline(cmd; stdout, stderr)) + end + end + end end println("GPU tests passed.") diff --git a/gpu/test_cuda_1d_parity.jl b/gpu/test_cuda_1d_parity.jl index da8a3b9..0115f94 100644 --- a/gpu/test_cuda_1d_parity.jl +++ b/gpu/test_cuda_1d_parity.jl @@ -9,6 +9,7 @@ using StructureFunctions import KernelAbstractions as KA using CUDA, StaticArrays, Printf using Statistics: median +using Random: Random const SF = StructureFunctions const SFC = SF.Calculations const GE = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) @@ -36,6 +37,9 @@ end println("CUDA 1D fast-kernel parity vs KA.CPU() — N=$N B=$B D=$D\n") println("| NMOM | fixed_x | NB | handled | max relΔ | max |Δcount| |") for NMOM in (1, 6), fixed_x in (true, false), NB in (16, 50, 128) + # A fixed draw per case: the two devices round Float32 differently, so a separation within an ulp of + # a bin edge can land either side of it, and which pairs do is a property of the draw. + Random.seed!(20260916 + 1000 * NMOM + 100 * Int(fixed_x) + NB) x_h = fixed_x ? rand(FT, D, N) : rand(FT, D, N, B) u_h = randn(FT, D, N, B) dist_bins = collect(FT, range(0.05f0, 2.0f0, length = NB + 1)) @@ -51,6 +55,7 @@ end # ---- timing: SP1D NB=50 & individual NB=50, fixed-x, real N=20000 ---- println("\n--- timing 1D fixed-x N=20000 (kernel, extrapolate to B=8064) ---") let Nt = 20000, Bt = 64, NB = 50 + Random.seed!(20260916) x_h = rand(FT, D, Nt); u_h = randn(FT, D, Nt, Bt) dist_bins = collect(FT, range(0.05f0, 2.0f0, length = NB + 1)) dig = GE._sf_batch_dist_digitizer(CUDA.CUDABackend(), dist_bins) @@ -70,6 +75,7 @@ end println("\n--- joint2d-varying CUDA vs KA-CPU count diff (expect few pairs) ---") let Nj = 3000, Bj = 6, nd = 20, nv = 20 for seed_shift in (0.0f0, 0.137f0) + Random.seed!(20260916) x_h = rand(FT, D, Nj, Bj) .+ seed_shift; u_h = randn(FT, D, Nj, Bj) db = collect(FT, range(0.05f0, 2.0f0, length = nd + 1)) vb = collect(FT, range(-5f0, 5f0, length = nv + 1)) diff --git a/gpu/test_cuda_2d_parity.jl b/gpu/test_cuda_2d_parity.jl index 01c8ce0..b3098ba 100644 --- a/gpu/test_cuda_2d_parity.jl +++ b/gpu/test_cuda_2d_parity.jl @@ -9,6 +9,7 @@ using StructureFunctions import KernelAbstractions as KA using CUDA, StaticArrays, Printf using Statistics: median +using Random: Random const SF = StructureFunctions const SFC = SF.Calculations const GE = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) @@ -41,10 +42,13 @@ function cuda_2d(xd, ud, ddig, vplan, N, n_dist, n_val, B, NMOM, fixed_x) end println("CUDA 2D fast-kernel parity vs KA.CPU() reference — N=$N B=$B D=$D\n") -println("| NMOM | fixed_x | bins | handled | max relΔ sums | counts exact | TILE-fit |") +println("| NMOM | fixed_x | bins | handled | max relΔ sums | pairs in a different value bin | TILE-fit |") for NMOM in (1, 6) for fixed_x in (true, false) for (n_dist, n_val) in ((16, 8), (20, 20), (50, 50)) + # A fixed draw per case, so a row is reproducible and a change in it is attributable to the + # code. The criterion below is a bound that holds for any draw. + Random.seed!(20260916 + 1000 * NMOM + 100 * Int(fixed_x) + n_dist + n_val) x_h = fixed_x ? rand(FT, D, N) : rand(FT, D, N, B) u_h = randn(FT, D, N, B) dist_bins = collect(FT, range(0.05f0, 2.0f0, length = n_dist + 1)) @@ -60,9 +64,14 @@ for NMOM in (1, 6) o_cu, c_cu, handled = cuda_2d(xd, ud, ddig, vplan, N, n_dist, n_val, B, NMOM, fixed_x) oc = Array(o_cu); cc = Array(c_cu) rel = maximum(abs.(oc .- o_ref) ./ max.(abs.(o_ref), 1f-3)) - cexact = cc == c_ref - @printf("| %d | %s | %dx%d | %s | %.2e | %s | %s |\n", - NMOM, fixed_x, n_dist, n_val, handled, rel, cexact, handled) + # A pair is placed by its value, and in Float32 a value within an ulp of a value-bin edge + # digitizes differently under the two devices' rounding, so one bin's count is not an invariant + # of the pair set. The invariant is that every pair is placed: the measure is the misplaced + # share of the total. + moved = sum(abs.(Int.(cc) .- Int.(c_ref))) ÷ 2 + total = sum(Int.(c_ref)) ÷ max(NMOM, 1) + @printf("| %d | %s | %dx%d | %s | %.2e | %d / %d = %.1e | %s |\n", + NMOM, fixed_x, n_dist, n_val, handled, rel, moved, total, moved / max(total, 1), handled) end end end diff --git a/gpu/test_cuda_gridded_parity.jl b/gpu/test_cuda_gridded_parity.jl new file mode 100644 index 0000000..7a4d7c3 --- /dev/null +++ b/gpu/test_cuda_gridded_parity.jl @@ -0,0 +1,185 @@ +# ============================================================================= +# Parity and timing of the transform engine on CUDA against the CPU engine: uniform, rectilinear and +# zonal schedules, masked and complete, second and third order. Counts must be exact, sums to +# round-off. Both engines run inside the same job, so the timings are comparable. +# julia --project=gpu gpu/test_cuda_gridded_parity.jl +# ============================================================================= +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + HelperFunctions as SFH +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using SpectralBackends: SpectralBackends as SB +using KernelAbstractions: KernelAbstractions as KA +using StaticArrays: StaticArrays as SA +using CUDA: CUDA +using FFTW: FFTW +using OhMyThreads: OhMyThreads +using NonuniformFFTs: NonuniformFFTs +using FINUFFT: FINUFFT +using Distances: Distances +using Printf: Printf +using Random: Random + +const FFT = SB.FastFourierTransformSpectralBackend() +const GPU = CB.GPUBackend(CUDA.CUDABackend()) +const CPU = Threads.nthreads() > 1 ? CB.ThreadedBackend() : CB.SerialBackend() + +println("device: ", CUDA.name(CUDA.device()), " host threads: ", Threads.nthreads()) +println("| case | operator | max |Δcount| (relative when weighted) | max |Δsum|/scale | cpu s | gpu s |") + +failures = Ref(0) +function compare(name, sf, u, s, edges, D; valid = SFC.AllValid(), weights = nothing) + nb = length(edges) - 1 + CT = weights === nothing ? Int : Float64 + a, ca = zeros(nb), zeros(CT, nb) + b, cb = zeros(nb), zeros(CT, nb) + SFC.gridded_sweep!(a, ca, sf, u, s, edges, Val(D), FFT; valid, weights, backend = CPU) + SFC.gridded_sweep!(b, cb, sf, u, s, edges, Val(D), FFT; valid, weights, backend = GPU) + fill!(a, 0); fill!(ca, 0); fill!(b, 0); fill!(cb, 0) + tc = @elapsed SFC.gridded_sweep!(a, ca, sf, u, s, edges, Val(D), FFT; valid, weights, backend = CPU) + tg = @elapsed (SFC.gridded_sweep!(b, cb, sf, u, s, edges, Val(D), FFT; valid, weights, backend = GPU); CUDA.synchronize()) + dc = maximum(abs.(ca .- cb)) / (CT <: Integer ? 1 : max(maximum(abs, ca), 1e-12)) + ds = maximum(abs.(a .- b)) / max(maximum(abs, a), 1e-12) + Printf.@printf("| %s | %s | %.1e | %.1e | %.3f | %.3f |\n", name, nameof(typeof(sf)), dc, ds, tc, tg) + (dc <= (CT <: Integer ? 0 : 1e-12) && ds <= 1e-10) || (failures[] += 1) + return nothing +end + +Random.seed!(1) +let dims = (256, 256) + s = SFC.UniformLagSchedule(dims, (1.0, 1.0), (true, true)) + u = randn(2, dims...) + edges = collect(range(0.0, 120.0; length = 41)) + compare("uniform 256² periodic", SFT.L2SFType(), u, s, edges, 2) + compare("uniform 256² periodic", SFT.L3SFType(), u, s, edges, 2) + compare("uniform 256² periodic", SFT.T3SFType(), u, s, edges, 2) + um = copy(u) + umf = reshape(um, 2, :) + umf[:, rand(size(umf, 2)) .< 0.25] .= NaN + valid = SFC.field_validity(um) + compare("uniform 256² masked", SFT.L2SFType(), um, s, edges, 2; valid) + compare("uniform 256² masked, weighted", SFT.L3SFType(), um, s, edges, 2; valid, weights = 0.5 .+ rand(prod(dims))) + sb = SFC.UniformLagSchedule(dims, (1.0, 1.0), (false, false)) + compare("uniform 256² bounded", SFT.S3SFType(), u, sb, edges, 2) +end + +let dims = (48, 48, 40) + s = SFC.UniformLagSchedule(dims, (1.0, 1.0, 1.0), (true, true, false)) + u = randn(3, dims...) + compare("uniform 48×48×40", SFT.L2SFType(), u, s, collect(range(0.0, 30.0; length = 31)), 3) + compare("uniform 48×48×40", SFT.T3SFType(), u, s, collect(range(0.0, 30.0; length = 31)), 3) + about_a = SFH.ReferenceAxisTransverseBasis(SA.SVector(1.0, sqrt(2.0), sqrt(3.0))) + compare("uniform 48×48×40 axis", SFT.ProjectedStructureFunctionType{0, 3}(about_a), u, s, + collect(range(0.0, 30.0; length = 31)), 3) +end + +let coords = cumsum(0.8 .+ 0.4 .* rand(128)) + s = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((256,), (1.0,), (true,)), (coords,), (1, 2)) + u = randn(2, 256, 128) + compare("rectilinear 256×128", SFT.L2SFType(), u, s, collect(range(0.0, 60.0; length = 31)), 2) +end + +let n_lon = 720, n_lat = 360 + lats = collect(range(-π / 2 + π / (2n_lat), π / 2 - π / (2n_lat); length = n_lat)) + s = SFC.ZonalLagSchedule(lats, n_lon, 2π / n_lon, 1.0, true) + u = randn(2, n_lon, n_lat) + # edges off the lattice's own separations: on the sphere the device's transcendentals round differently + # from the host's, so a pair exactly on an edge may change bins + edges = collect(range(0.0, π; length = 65)) .+ 1e-3 + compare("zonal 720×360", SFT.L2SFType(), u, s, edges, 2) + compare("zonal 720×360 weighted", SFT.L2SFType(), u, s, edges, 2; weights = 0.5 .+ rand(n_lon * n_lat)) + f = Fields(vectors = (u,), scalars = (randn(n_lon, n_lat),)) + nb = length(edges) - 1 + a, ca = zeros(nb), zeros(Int, nb) + b, cb = zeros(nb), zeros(Int, nb) + SFC.gridded_sweep!(a, ca, SFT.MixedSFType{1, 0, 2}(), f, s, edges, FFT; backend = CPU) + SFC.gridded_sweep!(b, cb, SFT.MixedSFType{1, 0, 2}(), f, s, edges, FFT; backend = GPU) + dc = maximum(abs.(ca .- cb)) + ds = maximum(abs.(a .- b)) / maximum(abs, a) + Printf.@printf("| %s | %s | %d | %.1e | - | - |\n", "zonal 720×360 multi-field", "Mixed{1,0,2}", dc, ds) + (dc == 0 && ds <= 1e-10) || (failures[] += 1) +end + +# The non-uniform FFT route: the same engine on scattered points, its forward transforms from each provider on +# the device the field lives on (cuFINUFFT for FINUFFT); counts are a kernel-weighted mass, compared relatively. +# The two providers are also held to each other on the host. +let N = 20_000 + x = rand(2, N) .* (100.0, 60.0) + u = randn(2, N) + s = SFC.ScatteredModesSchedule(x, 30.0, (256, 192); taper = SF.GaussianTaper(0.3)) + edges = collect(range(0.0, 30.0; length = 31)) + nb = length(edges) - 1 + providers = (SFC.NonuniformFFTsSpectralBackend(), SFC.FINUFFTSpectralBackend()) + for sf in (SFT.L2SFType(), SFT.S3SFType()) + host = map(providers) do tag + a, ca = zeros(nb), zeros(nb) + b, cb = zeros(nb), zeros(nb) + SFC.gridded_sweep!(a, ca, sf, u, s, edges, Val(2), tag; backend = CPU) + SFC.gridded_sweep!(b, cb, sf, u, s, edges, Val(2), tag; backend = GPU) + fill!(a, 0); fill!(ca, 0); fill!(b, 0); fill!(cb, 0) + tc = @elapsed SFC.gridded_sweep!(a, ca, sf, u, s, edges, Val(2), tag; backend = CPU) + tg = @elapsed (SFC.gridded_sweep!(b, cb, sf, u, s, edges, Val(2), tag; backend = GPU); CUDA.synchronize()) + dc = maximum(abs.(ca .- cb)) / maximum(abs, ca) + ds = maximum(abs.(a .- b)) / maximum(abs, a) + Printf.@printf("| %s (%s) | %s | %.1e | %.1e | %.3f | %.3f |\n", "scattered 20k → 256×192 modes", + nameof(typeof(tag)), nameof(typeof(sf)), dc, ds, tc, tg) + (dc <= 1e-10 && ds <= 1e-9) || (failures[] += 1) + (a, ca) + end + dc = maximum(abs.(host[1][2] .- host[2][2])) / maximum(abs, host[1][2]) + ds = maximum(abs.(host[1][1] .- host[2][1])) / maximum(abs, host[1][1]) + Printf.@printf("| %s | %s | %.1e | %.1e | - | - |\n", "scattered: NonuniformFFTs vs FINUFFT on the host", + nameof(typeof(sf)), dc, ds) + (dc <= 1e-10 && ds <= 1e-9) || (failures[] += 1) + end +end + +# The tensor kernel: every component of the rank-P moment tensor, an odd rank taking the canonical pair +# reading in a fixed frame and none in the sphere's geodesic frame, against the serial point tensor and +# against the transform tensor on a grid. +let N = 3000 + RAW = SF.StructureFunctionTensorSumsAndCounts + function tensor_compare(name, P, x, u, edges; distance_metric = Distances.Euclidean()) + ref = SFC.calculate_structure_function_tensor(Val(P), x, u, edges; backend = CB.SerialBackend(), + distance_metric, output_type = RAW) + got = SFC.calculate_structure_function_tensor(Val(P), x, u, edges; backend = GPU, + distance_metric, output_type = RAW) + CUDA.synchronize() + dc = maximum(abs.(Int.(ref.counts) .- Int.(got.counts))) + ds = maximum(abs.(ref.sums .- got.sums)) / maximum(abs, ref.sums) + Printf.@printf("| %s | tensor P=%d | %d | %.1e | - | - |\n", name, P, dc, ds) + (dc == 0 && ds <= 1e-10) || (failures[] += 1) + return nothing + end + x = rand(2, N) .* 10.0 + u = randn(2, N) + edges = collect(range(0.0, 5.0; length = 21)) .+ 1e-3 + tensor_compare("points 3000 flat", 2, x, u, edges) + tensor_compare("points 3000 flat", 3, x, u, edges) + lam = rand(N) .* 2π + phi = asin.(2 .* rand(N) .- 1) + xs = Matrix(hcat(lam, phi)') + us = randn(2, N) + tensor_compare("points 3000 sphere", 3, xs, us, collect(range(0.0, π; length = 17)) .+ 1e-3; + distance_metric = SFH.SphericalDistance(1.0)) + dims, spacing = (64, 48), (0.5, 0.25) + ug = randn(2, dims...) + xg = Matrix(hcat([[(i - 1) * spacing[1], (j - 1) * spacing[2]] for i in 1:dims[1], j in 1:dims[2]]...)) + gedges = collect(range(0.0, 8.0; length = 17)) .+ 1e-3 + sched = SFC.UniformLagSchedule(dims, spacing, (false, false)) + for P in (2, 3) + tsums = zeros(ntuple(_ -> 2, P)..., length(gedges) - 1) + tcounts = zeros(Int, length(gedges) - 1) + SFC.gridded_tensor_sweep!(tsums, tcounts, Val(P), reshape(ug, 2, :), sched, gedges, Val(2), FFT; backend = CPU) + got = SFC.calculate_structure_function_tensor(Val(P), xg, reshape(ug, 2, :), gedges; backend = GPU, + output_type = RAW) + CUDA.synchronize() + dc = maximum(abs.(tcounts .- Int.(got.counts))) + ds = maximum(abs.(tsums .- got.sums)) / maximum(abs, tsums) + Printf.@printf("| %s | transform vs gpu tensor P=%d | %d | %.1e | - | - |\n", "grid 64×48", P, dc, ds) + (dc == 0 && ds <= 1e-9) || (failures[] += 1) + end +end + +println(failures[] == 0 ? "PARITY OK" : "PARITY FAILED in $(failures[]) case(s)") +exit(failures[] == 0 ? 0 : 1) diff --git a/src/BinEdges.jl b/src/BinEdges.jl index d46a551..c37b5be 100644 --- a/src/BinEdges.jl +++ b/src/BinEdges.jl @@ -6,19 +6,18 @@ Supertype for all custom, high-performance bin edge collections in `StructureFunctions.jl`. ### Why AbstractBinEdges Exists -In structure function calculations over large datasets, the spatial separation distance \$r\$ for each of -the \$O(N^2)\$ point pairs must be mapped to its corresponding distance bin (index). Using a standard sorted -vector of bin edges requires a binary search (`searchsortedfirst`), which has \$O(\\log B)\$ complexity -where \$B\$ is the number of bins. - -For large \$N\$, this binary search becomes the dominant CPU bottleneck, causing high branch mispredictions and -cache misses. Subtypes of `AbstractBinEdges` bypass the standard binary search by implementing custom -`Base.searchsortedfirst` overrides that execute in \$O(1)\$ time: +In structure function calculations over large datasets, the spatial separation distance ``r`` for each of +the ``O(N^2)`` point pairs must be mapped to its corresponding distance bin (index). Using a standard sorted +vector of bin edges requires a binary search (`searchsortedfirst`), which has ``O(\\log B)`` complexity +where ``B`` is the number of bins. + +For large ``N``, this binary search becomes the dominant CPU bottleneck, causing high branch mispredictions and +cache misses. Subtypes of `AbstractBinEdges` bypass the standard binary search by implementing custom +`Base.searchsortedfirst` overrides that execute in ``O(1)`` time: - `LinearBinEdges` utilizes Fused Multiply-Add (FMA) arithmetic for uniformly-spaced bins. - `LogBinEdges` maps physical queries via `log(q)` then the same FMA path on the log-space grid. -Wrapping standard arrays in these subtypes allows `digitize` to execute 5x to 15x faster, resolving the -primary computational bottleneck in the package. +Wrapping standard arrays in these subtypes makes `digitize` a constant-time lookup. ## Bin edges and backends @@ -44,7 +43,7 @@ Bypasses range-specific optimizations but conforms to the `AbstractBinEdges` int ### Behavior - If constructed with an `AbstractRange` (e.g. `StepRange` or `StepRangeLen`), it automatically promotes and returns a `LinearBinEdges` wrapper to enable O(1) FMA indexing. -- Otherwise, it wraps the vector and delegates to standard \$O(\\log N)\$ binary search methods. +- Otherwise, it wraps the vector and delegates to standard ``O(\\log N)`` binary search methods. """ struct BinEdges{T, ET <: AbstractVector{T}} <: AbstractBinEdges{T} edges::ET @@ -70,13 +69,13 @@ Base.getindex(v::BinEdges, i::Int) = v.edges[i] High-performance wrapper for uniformly-spaced ranges (linear spacing). ### Mathematical Theory -A standard binary search takes \$O(\\log B)\$ steps. With a uniformly spaced range of bin edges \$v_i = v_1 + (i-1)\\delta\$, -`searchsortedfirst(v, x)` is the smallest index \$i\$ with \$v_i \\ge x\$: -\$\$ +A standard binary search takes ``O(\\log B)`` steps. With a uniformly spaced range of bin edges ``v_i = v_1 + (i-1)\\delta``, +`searchsortedfirst(v, x)` is the smallest index ``i`` with ``v_i \\ge x``: +```math i^*(x) = \\min\\{ i : v_1 + (i-1)\\delta \\ge x \\} = \\left\\lfloor \\frac{x - v_1}{\\delta} \\right\\rfloor + 1 = \\lceil \\frac{x - v_1}{\\delta} + 1 \\rceil . -\$\$ +``` The discrete operator is **ceiling / floor+1**, not `round` (which answers a different question). Precompute `inv_step = 1/δ` and at query time one FMA gives \$t = (x-v_1)/\\delta\$: @@ -88,8 +87,8 @@ Precompute `inv_step = 1/δ` and at query time one FMA gives \$t = (x-v_1)/\\del error without a second downward correction. ### Performance -Bypasses the Twice-Precision arithmetic of Julia's standard `StepRangeLen` search. -Reduces lookup time from **~46 ns** to **~3 ns** (a 15x speedup), completely eliminating the linear binning bottleneck. +Bypasses the twice-precision arithmetic of Julia's `StepRangeLen` search, so a lookup is one FMA and +one comparison. """ struct LinearBinEdges{T, RT <: AbstractRange{T}} <: AbstractBinEdges{T} edges::RT @@ -157,8 +156,8 @@ Log-spaced (geometric) bin edges: uniform grid in log-space. ### Digitize semantics `log_edges` is the authoritative grid. A physical query `q > 0` maps to -`searchsortedfirst(LinearBinEdges(log_edges), log(q))`. See -[`docs/UNIFORM_BIN_DIGITIZE.md`](@ref) and `benchmark/LOG_BIN_EDGES_BENCHMARK.md`. +`searchsortedfirst(LinearBinEdges(log_edges), log(q))`. See the documentation's "Binning Internals" +page. [`LogBinEdges`](@ref) from a physical vector builds the same log grid from `range(log(first), log(last); length)`. [`LogBinEdges_from_log_edges`](@ref) accepts @@ -166,7 +165,7 @@ the log grid directly. ### Performance -One `log(q)` (~6 ns) plus O(1) FMA digitize (~2.5 ns) on the log grid. See benchmark log. +One `log(q)` plus the constant-time FMA digitize on the log grid. """ struct LogBinEdges{T, LRT <: AbstractRange{T}, LBET <: LinearBinEdges{T}} <: AbstractBinEdges{T} log_edges::LRT @@ -255,8 +254,7 @@ an existing bin edge collection. ### Why InfPaddedBinEdges Exists Structure function distance bins are defined as half-open intervals \$(r_i, r_{i+1}]\$. When mapping a distance \$r\$ to a bin, any query value \$r < \\text{first}(edges)\$ or \$r > \\text{last}(edges)\$ is out-of-bounds. -Instead of checking for these out-of-bound cases manually using branches in inner loops, `InfPaddedBinEdges` -embeds the infinite endpoints implicitly: +`InfPaddedBinEdges` embeds the infinite endpoints, so an inner loop needs no out-of-bounds branch: - The first element is treated as `typemin(T)` (\$-\\infty\$). - The last element is treated as `typemax(T)` (\$+\\infty\$). @@ -344,6 +342,30 @@ end @inline Base.searchsorted(v::InfPaddedBinEdges, x) = searchsortedfirst(v, x):searchsortedlast(v, x) @inline Base.searchsorted(v::InfPaddedBinEdges, x, o::Base.Order.Ordering) = searchsortedfirst(v, x, o):searchsortedlast(v, x, o) +""" + ModeBinEdges(edges, schedule) + +Distance bins applied to the lags of a mode grid. The edges are ordinary bin edges, but every pair +reaches them through the periodic kernel of the mode set `schedule` describes, so a bin's sum and +count are kernel-weighted and the histogram is soft-binned. Carried by the results of the +non-uniform FFT route, so they cannot be mistaken for pair counts. +""" +struct ModeBinEdges{T, ET <: AbstractBinEdges{T}, S} <: AbstractBinEdges{T} + edges::ET + schedule::S +end + +ModeBinEdges(edges::AbstractVector, schedule) = ModeBinEdges(BinEdges(edges), schedule) + +Base.size(v::ModeBinEdges) = size(v.edges) +Base.getindex(v::ModeBinEdges, i::Int) = v.edges[i] +@inline Base.searchsortedfirst(v::ModeBinEdges, x) = searchsortedfirst(v.edges, x) +@inline Base.searchsortedfirst(v::ModeBinEdges, x, o::Base.Order.Ordering) = searchsortedfirst(v.edges, x, o) +@inline Base.searchsortedlast(v::ModeBinEdges, x) = searchsortedlast(v.edges, x) +@inline Base.searchsortedlast(v::ModeBinEdges, x, o::Base.Order.Ordering) = searchsortedlast(v.edges, x, o) +@inline Base.searchsorted(v::ModeBinEdges, x) = searchsorted(v.edges, x) +@inline Base.searchsorted(v::ModeBinEdges, x, o::Base.Order.Ordering) = searchsorted(v.edges, x, o) + """ midpoints(edges) -> per-bin representative separations midpoints!(out, edges) -> out @@ -405,6 +427,8 @@ midpoints(::InfPaddedBinEdges) = throw( ), ) +midpoints(v::ModeBinEdges) = midpoints(v.edges) + @@ -434,8 +458,8 @@ BinEdges(edges::AbstractRange) = LinearBinEdges(edges) _fast_log2(x) `log2(x)` for finite `x > 0`, max error ~4e-8 (Float64). Exponent extract plus an odd series on a -mantissa recentred to `[1/√2, √2)`; vectorizes, unlike the scalar `libm log`. Approximate — the bin -is decided by [`squared_digitize`](@ref)'s correction, not by this. +mantissa recentred to `[1/√2, √2)`, so it vectorizes where the scalar `libm log` does not. +Approximate: the bin is decided by [`squared_digitize`](@ref)'s correction. """ @inline function _fast_log2(x::Float64) ix = reinterpret(UInt64, x) @@ -530,6 +554,8 @@ end # the generic binary-search plan. squared_digitize_plan(v::InfPaddedBinEdges) = SquaredInfPaddedPlan(squared_digitize_plan(v.edges)) +squared_digitize_plan(v::ModeBinEdges) = squared_digitize_plan(v.edges) + squared_digitize_plan(edges::AbstractVector) = squared_digitize_plan(BinEdges(edges)) """Bins covered by the plan (`digitize` results in `1:n_bins` are in range).""" @@ -586,8 +612,8 @@ the precomputed approximate index and this only corrects it; otherwise `i` is ig """ squared_correct(plan, r2, i) -> Int -Walk `i` to the exact `searchsortedfirst(sqedges, r²)`. 0 or 1 step for random separations; a loop -rather than a fixed step because within a few ulps of an edge more can be needed. +Walk `i` to the exact `searchsortedfirst(sqedges, r²)`. 0 or 1 step for a random separation; within a +few ulps of an edge it can take more, so it loops. """ @inline function squared_correct(p::AbstractSquaredDigitizePlan, r2, i::Integer) sq = p.sqedges @@ -608,7 +634,7 @@ end squared_digitize(plan, r2) -> Int Exact `digitize(r, edges)` computed from `r²` alone. Out-of-range gives `0` (below) or `n_bins + 1` -(above), matching [`digitize`](@ref). +(above), matching [`HelperFunctions.digitize`](@ref). """ @inline squared_digitize(p::AbstractSquaredDigitizePlan, r2) = squared_bin(p, digitize_key(p, r2), squared_approx_index(p, r2)) @@ -621,3 +647,139 @@ Exact `digitize(r, edges)` computed from `r²` alone. Out-of-range gives `0` (be return squared_correct(inner, r2, i) + 1 end + +# ========================================================================================= # +# 6. Tapers and the harmonic nodes of a kernel-binned statistic +# ========================================================================================= # + +""" + AbstractTaper + +A weight applied before a transform: on a lag-space autocovariance, as a function of the lag's +length; on a spherical harmonic series, as a function of the degree. `NoTaper()` leaves every term as +it is, `Bartlett()` falls linearly to zero at the largest lag or degree, `GaussianTaper(σ)` weights a +lag of length `r` by `exp(-r²/2σ²)` and a degree `l` by `exp(-l(l+1)σ²/2)`, with `σ` in the lag's or +the sphere's own unit. A taper trades resolution for variance, or a hard bin for a positive kernel. +""" +abstract type AbstractTaper end + +"""The taper that leaves every term as it is; see [`AbstractTaper`](@ref).""" +struct NoTaper <: AbstractTaper end + +"""The taper falling linearly to zero at the largest lag or degree; see [`AbstractTaper`](@ref).""" +struct Bartlett <: AbstractTaper end + +""" + GaussianTaper(σ) + +The Gaussian taper `exp(-r²/2σ²)` on a lag of length `r`, `exp(-l(l+1)σ²/2)` on a degree `l`, or +`exp(-k²σ²/2)` on a mode of wavenumber `k`, with `σ` a length; see [`AbstractTaper`](@ref). +""" +struct GaussianTaper{T <: Real} <: AbstractTaper + σ::T +end + +"""Weight of a lag of length `r` when the largest lag has length `r_max`.""" +@inline taper_weight(::NoTaper, r, r_max) = one(r) +@inline taper_weight(::Bartlett, r, r_max) = max(zero(r), one(r) - r / r_max) +@inline taper_weight(t::GaussianTaper, r, r_max) = exp(-r * r / (2 * t.σ * t.σ)) + +"""Weight of degree `l` in a series truncated at `lmax`.""" +@inline harmonic_taper(::NoTaper, l::Integer, lmax::Integer) = 1.0 +@inline harmonic_taper(::Bartlett, l::Integer, lmax::Integer) = max(0.0, 1.0 - l / (lmax + 1)) +@inline harmonic_taper(t::GaussianTaper, l::Integer, lmax::Integer) = exp(-l * (l + 1) * t.σ^2 / 2) + +""" +Weight of a Fourier mode of squared angular wavenumber `k2`, `σ` a length: the mode set's periodic +kernel becomes the inverse transform of the squared weights. +""" +@inline mode_taper(::NoTaper, k2) = one(k2) +@inline mode_taper(t::GaussianTaper, k2) = exp(-k2 * t.σ^2 / 2) + +""" + HarmonicNodes(separations, lmax; taper = NoTaper()) + HarmonicNodes(n::Integer, lmax; taper = NoTaper()) + +The "bins" of a kernel-binned pair statistic on a sphere: the central angles `separations` (radians) +at which it is reported, the degree `lmax` its harmonic series is truncated at, and the `taper` on +that series. Together they are the kernel, `K(γ, β) = (1/16π²) Σ_{l ≤ lmax} (2l+1) b_l d^l(cos γ) d^l(cos β)`, +which replaces a hard bin around `β`; it narrows as `π/lmax` and tends to a delta in `cos γ`. + +`weights` are quadrature weights in `μ = cos β`, `∫_{-1}^{1} f dμ ≈ Σ_k w_k f(μ_k)`: Gauss–Legendre for +the `n`-node form, whose nodes are the Gauss–Legendre points of `μ`, and the midpoint rule on the +nodes' own cells for given separations. They are what inverts the statistic back to a spectrum. + +Not a vector of edges: one value is reported per node, so a result built on these has as many values +as nodes. +""" +struct HarmonicNodes{T <: Real, SV <: AbstractVector{T}, WV <: AbstractVector{T}, B <: AbstractTaper} + separations::SV + weights::WV + lmax::Int + taper::B + function HarmonicNodes(separations::AbstractVector{T}, weights::AbstractVector{T}, lmax::Integer, + taper::B) where {T <: Real, B <: AbstractTaper} + length(separations) == length(weights) || throw(DimensionMismatch( + "$(length(separations)) separations and $(length(weights)) weights", + )) + issorted(separations) || throw(ArgumentError("separations must be sorted")) + (isempty(separations) || (first(separations) >= 0 && last(separations) <= π)) || + throw(ArgumentError("separations are central angles in radians, in [0, π]")) + lmax >= 0 || throw(ArgumentError("lmax must be non-negative")) + return new{T, typeof(separations), typeof(weights), B}(separations, weights, Int(lmax), taper) + end +end + +function HarmonicNodes(separations::AbstractVector{<:Real}, lmax::Integer; taper::AbstractTaper = NoTaper()) + T = float(eltype(separations)) + sep = convert(AbstractVector{T}, separations) + μ = cos.(sep) + n = length(μ) + w = Vector{T}(undef, n) + @inbounds for k in 1:n + hi = k == 1 ? one(T) : (μ[k - 1] + μ[k]) / 2 + lo = k == n ? -one(T) : (μ[k] + μ[k + 1]) / 2 + w[k] = hi - lo + end + return HarmonicNodes(sep, w, lmax, taper) +end + +function HarmonicNodes(n::Integer, lmax::Integer; taper::AbstractTaper = NoTaper()) + μ, w = gauss_legendre(Int(n)) + return HarmonicNodes(acos.(reverse(μ)), reverse(w), lmax, taper) +end + +""" + gauss_legendre(n) -> (nodes, weights) + +The `n` Gauss–Legendre nodes on `(-1, 1)`, ascending, and their weights, by Newton's method on `P_n` +from the Tricomi estimate. +""" +function gauss_legendre(n::Integer) + n >= 1 || throw(ArgumentError("need at least one node")) + x = Vector{Float64}(undef, n) + w = Vector{Float64}(undef, n) + for k in 1:n + z = cos(π * (k - 0.25) / (n + 0.5)) + dp = 0.0 + for _ in 1:100 + p0, p1 = 1.0, z + for l in 1:(n - 1) + p0, p1 = p1, ((2l + 1) * z * p1 - l * p0) / (l + 1) + end + dp = n * (z * p1 - p0) / (z * z - 1) + dz = p1 / dp + z -= dz + abs(dz) < 1e-15 && break + end + x[n + 1 - k] = z + w[n + 1 - k] = 2 / ((1 - z * z) * dp * dp) + end + return x, w +end + +@inline midpoints(nodes::HarmonicNodes) = nodes.separations +@inline n_histogram_bins(nodes::HarmonicNodes) = length(nodes.separations) +@inline Base.length(nodes::HarmonicNodes) = length(nodes.separations) +Base.:(==)(a::HarmonicNodes, b::HarmonicNodes) = + a.separations == b.separations && a.weights == b.weights && a.lmax == b.lmax && a.taper == b.taper diff --git a/src/Calculations.jl b/src/Calculations.jl index c80a8f5..ed225d3 100644 --- a/src/Calculations.jl +++ b/src/Calculations.jl @@ -5,12 +5,15 @@ module Calculations using ProgressMeter: ProgressMeter as PM using Distances: Distances as DI +using SpectralBackends: SpectralBackends as SB using ..HelperFunctions: HelperFunctions as SFH -using ..Channels: Channels as CH +using ..MultiFields: MultiFields as MF using ..StructureFunctionTypes: StructureFunctionTypes as SFT using ..StructureFunctionObjects: StructureFunctionObjects as SFO using ..StructureFunctions: AbstractBinEdges, BinEdges, LinearBinEdges, LogBinEdges, - InfPaddedBinEdges, n_histogram_bins, midpoints, + InfPaddedBinEdges, ModeBinEdges, n_histogram_bins, midpoints, + AbstractTaper, NoTaper, Bartlett, GaussianTaper, taper_weight, harmonic_taper, mode_taper, HarmonicNodes, + gauss_legendre, AbstractSquaredDigitizePlan, squared_digitize_plan, squared_digitize, squared_approx_index, squared_correct, squared_bin, has_vector_index, digitize_key @@ -47,8 +50,13 @@ export calculate_structure_function, gpu_calculate_structure_function!, calculate_structure_function!, GPUSFWorkspace, CPUSFWorkspace, reset_histogram!, release!, joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256, - isotropic_spectrum, shell_spectrum, gridded_spectrum, shell_average, - helmholtz_spectra, spectral_flux, covariance, covariance_matrix, + isotropic_spectrum, shell_spectrum, gridded_spectrum, shell_average, cell_measure, + ScatteredModesSchedule, NonuniformFFTsSpectralBackend, FINUFFTSpectralBackend, nufft_half_support, + nufft_monomial_transforms, + helmholtz_spectra, spectral_flux, enstrophy_flux, covariance, covariance_matrix, harmonic_sweep!, harmonic_spectra, + AbstractForwardModel, SpectrumForwardModel, HelmholtzForwardModel, FluxForwardModel, forward_matrix, flux_matrix, + AbstractFitMethod, RegularizedLeastSquares, NonNegativeLeastSquares, SegmentedPowerLaw, segmented_spectrum, + fit_spectrum, fit_helmholtz_spectra, fit_flux, tradeoff_curve, select_segments, independent_pair_variance, calculate_structure_function_batch!, calculate_structure_function_2d_batch!, calculate_structure_functions_single_pass_batch!, calculate_structure_functions_single_pass_2d_batch!, @@ -62,10 +70,14 @@ include("Calculations/backends.jl") include("Calculations/shapes.jl") include("Calculations/culling.jl") include("Calculations/pair_schedule.jl") +include("Calculations/second_axis.jl") include("Calculations/gridded.jl") include("Calculations/gridded_zonal.jl") -include("Calculations/second_axis.jl") +include("Calculations/scattered_modes.jl") +include("Calculations/lag_moments.jl") +include("Calculations/sorted_line.jl") include("Calculations/transforms.jl") +include("Calculations/fits.jl") include("Calculations/batch_api.jl") include("Calculations/gpu_stubs.jl") include("Calculations/batch_leading.jl") @@ -76,6 +88,7 @@ include("Calculations/serial_2d.jl") include("Calculations/serial_single_pass.jl") include("Calculations/tensor.jl") include("Calculations/dispatch.jl") -include("Calculations/channels.jl") +include("Calculations/multifields.jl") +include("Calculations/harmonic.jl") end diff --git a/src/Calculations/backends.jl b/src/Calculations/backends.jl index 66d8ddd..866328a 100644 --- a/src/Calculations/backends.jl +++ b/src/Calculations/backends.jl @@ -29,6 +29,13 @@ function _dispatch_execution_backend( throw(ArgumentError("MPI backend is unavailable. Load MPI (`using MPI`) to enable StructureFunctionsMPIExt, or use a different backend.")) end +""" + threaded_calculate_structure_function(sf, x, u, distance_bins[, value_bins][, count_eltype]; kwargs...) + +The point-list structure function on the threaded CPU backend, returning the raw sums and counts. +Takes the arguments of [`calculate_structure_function`](@ref) without `backend`; supplied by the +OhMyThreads extension, so `using OhMyThreads` is required. +""" function threaded_calculate_structure_function(args...; kwargs...) throw( ArgumentError( @@ -37,6 +44,12 @@ function threaded_calculate_structure_function(args...; kwargs...) ) end +""" + threaded_calculate_structure_function!(sums, counts, sf, x, u, distance_bins[, value_bins]; kwargs...) + +The in-place form of [`threaded_calculate_structure_function`](@ref), accumulating into `sums` and +`counts`; supplied by the OhMyThreads extension. +""" function threaded_calculate_structure_function!(args...; kwargs...) throw( ArgumentError( @@ -45,12 +58,9 @@ function threaded_calculate_structure_function!(args...; kwargs...) ) end -# Set to `true` by the OhMyThreads extension's `__init__` when it loads. AutoBackend gates its -# threaded choice on this rather than `hasmethod`, because the throwing stub above makes -# `hasmethod` always true — which previously fooled AutoBackend into the threaded path (then it -# threw) when OhMyThreads was not loaded. With this flag, AutoBackend falls back to serial. -# A `Ref` (set at load via `__init__`) is used instead of a method override, which would be an -# illegal method-overwrite during the extension's precompilation. +# Set to `true` by the OhMyThreads extension's `__init__`. This is what `AutoBackend` tests: the +# throwing stub above makes `hasmethod` true whether or not the extension is loaded. A `Ref` set at +# load time, because overwriting a method during the extension's precompilation is illegal. const _OHMYTHREADS_LOADED = Ref(false) _ohmythreads_loaded() = _OHMYTHREADS_LOADED[] diff --git a/src/Calculations/batch.jl b/src/Calculations/batch.jl index 4c53de7..c6e6096 100644 --- a/src/Calculations/batch.jl +++ b/src/Calculations/batch.jl @@ -189,6 +189,7 @@ function _serial_calculate_structure_function_point( ::Type{CT}; distance_metric::DI.PreMetric = DI.Euclidean(), culling::CullingPolicy = AutoCulling(), + weights = nothing, verbose::Bool = true, show_progress::Bool = true, ) where {FT1, FT2, D, CT} @@ -210,6 +211,7 @@ function _serial_calculate_structure_function_point( distance_bins; geometry = geom, culling = culling, + weights = weights, verbose = verbose, show_progress = show_progress, ) @@ -242,13 +244,19 @@ function serial_calculate_structure_function( end # Point-field route: D = size(u, 1) + D == 1 && return _serial_calculate_structure_function_point( + structure_function_type, x, u, distance_bins, Val(1), count_eltype; kwargs..., + ) D == 2 && return _serial_calculate_structure_function_point( structure_function_type, x, u, distance_bins, Val(2), count_eltype; kwargs..., ) D == 3 && return _serial_calculate_structure_function_point( structure_function_type, x, u, distance_bins, Val(3), count_eltype; kwargs..., ) - return _validate_spatial_dimension(D) + _validate_spatial_dimension(D) + return _serial_calculate_structure_function_point( + structure_function_type, x, u, distance_bins, Val(D), count_eltype; kwargs..., + ) end function threaded_calculate_structure_function( diff --git a/src/Calculations/batch_api.jl b/src/Calculations/batch_api.jl index 32c10d4..ee2cf4a 100644 --- a/src/Calculations/batch_api.jl +++ b/src/Calculations/batch_api.jl @@ -98,6 +98,21 @@ end const SINGLE_PASS_N = 6 const SINGLE_PASS_WITH_HELMHOLTZ_N = 8 +""" + single_pass_invariants(δu_L, δu_norm2) -> NTuple{SINGLE_PASS_N} + +The six single-pass invariants of one pair — `(S2, L2, T2, S3, L3, L1T2)`, the stacked-row order — from the +longitudinal increment and the squared norm, which is what every geometry returns +([`HelperFunctions.pair_invariants`](@ref)). + +`S2` is the norm as measured and `S3` is `δu_L` times it, so every backend sums one expression. +""" +@inline function single_pass_invariants(du_L, du_norm2) + du_L2 = du_L * du_L + du_T2 = du_norm2 - du_L2 + return (du_norm2, du_L2, du_T2, du_L * du_norm2, du_L * du_L2, du_L * du_T2) +end + const SinglePass2DValueBins = Union{AbstractVector, Tuple{Vararg{AbstractVector, SINGLE_PASS_N}}} @inline _sp2d_value_bin_at(value_bins, t::Int) = @@ -113,8 +128,7 @@ distinct binding per invariant. `value_bins` may be a heterogeneous `NTuple{6}` (log bins for the non-negative invariants, linear for the signed ones is the natural choice). Indexing it with a *runtime* `t` makes `vb` a `Union`, which turns the `digitize` call into a dynamic dispatch on every pair × invariant in the hot loop. -A macro rather than a higher-order function: passing `body` as a closure measured 45 ns/pair slower -in the single-pass 2D scatter than emitting it inline. +A macro, so `body` is emitted inline at each of the six literal indices. """ macro sp2d_each_invariant(value_bins, t, vb, body) blocks = map(1:SINGLE_PASS_N) do i diff --git a/src/Calculations/batch_leading.jl b/src/Calculations/batch_leading.jl index 3341624..3572314 100644 --- a/src/Calculations/batch_leading.jl +++ b/src/Calculations/batch_leading.jl @@ -1,17 +1,9 @@ -# Batch-leading, Val{D}-specialized CPU batch kernels. +# CPU batch kernels over a batch-leading `(B, D, N)` working buffer, specialized on `Val(D)`. # -# Two problems in the original (D,N,B) batch kernels (see benchmark/cpu_regimes.jl baseline): -# 1. `D = size(x,1)` was a RUNTIME value, so `SVector{D}` / `Val(D)` built the SVector TYPE -# inside the hot loop → type instability → ~1140 allocs per pair-op → GC-bound (the 32 s). -# 2. the `@simd for b` loop read `u[d, point, b]` with stride D*N in b → no packed SIMD. -# -# Fix (proven ordering — type stability first, then layout): -# * a single dynamic dispatch on `Val(D)` is a FUNCTION BARRIER: the kernel body is fully -# specialized on `D` (0 allocations), the one unstable call is amortized over the whole O(N²B). -# * kernels operate on a batch-LEADING working buffer `(B, D, N)` so `@simd for b` gets unit -# stride; for shared positions the bin is constant across b ⇒ contiguous accumulate (no scatter). -# -# Isolated micro-bench (N=150,B=64,D=3): runtime-D 814M allocs/1906 ms → Val{D}+(B,D,N) 0/0.53 ms. +# `D` reaches every kernel as a type parameter, so each `SVector{D}` has a compile-time type and the +# body allocates nothing; the one dynamic dispatch on `Val(D)` is amortized over the whole `O(N²B)` +# sweep. The batch axis is innermost, so `@simd for b` reads unit stride, and with shared positions +# the bin is constant across `b`, making the accumulation contiguous. using Distances: Distances as DI @@ -23,7 +15,7 @@ using Distances: Distances as DI Wrap a velocity/position array that is already stored **batch-leading**, shape `(B, D, N)` (batch axis innermost/contiguous — the CPU-optimal SoA layout). CPU batch kernels then run zero-copy. A plain `(D, N, B...)` array (the default contract, GPU-optimal) is transposed once -internally (measured <1% of one pass). Zero-cost type tag. +internally. Zero-cost type tag. """ struct BatchLeading{A <: AbstractArray} data::A @@ -95,9 +87,8 @@ Base.@propagate_inbounds _bl_vel(ub, b, i, ::Val{D}) where {D} = """ Throw unless the staged coordinate width matches what `geom` needs. -The batch entry points take raw `(D, N, B…)` arrays rather than going through -[`_validate_array_shape`](@ref), so this is where a mismatched `x` is caught — before the kernels -load it under `@inbounds`. +The batch entry points take raw `(D, N, B…)` arrays, so this is where a mismatched `x` is caught, +before the kernels load it under `@inbounds`. """ @inline function _validate_bl_geometry(geom, W::Int, D::Int) want = _val_int(SFH.coordinate_width(geom)) @@ -273,18 +264,10 @@ end # and du_norm2=⟨du,du⟩ are needed — the old `du_T = mδu_t(...)` was dead work (now removed). # ---------------------------------------------------------------------------------------- @inline function _bl_sp1d_write!(sums_bl, counts_bl, b, bin, du_L, du_norm2, ::Type{CT}) where {CT} - du_L2 = du_L * du_L - du_T2 = du_norm2 - du_L2 - @inbounds begin - sums_bl[b, 1, bin] += du_norm2 # S2 = du_L2 + du_T2 - sums_bl[b, 2, bin] += du_L2 # L2 - sums_bl[b, 3, bin] += du_T2 # T2 - sums_bl[b, 4, bin] += du_L * du_norm2 # S3 - sums_bl[b, 5, bin] += du_L * du_L2 # L3 - sums_bl[b, 6, bin] += du_L * du_T2 # L1T2 - for t in 1:SINGLE_PASS_N - counts_bl[b, t, bin] += one(CT) - end + vals = single_pass_invariants(du_L, du_norm2) + @inbounds for t in 1:SINGLE_PASS_N + sums_bl[b, t, bin] += vals[t] + counts_bl[b, t, bin] += one(CT) end return nothing end @@ -344,11 +327,7 @@ end # Single-pass 2D (6 invariants × per-invariant value bins). Accumulator (B, 6, n_dist, n_val); # per-invariant value bin ⇒ scatter ⇒ plain b-loop. # ---------------------------------------------------------------------------------------- -@inline function _sp1d_vals(du_L, du_norm2) - du_L2 = du_L * du_L - du_T2 = du_norm2 - du_L2 - return (du_norm2, du_L2, du_T2, du_L * du_norm2, du_L * du_L2, du_L * du_T2) -end +@inline _sp1d_vals(du_L, du_norm2) = single_pass_invariants(du_L, du_norm2) @inline function _bl_sp2d_write!(sums_bl, counts_bl, b, dbin, vals, value_bins, n_val, ::Type{CT}) where {CT} @sp2d_each_invariant value_bins t vb begin @@ -416,11 +395,9 @@ end # ======================================================================================== # Drivers: prep (transpose to batch-leading) + run kernel via an EXECUTOR + transpose back. # -# Parallelism is over the OUTER pair index `i` (each pair's geometry is computed exactly once; -# the inner batch loop over b stays full and SIMD-vectorized). The b-work is so fast that -# parallelizing over b instead (recomputing geometry per task) was a NET SLOWDOWN — so we -# partition `i` with round-robin chunks (triangle load balance) and reduce thread-local -# accumulators, mirroring the point-field threaded path. +# Parallelism is over the outer pair index `i`, so each pair's geometry is computed once and the +# inner batch loop over `b` stays full and SIMD-vectorized. `i` is partitioned into round-robin +# chunks, which balances the triangle, and thread-local accumulators are reduced at the end. # # executor(make_accum, run_chunk!, ifull, B, accum_bytes, ws) → reduced (sums, counts), width B: # make_accum(bw) → fresh zeroed (sums_bl, counts_bl) of batch width bw @@ -444,7 +421,7 @@ end One accumulator per task, of the given batch widths, drawn from the workspace when there is one and allocated fresh otherwise. Always built outside the parallel region, so tasks only read their slot. """ -_bl_accum_pool(::Nothing, make_accum::F, widths::Vector{Int}) where {F} = +_bl_accum_pool(::Nothing, make_accum::F, widths::AbstractVector{Int}) where {F} = [make_accum(w) for w in widths] """The full-width reduction accumulator, from the workspace when there is one.""" diff --git a/src/Calculations/channels.jl b/src/Calculations/channels.jl deleted file mode 100644 index fc22fa0..0000000 --- a/src/Calculations/channels.jl +++ /dev/null @@ -1,362 +0,0 @@ -# Multi-channel pair sweep. A field carrying more than one channel forms its increment channel by -# channel — vectors transported, scalars differenced — and hands the whole bundle to the operator, -# which reads the channels it names. - -""" - channel_increment(::Fields{D,V,K}, data, geom, frame, r, i, j) -> ChannelIncrement - -One pair's increment across every channel of a packed field. - -Each vector channel is transported into the pair's common frame before differencing, exactly as a -single-channel field is; each scalar channel is differenced where it stands, because a scalar has -nothing to transport. -""" -@inline function channel_increment( - ::Val{F}, ::Val{V}, ::Val{K}, data::AbstractMatrix{T}, geom, frame, i::Integer, j::Integer, -) where {F, V, K, T} - vectors = ntuple(Val(V)) do c - o = (c - 1) * F - a = SA.SVector{F, T}(ntuple(d -> @inbounds(data[o + d, i]), Val(F))) - b = SA.SVector{F, T}(ntuple(d -> @inbounds(data[o + d, j]), Val(F))) - SFH.pair_delta(geom, frame, nothing, nothing, a, b) - end - scalars = ntuple(Val(K)) do c - @inbounds data[V * F + c, j] - data[V * F + c, i] - end - Dp = V == 0 ? 0 : length(first(vectors)) - return CH.ChannelIncrement{Dp, V, K, T}(vectors, scalars) -end - -""" - _kernel_channels(fields, geom, x) -> (x_kernel, packed_kernel, Val{F}) - -The field in the form the kernels index: every vector channel widened by the geometry exactly as a -single-channel field is, scalars untouched. - -On a sphere a velocity is carried as an ambient 3-vector, so a bundle's vector channels must be -widened too — the same `prepare_pair_inputs` the array path uses, once per channel, so there is no -second conversion to drift from it. -""" -function _kernel_channels(f::CH.Fields{D, V, K}, geom, x::AbstractMatrix) where {D, V, K} - data = CH.packed(f) - N = size(data, 2) - F = SFC_val_int(SFH.field_width(geom)) - if F == D - return SFH.prepare_coordinates(geom, x), data, Val(D) - end - T = float(eltype(data)) - out = Matrix{T}(undef, V * F + K, N) - @inbounds for c in 1:V - rows = ((c - 1) * D + 1):(c * D) - _, vk = SFH.prepare_pair_inputs(geom, x, @view(data[rows, :])) - out[((c - 1) * F + 1):(c * F), :] .= vk - end - @inbounds for c in 1:K - out[V * F + c, :] .= @view(data[V * D + c, :]) - end - return SFH.prepare_coordinates(geom, x), out, Val(F) -end - -""" - serial_calculate_structure_function!(sums, counts, sf, x, fields, distance_bins; kwargs...) - -Accumulate a multi-channel field's pairs into the 1-D distance histogram. - -A field of one vector channel and no scalars is the array path — it forwards there, so a bare `u` and -`Fields(vectors = (u,))` give the same answer through the same kernel. Anything carrying more than -one channel takes this sweep, which builds each pair's whole increment bundle and hands it to the -operator; it is a scalar loop, where the single-channel path is a SIMD compute/scatter split. -""" -function serial_calculate_structure_function!( - sums::AbstractVector, counts::AbstractVector, - sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::CH.Fields{D, 1, 0}, distance_bins; - kwargs..., -) where {D} - return serial_calculate_structure_function!(sums, counts, sf, x, CH.packed(f), distance_bins; - kwargs...) -end - -function serial_calculate_structure_function!( - sums::AbstractVector{OT}, counts::AbstractVector{CT}, - sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, f::CH.Fields{D, V, K}, distance_bins; - distance_metric::DI.PreMetric = DI.Euclidean(), - culling::CullingPolicy = AutoCulling(), - verbose::Bool = true, - show_progress::Bool = true, -) where {OT, CT, D, V, K} - N = size(CH.packed(f), 2) - size(x, 2) == N || throw(DimensionMismatch( - "x covers $(size(x, 2)) points and the field $N", - )) - geom, xk, data, vF, plan, grid = channel_setup(f, x, distance_bins, distance_metric, culling) - _channel_run_blocks!(sums, counts, sf, xk, data, geom, vF, Val(V), Val(K), plan, - n_histogram_bins(plan), Val(SFC_val_int(SFH.coordinate_width(geom))), - 1:(N - 1), N, grid) - return nothing -end - -""" - channel_setup(fields, x, distance_bins, metric, culling) -> (geom, xk, data, vF, plan, grid) - -Everything a multi-channel sweep needs before its first pair: the geometry, the widened coordinates -and channels, the digitize plan, and the cull grid with both arrays already permuted into it. - -Shared by the serial and threaded drivers so the sort and the widening happen **once**, above any -task loop — doing them inside one would pay them per task. -""" -function channel_setup(f::CH.Fields{D, V, K}, x::AbstractMatrix, distance_bins, - distance_metric, culling::CullingPolicy) where {D, V, K} - geom = SFH.pair_geometry_for(distance_metric, Val(max(D, 1))) - xk, data, vF = _kernel_channels(f, geom, x) - W = SFC_val_int(SFH.coordinate_width(geom)) - plan = squared_digitize_plan(distance_bins) - xc = ntuple(d -> collect(view(xk, d, :)), Val(W)) - grid = culling isa NoCulling ? nothing : cull_grid_for(xc, geom, distance_bins, culling) - if grid !== nothing - xk = xk[:, grid.perm] - data = data[:, grid.perm] - end - return geom, xk, data, vF, plan, grid -end - -# Dispatch on the grid so the kernel receives one concretely typed schedule, as the single-channel -# path does. -@inline _channel_run_blocks!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, ilist, N, - ::Nothing) = - _channel_pairs!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, - pair_blocks(N, ilist)) - -@inline _channel_run_blocks!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, ilist, N, - grid::CellGrid) = - _channel_pairs!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, - pair_blocks(N, ilist; grid = grid)) - -""" - _channel_pairs!(sums, counts, sf, xk, data, geom, ...) -> nothing - -Accumulate the pairs `blocks` covers for a multi-channel field. - -Each block pair is worked to completion, so its columns stay cache-resident across the `i` sweep — -the reason the single-channel kernel is blocked, and it applies here for the same reason. -""" -# Flat geometry: the separation IS the displacement, so the whole per-pair computation is arithmetic -# on stack values and the compute half vectorizes — the same compute/scatter split the single-channel -# kernel uses, and for the same reason (a scatter in the loop body stops it vectorizing). -function _channel_pairs!( - sums::AbstractVector{OT}, counts::AbstractVector{CT}, - sf::SFT.AbstractPairwiseStructureFunctionType, - xk::AbstractMatrix, data::AbstractMatrix, geom::SFH.FlatGeometry, ::Val{F}, ::Val{V}, ::Val{K}, - plan::AbstractSquaredDigitizePlan, nb::Int, ::Val{W}, blocks, -) where {OT, CT, F, V, K, W} - FTx = eltype(xk) - T = eltype(data) - N = size(xk, 2) - keybuf = Vector{FTx}(undef, N) - valbuf = Vector{OT}(undef, N) - idxbuf = Vector{Int32}(undef, N) - @inbounds for (ir, jr) in blocks - j_first, j_last = first(jr), last(jr) - for i in ir - jlo = max(i + 1, j_first) - jlo > j_last && continue - Xi = SA.SVector{W, FTx}(ntuple(d -> xk[d, i], Val(W))) - @simd for j in jlo:j_last - Xj = SA.SVector{W, FTx}(ntuple(d -> xk[d, j], Val(W))) - dx = Xj - Xi - r2 = LA.dot(dx, dx) - vectors = ntuple(Val(V)) do c - o = (c - 1) * F - SA.SVector{F, T}(ntuple(d -> data[o + d, j] - data[o + d, i], Val(F))) - end - scalars = ntuple(c -> data[V * F + c, j] - data[V * F + c, i], Val(K)) - inc = CH.ChannelIncrement{F, V, K, T}(vectors, scalars) - keybuf[j] = digitize_key(plan, r2) - valbuf[j] = OT(sf(inc, dx / sqrt(r2))) - if has_vector_index(plan) - idxbuf[j] = squared_approx_index(plan, r2) - end - end - for j in jlo:j_last - b = squared_bin(plan, keybuf[j], idxbuf[j]) - if 1 <= b <= nb - sums[b] += valbuf[j] - counts[b] += one(CT) - end - end - end - end - return nothing -end - -function _channel_pairs!( - sums::AbstractVector{OT}, counts::AbstractVector{CT}, - sf::SFT.AbstractPairwiseStructureFunctionType, - xk::AbstractMatrix, data::AbstractMatrix, geom, ::Val{F}, ::Val{V}, ::Val{K}, - plan::AbstractSquaredDigitizePlan, nb::Int, ::Val{W}, blocks, -) where {OT, CT, F, V, K, W} - FTx = eltype(xk) - @inbounds for (ir, jr) in blocks - j_first, j_last = first(jr), last(jr) - for i in ir - jlo = max(i + 1, j_first) - jlo > j_last && continue - Xi = SA.SVector{W, FTx}(ntuple(d -> xk[d, i], Val(W))) - for j in jlo:j_last - Xj = SA.SVector{W, FTx}(ntuple(d -> xk[d, j], Val(W))) - ok, r, frame = SFH.pair_frame(geom, Xi, Xj) - ok || continue - b = squared_digitize(plan, r * r) - 1 <= b <= nb || continue - inc = channel_increment(Val(F), Val(V), Val(K), data, geom, frame, i, j) - sums[b] += OT(sf(inc, SFH.pair_direction(geom, frame, r))) - counts[b] += one(CT) - end - end - end - return nothing -end - -@inline SFC_val_int(::Val{W}) where {W} = W - -""" - required_channels(operator) -> (n_vector, n_scalar) - -The highest vector and scalar channel index an operator reads. - -Every operator that predates the channel bundle reads the field itself, which is channel 1 of the -vector side — that is what keeps `Fields(vectors = (u,))` identical to a bare `u`. -""" -@inline required_channels(::SFT.AbstractPairwiseStructureFunctionType) = (1, 0) -@inline required_channels(sf::SFT.ScalarStructureFunctionType) = (0, sf.channel) -@inline required_channels(sf::SFT.MixedStructureFunctionType) = - (sf.vector_channel, sf.scalar_channel) -@inline required_channels(sf::SFT.VectorDotStructureFunctionType) = (max(sf.a, sf.b), 0) -@inline required_channels(sf::SFT.ScalarDotStructureFunctionType) = (0, max(sf.a, sf.b)) - -""" - validate_channels(operator, fields) - -Refuse an operator that reads a channel the bundle does not carry. - -Checked once at the entry rather than per pair: the per-pair check would be inside a task on a -threaded backend, where the error surfaces wrapped in a `TaskFailedException` instead of as itself. -""" -function validate_channels(sf::SFT.AbstractPairwiseStructureFunctionType, - f::CH.Fields{D, V, K}) where {D, V, K} - nv, ns = required_channels(sf) - nv <= V || throw(ArgumentError( - "$(nameof(typeof(sf))) reads vector channel $nv, but this field carries $V. Build the " * - "bundle with that channel, e.g. `Fields(vectors = (u, 𝓐u))`.", - )) - ns <= K || throw(ArgumentError( - "$(nameof(typeof(sf))) reads scalar channel $ns, but this field carries $K. Build the " * - "bundle with that channel, e.g. `Fields(vectors = (u,), scalars = (θ,))`.", - )) - return nothing -end - -""" - channel_partial(sf, x, fields, distance_bins, outer; kwargs...) -> (sums, counts) - -A worker's share of a multi-channel sweep: the pairs whose lower index is in `outer`, in freshly -allocated accumulators. - -The outer lists partition `1:(N-1)`, so the partials add to the whole sweep exactly. Note the -indices are into the **culled ordering** when culling is on, which is a permutation of the input and -therefore still a partition. -""" -function channel_partial( - sf::SFT.AbstractPairwiseStructureFunctionType, x::AbstractMatrix, f::CH.Fields{D, V, K}, - distance_bins, outer; - distance_metric::DI.PreMetric = DI.Euclidean(), - culling::CullingPolicy = AutoCulling(), - count_eltype::Type{CT} = UInt32, -) where {D, V, K, CT} - N = size(CH.packed(f), 2) - nb = n_histogram_bins(squared_digitize_plan(distance_bins)) - sums = zeros(float(eltype(CH.packed(f))), nb) - counts = zeros(CT, nb) - geom, xk, data, vF, plan, grid = channel_setup(f, x, distance_bins, distance_metric, culling) - _channel_run_blocks!(sums, counts, sf, xk, data, geom, vF, Val(V), Val(K), plan, - n_histogram_bins(plan), Val(SFC_val_int(SFH.coordinate_width(geom))), - outer, N, grid) - return sums, counts -end - -""" - distributed_calculate_structure_function!(sums, counts, sf, x, fields, bins; kwargs...) - -Accumulate a multi-channel sweep across worker processes. Supplied by the Distributed extension. -""" -function distributed_calculate_structure_function!(sums, counts, sf, x, f::CH.Fields, bins; - kwargs...) - throw(ArgumentError( - "the distributed multi-channel sweep needs Distributed: run `using Distributed` and add " * - "workers.", - )) -end - -""" - gpu_calculate_structure_function!(backend, sums, counts, sf, x, fields, bins; kwargs...) - -Accumulate a multi-channel sweep on a device. Supplied by the KernelAbstractions extension. -""" -function gpu_calculate_structure_function_channels!(backend, sums, counts, sf, x, f::CH.Fields, - bins; kwargs...) - throw(ArgumentError( - "the GPU multi-channel sweep needs KernelAbstractions: run `using KernelAbstractions` and " * - "a device backend such as CUDA.", - )) -end - -# Backend selection for a channel bundle, mirroring the array path's: the concrete backends dispatch, -# and `Auto` takes the threaded one when there are threads to use and the extension supplying it is -# loaded. -@inline _channel_dispatch!(::CB.AbstractSerialBackend, sums, counts, sf, x, f, bins; kwargs...) = - serial_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) - -@inline _channel_dispatch!(::CB.AbstractThreadedBackend, sums, counts, sf, x, f, bins; kwargs...) = - threaded_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) - -@inline _channel_dispatch!(::CB.AbstractDistributedBackend, sums, counts, sf, x, f, bins; - kwargs...) = - distributed_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) - -@inline _channel_dispatch!(be::CB.AbstractGPUBackend, sums, counts, sf, x, f, bins; kwargs...) = - gpu_calculate_structure_function_channels!(be, sums, counts, sf, x, f, bins; kwargs...) - -function _channel_dispatch!(::CB.AbstractAutoBackend, sums, counts, sf, x, f, bins; kwargs...) - if Threads.nthreads() > 1 && _ohmythreads_loaded() - return threaded_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) - end - return serial_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) -end - -""" - calculate_structure_function(sf, x, fields, distance_bins[, count_eltype]; kwargs...) - -Structure function of a multi-channel field: several quantities sampled at the same points, swept -together so a mixed moment costs one pass rather than one per channel. -""" -function calculate_structure_function( - sf::SFT.AbstractPairwiseStructureFunctionType, - x::AbstractMatrix, - f::CH.Fields, - distance_bins::AbstractVector, - count_eltype::Type{CT} = UInt32; - backend::CB.AbstractExecutionBackend = CB.AutoBackend(), - output_type::Type{OT} = SFO.StructureFunction, - kwargs..., -) where {OT, CT} - N = size(CH.packed(f), 2) - _assert_counts_representable(CT, N) - nb = n_histogram_bins(squared_digitize_plan(distance_bins)) - validate_channels(sf, f) - sums = zeros(float(eltype(CH.packed(f))), nb) - counts = zeros(CT, nb) - _channel_dispatch!(backend, sums, counts, sf, x, f, distance_bins; kwargs...) - raw = SFO.StructureFunctionSumsAndCounts(sf, distance_bins, sums, counts) - return _finalize(raw, output_type) -end diff --git a/src/Calculations/culling.jl b/src/Calculations/culling.jl index cbc3c80..022effe 100644 --- a/src/Calculations/culling.jl +++ b/src/Calculations/culling.jl @@ -5,11 +5,11 @@ cull_cutoff(geometry, r_max) Euclidean cutoff, in the coordinate space the kernels see, that bounds a true separation of -`r_max`. Culling compares squared Euclidean distances against this, so it must never be smaller -than the true bound or in-range pairs would be dropped. +`r_max`. Culling compares squared Euclidean distances against this, so it must be at least the true +bound; a smaller one drops in-range pairs. -`nothing` means the geometry has declared no such bound, and culling then declines rather than -risk dropping pairs. A user-defined geometry is therefore correct by default and opts in by adding +`nothing` means the geometry has declared no such bound, and culling declines. A user-defined +geometry is therefore correct by default and opts in by adding a method — it is never required to have one. """ @inline cull_cutoff(::Any, r_max) = nothing @@ -32,10 +32,10 @@ Uniform cell decomposition of a point set, with points sorted by cell id, so eve contiguous run: `cell_run(grid, c)` in the permuted order. Only **occupied** cells are stored, as the sorted ids `cell_ids` and their run boundaries -`run_starts`. A dense array indexed by cell id would be `prod(dims)+1` long, which is unbounded: -`dims` grows as `(extent/cutoff)^D`, so a flat 3-D set at `r_max/L = 0.003` wants 2.3 GB and a -64 km cutoff on a shell wants 0.5 GB — while occupancy never exceeds the point count. Storing the -occupied cells makes both the memory and the block enumeration `O(N)` at any resolution. +`run_starts`. The cell-id space is unbounded — `dims` grows as `(extent/cutoff)^D`, reaching 2.3 GB +of ids for a flat 3-D set at `r_max/L = 0.003` — while occupancy never exceeds the point count, so +storing the occupied cells keeps both the memory and the block enumeration `O(N)` at any +resolution. The index and offset arrays are type parameters, not `Vector`s, so one type serves a host build and a device-resident copy. @@ -107,8 +107,8 @@ end cull_row_offsets(span, ::Val{D}) Each surviving stencil row as `(offset over dimensions 2:D, half-extent along dimension 1)`. -Dimension 1 is carried as an extent rather than an offset because cells adjacent along it are -contiguous in the sorted order, so a whole row is swept as one run; the extent is the widest that +Dimension 1 is carried as an extent: cells adjacent along it are contiguous in the sorted order, so +a whole row is swept as one run. The extent is the widest that still satisfies the corner test, so the row is no larger than the true stencil. """ function cull_row_offsets(span::Int, ::Val{D}) where {D} @@ -139,7 +139,7 @@ A counting sort is faster but needs scratch proportional to the **cell-id space* unbounded in the cutoff. So it is used only while that space stays within a small multiple of the point count; `sortperm` covers the rest, where the cells are mostly empty anyway. """ -function _cull_sortperm(cell_raw::Vector{Int}, n_cells::Int, N::Int) +function _cull_sortperm(cell_raw::AbstractVector{Int}, n_cells::Int, N::Int) n_cells <= SF_CULL_COUNTING_SORT_CELLS_PER_POINT * N || return sortperm(cell_raw) cursor = zeros(Int, n_cells + 1) @inbounds for i in 1:N @@ -291,7 +291,7 @@ _cull_reject_unsupported(::AlwaysCulling, what::AbstractString) = throw(Argument """ cull_cutoff_for(geometry, distance_bins, policy) -> cutoff or nothing -The Euclidean cutoff a cull grid would be built with, or `nothing` when culling does not apply: +The Euclidean cutoff for a cull grid, or `nothing` when culling does not apply: the policy is [`NoCulling`](@ref), the last bin is unbounded, or the geometry declares no bound. """ function cull_cutoff_for(geometry, distance_bins, policy::CullingPolicy) diff --git a/src/Calculations/dispatch.jl b/src/Calculations/dispatch.jl index 18d0e92..0b9c1e6 100644 --- a/src/Calculations/dispatch.jl +++ b/src/Calculations/dispatch.jl @@ -22,6 +22,7 @@ _finalize(r::SFO.StructureFunctionSumsAndCounts, ::Type{<:SFO.StructureFunction} SFO.StructureFunction(r.operator, r.distance, _bin_average(r.sums, r.counts)) _finalize(r::SFO.StructureFunction2DSumsAndCounts, ::Type{<:SFO.StructureFunction2DSumsAndCounts}) = r _finalize(r::SFO.StructureFunctionTensorSumsAndCounts, ::Type{<:SFO.StructureFunctionTensorSumsAndCounts}) = r +_finalize(r::SFO.StructureFunctionTensor2DSumsAndCounts, ::Type{<:SFO.StructureFunctionTensor2DSumsAndCounts}) = r _finalize(r::SFO.StructureFunctionTensorSumsAndCounts{P}, ::Type{<:SFO.StructureFunctionTensor}) where {P} = SFO.StructureFunctionTensor(r.order, r.distance_bins, _tensor_bin_average(r.sums, r.counts, Val(P))) _finalize(r, ::Type{R}) where {R} = throw(ArgumentError( @@ -74,11 +75,12 @@ function calculate_structure_function( kwargs..., ) where {FT1, FT2, OT, CT} shape = _validate_array_shape(x, u, distance_metric) + has_auxiliary_axes(shape) && _refuse_weights(kwargs, "the batched entries over auxiliary axes") _assert_counts_representable(CT, size(x, 2)) # The shape carries the velocity dimension as a type parameter, but that dimension is an array - # axis length, so the constructed type is not inferrable and every kernel below it would be - # typed `Any`. Re-entering through a concrete `Val` hands each branch a shape whose parameter is - # known: the branch is chosen at runtime, everything under it is not. + # axis length, so the constructed type is not inferrable and types every kernel below it `Any`. + # Re-entering through a concrete `Val` hands each branch a shape whose parameter is known: the + # branch is chosen at runtime, everything under it is not. D = size(u, 1) S = _shape_kind(x, u) kw = (; distance_metric, kwargs...) @@ -94,8 +96,8 @@ function calculate_structure_function( return _finalize(raw, output_type) end -"""Largest velocity width the entry specializes for. Beyond it the kernels would be dispatched -dynamically per pair, so the boundary is stated rather than crossed silently.""" +"""Largest velocity width the entry specializes for. Past it a kernel dispatches once per pair, so the +entry refuses the width by name.""" const MAX_SPECIALIZED_WIDTH = 8 """ @@ -104,17 +106,26 @@ const MAX_SPECIALIZED_WIDTH = 8 Dispatch with a shape whose width parameter is a **literal**. An array's axis length is a value, not a type, so a shape built straight from it cannot be inferred -and every kernel below would be typed `Any` — a dynamic dispatch per pair. The caller therefore -branches on the width and passes a literal here. The keywords ride as a positional `NamedTuple` +and types every kernel below `Any`, a dynamic dispatch per pair. The caller therefore branches on the +width and passes a literal here. The keywords ride as a positional `NamedTuple` because a keyword call blocks the constant propagation this depends on. """ @inline _dw(shape, backend, sf, x, u, distance_bins, count_eltype, kw::NamedTuple) = _dispatch_execution_backend(backend, shape, sf, x, u, distance_bins, count_eltype; kw...) +""" +Pair weights reach the serial and threaded point kernels and every gridded route; a path that has no +weighted kernel refuses them by name. +""" +_refuse_weights(kwargs, path::AbstractString) = get(kwargs, :weights, nothing) === nothing ? nothing : + throw(ArgumentError( + "pair weights are not implemented on $path; use the serial or threaded backend, or a gridded entry", + )) + @noinline _width_unsupported(D) = throw(ArgumentError( "velocity dimension D=$D exceeds the largest width the kernels are specialized for " * - "($MAX_SPECIALIZED_WIDTH). Widths are specialized rather than dispatched dynamically because " * - "the alternative costs a dynamic dispatch per pair.", + "($MAX_SPECIALIZED_WIDTH). Widths are specialized, because dispatching on the width costs one " * + "dynamic dispatch per pair.", )) """ @@ -158,6 +169,7 @@ function calculate_structure_function( distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., ) where {FT1, FT2, OT, CT} + _refuse_weights(kwargs, "the value-binned joint histogram of a point list") shape = _validate_array_shape(x, u, distance_metric) _assert_counts_representable(CT, size(x, 2)) raw = _dispatch_execution_backend( @@ -210,8 +222,7 @@ function calculate_structure_function( min_distance, max_distance = _minmax_for_autobins(shape, x, distance_metric, show_progress) actual_bins = _auto_distance_bins(min_distance, max_distance, distance_bins, bin_spacing) - # `bin_spacing` selected these edges and means nothing downstream, so it is consumed here - # rather than forwarded into a `kwargs...` sink that would silently swallow it. + # `bin_spacing` selected these edges and means nothing downstream, so it is consumed here. return calculate_structure_function( structure_function_type, x, @@ -388,6 +399,7 @@ function calculate_structure_function!( backend=CB.SerialBackend(), distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) shape = _validate_array_shape(x, u, distance_metric) + has_auxiliary_axes(shape) && _refuse_weights(kwargs, "the batched entries over auxiliary axes") _assert_counts_representable(eltype(counts), size(x, 2)) _dispatch_execution_backend!(backend, shape, sums, counts, sf_type, x, u, distance_bins; distance_metric, kwargs...) @@ -405,6 +417,7 @@ function calculate_structure_function!( sums_2d, counts_2d, sf_type, x::AbstractArray, u::AbstractArray, distance_bins, value_bins; backend=CB.SerialBackend(), distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) + _refuse_weights(kwargs, "the value-binned joint histogram of a point list") shape = _validate_array_shape(x, u, distance_metric) _assert_counts_representable(eltype(counts_2d), size(x, 2)) _dispatch_execution_backend!(backend, shape, sums_2d, counts_2d, sf_type, x, u, distance_bins, value_bins; @@ -439,6 +452,7 @@ end function _dispatch_execution_backend!( backend::CB.AbstractGPUBackend, shape::PointField, sums::AbstractVector, counts::AbstractVector, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) + _refuse_weights(kwargs, "the GPU point kernels") gpu_calculate_structure_function!(sums, counts, structure_function_type, backend.backend, x, u, distance_bins; kwargs...) return nothing end @@ -571,12 +585,14 @@ end function _dispatch_execution_backend( backend::CB.AbstractDistributedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... ) where {CT} + _refuse_weights(kwargs, "the distributed point path") return _dispatch_execution_backend(backend, structure_function_type, x, u, distance_bins; count_eltype, kwargs...) end function _dispatch_execution_backend( backend::CB.AbstractGPUBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... ) where {CT} + _refuse_weights(kwargs, "the GPU point kernels") if has_auxiliary_axes(shape) return gpu_calculate_structure_function_batch(structure_function_type, backend.backend, x, u, distance_bins; count_eltype, kwargs...) end diff --git a/src/Calculations/fits.jl b/src/Calculations/fits.jl new file mode 100644 index 0000000..19a5a1a --- /dev/null +++ b/src/Calculations/fits.jl @@ -0,0 +1,616 @@ +# Regularised fits of spectra and fluxes to binned structure functions: linear forward models from +# values on wavenumber bins to the structure function at the result's separations, and the inversions +# that fit them. + +# --------------------------------------------------------------------------------------------------- +# Wavenumber quadrature +# --------------------------------------------------------------------------------------------------- + +""" + _bin_nodes(k_edges, r_max) -> (k, w, bin) + +Gauss–Legendre nodes and weights over every wavenumber bin, enough per bin to integrate a kernel that +oscillates as `cos(k r_max)` across it, with the bin each node belongs to. +""" +function _bin_nodes(k_edges::AbstractVector, r_max::Real) + nb = length(k_edges) - 1 + k = Float64[] + w = Float64[] + bin = Int[] + for j in 1:nb + a, b = Float64(k_edges[j]), Float64(k_edges[j + 1]) + n = 12 + ceil(Int, (b - a) * r_max / 2) + μ, ω = gauss_legendre(n) + append!(k, (a + b) / 2 .+ (b - a) / 2 .* μ) + append!(w, (b - a) / 2 .* ω) + append!(bin, fill(j, n)) + end + return k, w, bin +end + +function _check_wavenumber_edges(k_edges::AbstractVector) + length(k_edges) >= 2 || throw(ArgumentError("wavenumber edges need at least one bin")) + issorted(k_edges) || throw(ArgumentError("wavenumber edges must be sorted")) + first(k_edges) > 0 || throw(ArgumentError( + "wavenumber edges must be positive; the k = 0 mode is not recoverable from a structure function", + )) + return nothing +end + +function _check_separations(r::AbstractVector) + isempty(r) && throw(ArgumentError("no separation to fit at")) + issorted(r) || throw(ArgumentError("separations must be sorted")) + first(r) > 0 || throw(ArgumentError("separations must be positive")) + return nothing +end + +"""The bin each column of a forward matrix stands for: its centre and width.""" +_bin_centres(k_edges) = [(k_edges[j] + k_edges[j + 1]) / 2 for j in 1:(length(k_edges) - 1)] +_bin_widths(k_edges) = [k_edges[j + 1] - k_edges[j] for j in 1:(length(k_edges) - 1)] + +# --------------------------------------------------------------------------------------------------- +# Forward models +# --------------------------------------------------------------------------------------------------- + +""" + AbstractForwardModel + +A linear map `y = H x` from values on wavenumber bins to a structure function at fixed separations. +[`forward_matrix`](@ref) returns `H`; `model.r` the separations, `model.k_edges` the bin edges. +""" +abstract type AbstractForwardModel end + +"""The matrix of a forward model.""" +forward_matrix(m::AbstractForwardModel) = m.H + +""" + SpectrumForwardModel(::Val{D}, r, k_edges) + +The second-order trace at the separations `r` from a shell spectrum `E(k)` constant on each of the +wavenumber bins `k_edges`, in `D` dimensions: + +```math +S_2(r_i) = 2 ∫_0^∞ E(k)\\,[1 - \\mathrm{kernel}_D(k r_i)]\\,dk = Σ_j H_{ij} E_j, +\\qquad H_{ij} = 2 ∫_{k_j}^{k_{j+1}} [1 - \\mathrm{kernel}_D(k r_i)]\\,dk , +``` + +`kernel_D` the angular average of `cos(k·r)` ([`isotropic_kernel`](@ref); `J₀` in two dimensions, +which needs `Bessels`). `E` integrates over `k` to the variance, the convention of +[`shell_spectrum`](@ref). Each bin is integrated by Gauss–Legendre quadrature. +""" +struct SpectrumForwardModel{D, T, RT <: AbstractVector, KT <: AbstractVector} <: AbstractForwardModel + r::RT + k_edges::KT + H::Matrix{T} +end + +function SpectrumForwardModel(::Val{D}, r::AbstractVector, k_edges::AbstractVector) where {D} + _check_separations(r) + _check_wavenumber_edges(k_edges) + k, w, bin = _bin_nodes(k_edges, last(r)) + H = zeros(Float64, length(r), length(k_edges) - 1) + @inbounds for q in eachindex(k), i in eachindex(r) + H[i, bin[q]] += 2 * w[q] * (1 - isotropic_kernel(Val(D), k[q] * r[i])) + end + return SpectrumForwardModel{D, Float64, typeof(r), typeof(k_edges)}(r, k_edges, H) +end + +""" + HelmholtzForwardModel(r, k_edges) + +The longitudinal and transverse second-order structure functions of a two-dimensional field, stacked +as `[D_LL; D_TT]` at the separations `r`, from the gradient (`E`) and curl (`B`) shell spectra stacked +as `[E_E; E_B]` on the bins `k_edges`: + +```math +D_{LL} + D_{TT} = 2 ∫ (E_E + E_B)\\,[1 - J_0(kr)]\\,dk, \\qquad +D_{LL} - D_{TT} = 2 ∫ (E_E - E_B)\\, J_2(kr)\\,dk , +``` + +the relations [`helmholtz_spectra`](@ref) inverts. Needs `Bessels`. +""" +struct HelmholtzForwardModel{T, RT <: AbstractVector, KT <: AbstractVector} <: AbstractForwardModel + r::RT + k_edges::KT + H::Matrix{T} +end + +function HelmholtzForwardModel(r::AbstractVector, k_edges::AbstractVector) + _check_separations(r) + _check_wavenumber_edges(k_edges) + k, w, bin = _bin_nodes(k_edges, last(r)) + nr, nk = length(r), length(k_edges) - 1 + H = zeros(Float64, 2nr, 2nk) + @inbounds for q in eachindex(k), i in 1:nr + x = k[q] * r[i] + plus = w[q] * (1 - bessel_kernel(Val(0), x)) + minus = w[q] * bessel_kernel(Val(2), x) + j = bin[q] + H[i, j] += plus + minus + H[i, nk + j] += plus - minus + H[nr + i, j] += plus - minus + H[nr + i, nk + j] += plus + minus + end + return HelmholtzForwardModel{Float64, typeof(r), typeof(k_edges)}(r, k_edges, H) +end + +""" + FluxForwardModel(r, k_edges) + +The third-order structure function `S3 = ⟨δu_L ‖δu‖²⟩` of a two-dimensional isotropic flow at the +separations `r` from a spectral energy flux that is piecewise constant in wavenumber: `x = (ε, ξ₁, …, +ξ_n)` with `F(k) = -ε + Σ_j ξ_j Δk_j H(k - k_j)`, `k_j` the bin centres and `Δk_j` the bin widths, so +`ε` is the flux towards large scales below the first bin and `ξ_j` the injection density +(flux gained per unit wavenumber) in bin `j`. From `S3(r) = -4r ∫_0^∞ F(k) J_2(kr)/k\\,dk`, + +```math +S3(r_i) = 2 ε r_i - Σ_j 4\\,\\frac{ξ_j Δk_j}{k_j} J_1(k_j r_i) , +``` + +exactly for that `F`. `F` at the bin centres, just past each jump, is `G x` with +`G[i, 1] = -1`, `G[i, j + 1] = Δk_j` for `j ≤ i`; [`flux_matrix`](@ref) returns `G`. The sign is +that of [`spectral_flux`](@ref): positive towards small scales. Needs `Bessels`. +""" +struct FluxForwardModel{T, RT <: AbstractVector, KT <: AbstractVector} <: AbstractForwardModel + r::RT + k_edges::KT + H::Matrix{T} + G::Matrix{T} +end + +function FluxForwardModel(r::AbstractVector, k_edges::AbstractVector) + _check_separations(r) + _check_wavenumber_edges(k_edges) + kc = _bin_centres(k_edges) + dk = _bin_widths(k_edges) + nr, nk = length(r), length(kc) + H = zeros(Float64, nr, nk + 1) + @inbounds for i in 1:nr + H[i, 1] = 2 * r[i] + for j in 1:nk + H[i, j + 1] = -4 * dk[j] / kc[j] * bessel_kernel(Val(1), kc[j] * r[i]) + end + end + G = zeros(Float64, nk, nk + 1) + @inbounds for i in 1:nk + G[i, 1] = -1 + for j in 1:i + G[i, j + 1] = dk[j] + end + end + return FluxForwardModel{Float64, typeof(r), typeof(k_edges)}(r, k_edges, H, G) +end + +"""The matrix taking a flux model's `(ε, ξ…)` to the flux at the bin centres.""" +flux_matrix(m::FluxForwardModel) = m.G + +# --------------------------------------------------------------------------------------------------- +# Data covariance +# --------------------------------------------------------------------------------------------------- + +""" + _whitened(H, y, W) -> (Hw, yw) + +`W^{-1/2} H` and `W^{-1/2} y` for a data covariance `W` given as the variances of `y` (a vector), a +full matrix, or `nothing` for the identity. +""" +_whitened(H::AbstractMatrix, y::AbstractVector, ::Nothing) = (Matrix{Float64}(H), Vector{Float64}(y)) + +function _whitened(H::AbstractMatrix, y::AbstractVector, W::AbstractVector) + length(W) == length(y) || throw(DimensionMismatch( + "the data covariance names $(length(W)) variances for $(length(y)) values", + )) + all(>(0), W) || throw(ArgumentError("every data variance must be positive")) + s = 1 ./ sqrt.(W) + return H .* s, y .* s +end + +function _whitened(H::AbstractMatrix, y::AbstractVector, W::AbstractMatrix) + size(W) == (length(y), length(y)) || throw(DimensionMismatch( + "the data covariance is $(size(W)) for $(length(y)) values", + )) + L = LA.cholesky(LA.Symmetric(Matrix{Float64}(W))).L + return L \ Matrix{Float64}(H), L \ Vector{Float64}(y) +end + +""" + independent_pair_variance(joint::StructureFunction2DSumsAndCounts) -> Vector + +The variance of each distance bin's mean pair value under the assumption that the pairs are +independent: the variance of the pair values in the bin over the bin's count. Read from a +value-binned joint histogram (`InvariantValueAxis`), each value cell contributing its own mean, so +the spread inside a value cell is not seen and the result is a lower bound. A bin holding no pair is +`NaN`. This is the data covariance `W` the fits take. +""" +function independent_pair_variance(joint::SFO.StructureFunction2DSumsAndCounts) + nb = size(joint.sums, 1) + out = Vector{Float64}(undef, nb) + @inbounds for b in 1:nb + n = 0.0 + s1 = 0.0 + s2 = 0.0 + for v in axes(joint.sums, 2) + c = float(joint.counts[b, v]) + c > 0 || continue + m = joint.sums[b, v] / c + n += c + s1 += c * m + s2 += c * m * m + end + out[b] = n > 0 ? max(s2 / n - (s1 / n)^2, 0.0) / n : NaN + end + return out +end + +# --------------------------------------------------------------------------------------------------- +# Inversions +# --------------------------------------------------------------------------------------------------- + +""" + AbstractFitMethod + +How values on wavenumber bins are fitted to a structure function through a forward model. +""" +abstract type AbstractFitMethod end + +""" + RegularizedLeastSquares(prior) + +Regularised least squares with a Gaussian prior on the fitted values: for `y = H x + e`, `e` of +covariance `W` and a prior covariance `P`, + +```math +\\hat x = (Hᵀ W^{-1} H + P^{-1})^{-1} Hᵀ W^{-1} y, \\qquad C_{xx} = (Hᵀ W^{-1} H + P^{-1})^{-1} . +``` + +`prior` is the prior variance of each value (a vector), a full prior covariance matrix, or `nothing` +for no prior, which is ordinary weighted least squares. The data covariance `W` is required by the +fits taking this method; [`independent_pair_variance`](@ref) supplies one from a joint histogram, and +[`tradeoff_curve`](@ref) shows how the misfit and the norm of `x̂` trade against the prior. +""" +struct RegularizedLeastSquares{P} <: AbstractFitMethod + prior::P + function RegularizedLeastSquares(prior::P) where {P <: Union{Nothing, AbstractVector, AbstractMatrix}} + prior isa AbstractVector && !all(>(0), prior) && throw(ArgumentError( + "every prior variance must be positive", + )) + return new{P}(prior) + end +end + +""" + NonNegativeLeastSquares() + +Least squares with every fitted value constrained non-negative, by the Lawson–Hanson active-set +algorithm on the whitened system. For a flux that is the monotone-flux model, which cannot resolve a +sink; for a spectrum it is the constraint that a spectral density is non-negative. It returns no +covariance. +""" +struct NonNegativeLeastSquares <: AbstractFitMethod end + +""" + SegmentedPowerLaw(segments; slope_bounds = (-4.0, 1.0)) + +A shell spectrum that is a power law on each of `segments` wavenumber ranges, log-uniform between the +smallest and the largest wavenumber asked for, continuous at the breakpoints, with slopes held in +`slope_bounds` and a non-negative amplitude: `S + 1` parameters `(b₁, α₁, …, α_S)`. Fitted by bounded +Levenberg–Marquardt through `LsqFit` (`using LsqFit`), on the relative residual +`(S₂^{fit} - S₂)/S₂` when no data covariance is given. +""" +struct SegmentedPowerLaw <: AbstractFitMethod + segments::Int + slope_bounds::Tuple{Float64, Float64} + function SegmentedPowerLaw(segments::Integer; slope_bounds = (-4.0, 1.0)) + segments >= 1 || throw(ArgumentError("a segmented power law needs at least one segment")) + lo, hi = Float64(slope_bounds[1]), Float64(slope_bounds[2]) + lo < hi || throw(ArgumentError("the slope bounds must be ordered; got $slope_bounds")) + return new(Int(segments), (lo, hi)) + end +end + +"""`P⁻¹` of a prior given as variances, a matrix, or nothing (zero).""" +_prior_precision(::Nothing, n::Int) = zeros(Float64, n, n) +function _prior_precision(P::AbstractVector, n::Int) + length(P) == n || throw(DimensionMismatch("the prior names $(length(P)) variances for $n values")) + return LA.Diagonal(1 ./ Vector{Float64}(P)) +end +function _prior_precision(P::AbstractMatrix, n::Int) + size(P) == (n, n) || throw(DimensionMismatch("the prior covariance is $(size(P)) for $n values")) + return inv(LA.Symmetric(Matrix{Float64}(P))) +end + +""" + solve(method, H, y, W) -> (x, covariance) + +Fit `y = H x` by `method` under the data covariance `W`. [`RegularizedLeastSquares`](@ref) returns the +posterior covariance; [`NonNegativeLeastSquares`](@ref) returns `nothing` for it. +""" +function solve(m::RegularizedLeastSquares, H::AbstractMatrix, y::AbstractVector, W) + W === nothing && throw(ArgumentError( + "regularised least squares weighs the data by their covariance, which was not given; pass " * + "`W`, the variance of each structure-function value — `independent_pair_variance` reads one " * + "from a value-binned joint histogram — or a full covariance matrix", + )) + Hw, yw = _whitened(H, y, W) + n = size(H, 2) + A = LA.Symmetric(Hw' * Hw + _prior_precision(m.prior, n)) + C = inv(A) + x = C * (Hw' * yw) + return x, LA.Symmetric(C) +end + +function solve(::NonNegativeLeastSquares, H::AbstractMatrix, y::AbstractVector, W) + Hw, yw = _whitened(H, y, W) + return _nnls(Hw, yw), nothing +end + +""" + _nnls(A, b) -> x + +`argmin ‖A x − b‖₂` over `x ≥ 0` by the Lawson–Hanson active-set algorithm. +""" +function _nnls(A::AbstractMatrix, b::AbstractVector; maxiter::Int = 10 * size(A, 2)) + m, n = size(A) + length(b) == m || throw(DimensionMismatch("A is $(size(A)) and b has $(length(b)) entries")) + x = zeros(Float64, n) + passive = falses(n) + tol = 10 * eps(Float64) * max(LA.opnorm(A, 1), 1.0) * max(m, n) + w = A' * (b - A * x) + iter = 0 + while !all(passive) && maximum(w[.!passive]; init = -Inf) > tol && iter < maxiter + iter += 1 + j = argmax(ifelse.(passive, -Inf, w)) + passive[j] = true + s = zeros(Float64, n) + s[passive] = A[:, passive] \ b + while minimum(s[passive]; init = Inf) <= 0 + α = Inf + for i in 1:n + if passive[i] && s[i] <= 0 + α = min(α, x[i] / (x[i] - s[i])) + end + end + x .+= α .* (s .- x) + for i in 1:n + passive[i] && x[i] <= tol && (passive[i] = false; x[i] = 0) + end + s .= 0 + any(passive) && (s[passive] = A[:, passive] \ b) + any(passive) || break + end + x .= s + w = A' * (b - A * x) + end + return x +end + +# --------------------------------------------------------------------------------------------------- +# The segmented power law +# --------------------------------------------------------------------------------------------------- + +"""Log-uniform breakpoints, `S + 1` of them from `k_lo` to `k_hi`.""" +_segment_edges(k_lo::Real, k_hi::Real, S::Int) = exp.(range(log(k_lo), log(k_hi); length = S + 1)) + +""" + segmented_spectrum(p, k, edges) -> E(k) + +The continuous piecewise power law with parameters `p = (b₁, α₁, …, α_S)` on the segments `edges`: +`b_s k^{α_s}` on segment `s`, `b_{s+1} = b_s k_s^{α_s - α_{s+1}}` at each breakpoint. `k` outside the +segments takes the nearest end segment's law. +""" +function segmented_spectrum(p::AbstractVector, k::AbstractVector, edges::AbstractVector) + S = length(edges) - 1 + length(p) == S + 1 || throw(DimensionMismatch("$S segments take $(S + 1) parameters; got $(length(p))")) + T = promote_type(eltype(p), eltype(k)) + amps = Vector{T}(undef, S) + amps[1] = p[1] + for s in 1:(S - 1) + amps[s + 1] = amps[s] * T(edges[s + 1])^(p[s + 1] - p[s + 2]) + end + return [begin + s = clamp(searchsortedlast(edges, kq), 1, S) + amps[s] * T(kq)^p[s + 1] + end for kq in k] +end + +""" + _segmented_fit(method::SegmentedPowerLaw, ::Val{D}, r, y, W, k_lo, k_hi) + -> (p, covariance, edges, converged) + +The bounded Levenberg–Marquardt fit of the segmented power law; supplied by the LsqFit extension. +""" +function _segmented_fit(::SegmentedPowerLaw, ::Val, r, y, W, k_lo, k_hi) + throw(ArgumentError("fitting a segmented power law needs LsqFit: run `using LsqFit`")) +end + +""" + _segmented_design(::Val{D}, r, edges) -> (k, w, K) + +Quadrature nodes and weights over the segments — Gauss–Legendre on log-uniform panels of at most a +quarter octave, where a power law is close to linear — and the kernel matrix +`K[i, q] = 2 w_q [1 - kernel_D(k_q r_i)]`, so the model is `K * E(p)(k)` with `E` the spectrum at the +nodes. +""" +function _segmented_design(::Val{D}, r::AbstractVector, edges::AbstractVector) where {D} + panels = Float64[] + for s in 1:(length(edges) - 1) + n = max(1, ceil(Int, 4 * log2(edges[s + 1] / edges[s]))) + append!(panels, exp.(range(log(edges[s]), log(edges[s + 1]); length = n + 1))[1:end - 1]) + end + push!(panels, Float64(last(edges))) + k, w, _ = _bin_nodes(panels, last(r)) + K = Matrix{Float64}(undef, length(r), length(k)) + @inbounds for q in eachindex(k), i in eachindex(r) + K[i, q] = 2 * w[q] * (1 - isotropic_kernel(Val(D), k[q] * r[i])) + end + return k, w, K +end + +# --------------------------------------------------------------------------------------------------- +# Fits of result objects +# --------------------------------------------------------------------------------------------------- + +"""The separations and values a result holds, restricted to the bins with a value.""" +function _fit_samples(sf::SFO.AbstractStructureFunction) + r, vals, keep = _binned(sf) + isempty(keep) && throw(ArgumentError("no structure function value to fit")) + return r[keep], vals[keep], keep +end + +"""The data covariance over the bins holding a value, from one given over those bins or over all `n_all` bins.""" +_keep_variances(::Nothing, keep, n_all) = nothing +function _keep_variances(W::AbstractVector, keep, n_all) + length(W) == length(keep) && return Vector{Float64}(W) + length(W) == n_all && return Vector{Float64}(W[keep]) + throw(DimensionMismatch( + "the data covariance names $(length(W)) variances; the result holds $(length(keep)) values in $n_all bins", + )) +end +function _keep_variances(W::AbstractMatrix, keep, n_all) + size(W, 1) == size(W, 2) || throw(DimensionMismatch("a data covariance matrix must be square; got $(size(W))")) + size(W, 1) == length(keep) && return Matrix{Float64}(W) + size(W, 1) == n_all && return Matrix{Float64}(W[keep, keep]) + throw(DimensionMismatch( + "the data covariance is $(size(W)); the result holds $(length(keep)) values in $n_all bins", + )) +end + +""" + fit_spectrum(sf, k_edges, method, ::Val{D}; W = nothing) -> (k, E, covariance, …) + +The shell spectrum on the wavenumber bins `k_edges` that reproduces the second-order trace `sf` +through [`SpectrumForwardModel`](@ref), fitted by `method`. `W` is the data covariance: the variance +of each bin's value (a vector over the bins holding a value, or over all bins), or a full matrix. +Returns the bin centres `k`, the fitted `E` on the bins and the posterior `covariance` (`nothing` for +a method that gives none). A [`SegmentedPowerLaw`](@ref) returns `E` evaluated at `k`, and in +addition the fitted `parameters`, their `covariance`, the segment `breakpoints` and `converged`. +""" +function fit_spectrum(sf::SFO.AbstractStructureFunction, k_edges::AbstractVector, method::AbstractFitMethod, + ::Val{D}; W = nothing) where {D} + assert_invertible(sf.operator) + r, y, keep = _fit_samples(sf) + return _fit_spectrum(method, Val(D), r, y, k_edges, _keep_variances(W, keep, _value_count(sf))) +end + +function _fit_spectrum(method::AbstractFitMethod, ::Val{D}, r, y, k_edges, W) where {D} + model = SpectrumForwardModel(Val(D), r, k_edges) + x, C = solve(method, model.H, y, W) + return (k = _bin_centres(k_edges), E = x, covariance = C) +end + +function _fit_spectrum(method::SegmentedPowerLaw, ::Val{D}, r, y, k_edges, W) where {D} + _check_wavenumber_edges(k_edges) + p, C, edges, converged = _segmented_fit(method, Val(D), r, y, W, first(k_edges), last(k_edges)) + k = _bin_centres(k_edges) + return (k = k, E = segmented_spectrum(p, k, edges), covariance = C, parameters = p, + breakpoints = edges, converged = converged) +end + +""" + fit_helmholtz_spectra(L2, T2, k_edges, method; W = nothing) -> (k, E, B, covariance) + +The gradient (`E`) and curl (`B`) shell spectra on the bins `k_edges` that reproduce the longitudinal +and transverse second-order structure functions of a two-dimensional field through +[`HelmholtzForwardModel`](@ref). `L2` and `T2` share their bins; `W` covers the stacked values +`[D_LL; D_TT]` over the bins both hold (or over all bins of each). The `covariance` is over the +stacked `[E; B]`. +""" +function fit_helmholtz_spectra(L2::SFO.AbstractStructureFunction, T2::SFO.AbstractStructureFunction, + k_edges::AbstractVector, method::AbstractFitMethod; W = nothing) + _assert_projection(L2.operator, 2, 0, "longitudinal") + _assert_projection(T2.operator, 0, 2, "transverse") + r, dll, dtt = _paired_bins(L2, T2) + model = HelmholtzForwardModel(r, k_edges) + y = vcat(dll, dtt) + Wk = _stacked_variances(W, L2, T2, r) + x, C = solve(method, model.H, y, Wk) + nk = length(k_edges) - 1 + return (k = _bin_centres(k_edges), E = x[1:nk], B = x[(nk + 1):end], covariance = C) +end + +_stacked_variances(::Nothing, L2, T2, r) = nothing +function _stacked_variances(W::AbstractVector, L2, T2, r) + n = length(r) + length(W) == 2n && return Vector{Float64}(W) + _, _, ka = _binned(L2) + _, _, kb = _binned(T2) + keep = intersect(ka, kb) + nb = _value_count(L2) + length(W) == 2nb || throw(DimensionMismatch( + "the data covariance must cover the $(2n) stacked values the two results share, or the $(2nb) of every bin", + )) + return vcat(Float64.(W[keep]), Float64.(W[nb .+ keep])) +end +_stacked_variances(W::AbstractMatrix, L2, T2, r) = (size(W, 1) == 2length(r) || throw(DimensionMismatch( + "a full data covariance must cover the $(2length(r)) stacked values the two results share", +)); Matrix{Float64}(W)) + +_value_count(sf::SFO.StructureFunction) = length(sf.values) +_value_count(sf::SFO.StructureFunctionSumsAndCounts) = length(sf.sums) + +""" + fit_flux(sf, k_edges, method; W = nothing) -> (k, F, ξ, ε, covariance, flux_covariance) + +The piecewise-constant spectral energy flux that reproduces the third-order structure function +`sf = ⟨δu_L ‖δu‖²⟩` (`S3SFType`) of a two-dimensional isotropic flow through [`FluxForwardModel`](@ref). +`F` is the flux at the bin centres `k` (positive towards small scales), `ξ` the injection density on +the bins and `ε` the flux towards large scales below the first bin; `covariance` is over `(ε, ξ…)` +and `flux_covariance = G C Gᵀ` over `F`. +""" +function fit_flux(sf::SFO.AbstractStructureFunction, k_edges::AbstractVector, method::AbstractFitMethod; + W = nothing) + sf.operator isa SFT.S3SFType || throw(ArgumentError( + "the flux is fitted to ⟨δu_L ‖δu‖²⟩ (S3SFType); got $(nameof(typeof(sf.operator)))", + )) + r, y, keep = _fit_samples(sf) + model = FluxForwardModel(r, k_edges) + x, C = solve(method, model.H, y, _keep_variances(W, keep, _value_count(sf))) + F = model.G * x + CF = C === nothing ? nothing : LA.Symmetric(model.G * C * model.G') + return (k = _bin_centres(k_edges), F = F, ξ = x[2:end], ε = x[1], covariance = C, flux_covariance = CF) +end + +""" + tradeoff_curve(model, y, W, priors) -> (misfit, norm) + +For each prior in `priors` (each a prior variance shared by every value, or a vector of them), the +regularised least-squares fit of `y` through `model` under the data covariance `W`, reporting the +`W`-normalised misfit `‖W^{-1/2}(H x̂ - y)‖²` and `‖x̂‖₂`. The curve is returned for the caller to +choose from; nothing is chosen. +""" +function tradeoff_curve(model::AbstractForwardModel, y::AbstractVector, W, priors::AbstractVector) + H = forward_matrix(model) + n = size(H, 2) + Hw, yw = _whitened(H, y, W) + misfit = Vector{Float64}(undef, length(priors)) + norm = Vector{Float64}(undef, length(priors)) + for (i, p) in enumerate(priors) + prior = p isa AbstractVector ? p : fill(Float64(p), n) + x, _ = solve(RegularizedLeastSquares(prior), H, y, W) + misfit[i] = sum(abs2, Hw * x - yw) + norm[i] = LA.norm(x) + end + return (misfit = misfit, norm = norm) +end + +""" + select_segments(sf, k_edges, S_range, ::Val{D}; W = nothing, slope_bounds = (-4.0, 1.0)) + -> (segments, misfits, fits) + +Fit a [`SegmentedPowerLaw`](@ref) with each number of segments in `S_range` and report the one +minimising the mean relative misfit `mean(|S₂^{fit} - S₂| / S₂)`, with every misfit and every fit. +""" +function select_segments(sf::SFO.AbstractStructureFunction, k_edges::AbstractVector, S_range, ::Val{D}; + W = nothing, slope_bounds = (-4.0, 1.0)) where {D} + assert_invertible(sf.operator) + r, y, keep = _fit_samples(sf) + Wk = _keep_variances(W, keep, _value_count(sf)) + fits = [_fit_spectrum(SegmentedPowerLaw(S; slope_bounds), Val(D), r, y, k_edges, Wk) for S in S_range] + misfits = [begin + kq, _, K = _segmented_design(Val(D), r, f.breakpoints) + yfit = K * segmented_spectrum(f.parameters, kq, f.breakpoints) + sum(abs.(yfit .- y) ./ abs.(y)) / length(y) + end for f in fits] + best = argmin(misfits) + return (segments = collect(S_range)[best], misfits = misfits, fits = fits) +end diff --git a/src/Calculations/gpu_stubs.jl b/src/Calculations/gpu_stubs.jl index 99dbe66..e6ebe0e 100644 --- a/src/Calculations/gpu_stubs.jl +++ b/src/Calculations/gpu_stubs.jl @@ -8,8 +8,7 @@ # kernels run on CPU/AMD/whenever CUDA is not loaded. When both # KernelAbstractions and CUDA are loaded, StructureFunctionsCUDAExt adds # methods specialized on `CUDA.CUDABackend` that launch the N-body broadcast + -# (for 2D) dynamic-shared kernels and return `true`. See -# gpu/OPTIMAL_KERNEL_DESIGN.md for the settled design. +# (for 2D) dynamic-shared kernels and return `true`. """Try the CUDA fast 2D launch (N-body broadcast + privatized histogram, dynamic shared for large single-pass). Returns `true` if handled, `false` to fall back to @@ -29,8 +28,8 @@ gpu_fast_launch_1d_batch!(backend, out, cnt, x, u, sf_type, dist_dig, """ GPUDeviceCaps -What a GPU backend can actually offer, queried rather than assumed, so shared-memory strategy is -chosen per device instead of per hardcoded constant. Shared memory per block differs by an order of +What a GPU backend offers, queried at run time, so the shared-memory strategy is chosen per device. +Shared memory per block differs by an order of magnitude across parts a user may run on (V100 96 KiB, L40S 100 KiB, A100 163 KiB, later parts more), and the right accumulation strategy differs with it. @@ -53,10 +52,9 @@ struct GPUDeviceCaps end """ -Largest *static* shared allocation a block may declare. Measured, not assumed: on an A100 a static -`@localmem` of 48 KiB compiles and 64 KiB fails `ptxas`, while dynamic shared reaches the full -163 KiB opt-in. This is an architectural limit rather than a per-device one, so exceeding a device's -opt-in maximum is a separate check. +Largest *static* shared allocation a block may declare: on CUDA-class hardware a static `@localmem` +of 48 KiB compiles and 64 KiB fails `ptxas`, while dynamic shared reaches the full opt-in maximum. +The limit is architectural, not per-device, so a device's own opt-in maximum is a separate check. """ const GPU_SMEM_STATIC_MAX = 48 * 1024 @@ -77,7 +75,7 @@ if the device offers less than it. Bytes a dynamic-shared kernel should use per block. Expressed in device-relative terms — the opt-in ceiling, and the per-SM pool divided by an occupancy target — so the same rule sizes correctly on any -part rather than encoding one device's byte count. `target_blocks_per_sm` is the only free parameter +part, with no device's byte count written down. `target_blocks_per_sm` is the only free parameter and is dimensionless. """ @inline function gpu_dynamic_smem_budget(caps::GPUDeviceCaps; target_blocks_per_sm::Int = 2) @@ -88,10 +86,9 @@ end """ gpu_device_caps(backend) -> GPUDeviceCaps -Capabilities of `backend`. The default is deliberately the universal floor: a backend with no -override behaves exactly as the package did before device querying existed, so an unknown or future -backend degrades to "correct and portable" rather than to "assumes an A100". `StructureFunctionsCUDAExt` -overrides this with the real device attributes. +Capabilities of `backend`. The default is the universal floor, so a backend that overrides nothing +stays correct and portable. `StructureFunctionsCUDAExt` overrides it with the real device +attributes. """ gpu_device_caps(::Any) = GPUDeviceCaps(GPU_SMEM_UNIVERSAL_FLOOR, GPU_SMEM_UNIVERSAL_FLOOR, 1, 32) @@ -195,6 +192,12 @@ function gpu_calculate_structure_function_batch(args...; kwargs...) ) end +""" + gpu_calculate_structure_function_2d_batch(sf, backend, x, u, distance_bins, value_bins; kwargs...) + +The value-binned joint histogram of a field with auxiliary axes on a device, one histogram per +auxiliary slice; supplied by the KernelAbstractions extension. +""" function gpu_calculate_structure_function_2d_batch(args...; kwargs...) throw( ArgumentError( diff --git a/src/Calculations/gridded.jl b/src/Calculations/gridded.jl index ffdb918..74deb2b 100644 --- a/src/Calculations/gridded.jl +++ b/src/Calculations/gridded.jl @@ -5,7 +5,7 @@ """ AllValid() -Every cell holds a usable datum, as an indexable value rather than an absent one. +Every cell holds a usable datum, as an indexable value. Distinct from a grid's own mask, which says which cells *exist*: a cell can exist and still hold nothing, and it is the field that decides. [`field_validity`](@ref) combines the two. Spelling the @@ -17,21 +17,22 @@ struct AllValid end @inline Base.getindex(::AllValid, ::Integer) = true """ - field_validity(u, ::Val{D}[, cell_mask]) -> BitVector or AllValid + field_validity(u[, cell_mask]) -> BitVector or AllValid Which cells of `u` hold a usable datum: every component finite, and — where a `cell_mask` is given, -as a grid carries one — the cell marked as existing. +as a grid carries one — the cell marked as existing. `u` is `(components, cells...)` or a `Fields`. Returns [`AllValid`](@ref) when nothing is excluded, so a complete field costs nothing downstream. """ -function field_validity(u::AbstractArray, ::Val{D}, cell_mask = nothing) where {D} - n = length(u) ÷ D - uf = reshape(u, D, n) +function field_validity(u::AbstractArray, cell_mask = nothing) + W = size(u, 1) + n = length(u) ÷ W + uf = reshape(u, W, n) v = trues(n) any_invalid = false @inbounds for k in 1:n ok = true - for c in 1:D + for c in 1:W ok &= isfinite(uf[c, k]) end cell_mask === nothing || (ok &= cell_mask[k]) @@ -41,67 +42,352 @@ function field_validity(u::AbstractArray, ::Val{D}, cell_mask = nothing) where { return any_invalid ? v : AllValid() end +field_validity(f::MF.Fields, cell_mask = nothing) = field_validity(MF.packed(f), cell_mask) + +""" + NoWeights() + +Every pair counts once, as an indexable value: the unweighted sweep is the same kernel with the +weight folded away, as [`AllValid`](@ref) folds the mask away. """ - increment_tensor_value(sf, T, r̂) -> value +struct NoWeights end -The operator's summed value over a set of pairs, from that set's second-order increment tensor -`T[a,b] = Σ δu_a δu_b` and their shared separation direction. +""" + _pair_weights(weights, n, FT) -> NoWeights or Vector{FT} -Every operator that is a quadratic form in `δu` is a contraction of `T`, so a path that produces `T` -for many pairs at once — a correlation-theorem sweep, where `T` for every lag costs `O(M log M)` — -evaluates the operator without ever forming a pair. Anything not a quadratic form has no such -contraction and says so. +The per-cell pair weights a sweep multiplies by: `nothing` means none; a vector must hold one finite +weight per cell and is converted to the field's float type. """ -increment_tensor_value(sf::SFT.AbstractStructureFunctionType, T, r_hat) = throw(ArgumentError( - "$(typeof(sf)) is not a quadratic form in δu, so it is not a contraction of the second-order " * - "increment tensor. Use the lag sweep, which evaluates any pairwise operator exactly.", +_pair_weights(::Nothing, ::Int, ::Type) = NoWeights() +_pair_weights(w::NoWeights, ::Int, ::Type) = w +function _pair_weights(w::AbstractVector, n::Int, ::Type{FT}) where {FT} + length(w) == n || throw(DimensionMismatch("$(length(w)) weights for $n cells")) + all(isfinite, w) || throw(ArgumentError("every pair weight must be finite")) + return convert(Vector{FT}, w) +end + +"""Weighted pairs make the counts a weighted pair mass, which needs a floating-point count type.""" +_check_weighted_counts(::NoWeights, ::Type) = nothing +_check_weighted_counts(::AbstractVector, ::Type{CT}) where {CT} = CT <: AbstractFloat ? nothing : throw(ArgumentError( + "pair weights make the counts a weighted pair mass, which the count type $CT cannot hold; pass count_eltype = Float64, or Float64 counts", )) -@inline increment_tensor_value(::SFT.SecondOrderStructureFunctionType, T, r_hat) = LA.tr(T) +""" + cell_measure(grid) -> Vector + +The measure — length, area or volume — of every cell of `grid`, in the cell order the gridded entries +use. As `weights = cell_measure(grid)` it makes a structure function an area average. Supplied by the +FlowGeometries extension. +""" +function cell_measure end + +""" + _packed(u) -> (data, Val(D), Val(V), Val(K)) -@inline increment_tensor_value(::SFT.ProjectedStructureFunctionType{2, 0}, T, r_hat) = - LA.dot(r_hat, T, r_hat) +The one form every gridded kernel indexes: the `(V·D + K, cells)` matrix of a field with its field +layout as type parameters. A bare `(D, cells...)` array is one vector field of width `D`. +""" +@inline _packed(f::MF.Fields{D, V, K}) where {D, V, K} = (MF.packed(f), Val(D), Val(V), Val(K)) + +function _packed(u::AbstractArray) + D = size(u, 1) + return (reshape(u, D, :), Val(D), Val(1), Val(0)) +end -@inline increment_tensor_value(::SFT.ProjectedStructureFunctionType{0, 2}, T, r_hat) = - LA.tr(T) - LA.dot(r_hat, T, r_hat) +""" + _check_grid_field(sf, data, schedule, ::Val{D}, ::Val{V}, ::Val{K}) -@inline function increment_tensor_value( - ::SFT.TransverseComponentSecondOrderStructureFunctionType, T, r_hat, -) - D = length(r_hat) - D > 1 || throw(ArgumentError( - "T2ComponentSF averages over the transverse directions, of which there are none at D = 1", +The operator reads only fields the field carries; the packed field is `(V·D + K, n_cells)`; and a +field carrying vector fields has at least one component per grid direction, so that a lag has a +component to lie along. +""" +function _check_grid_field(sf, data::AbstractMatrix, s, ::Val{D}, ::Val{V}, ::Val{K}) where {D, V, K} + validate_fields(sf, Val(V), Val(K)) + Dg = grid_dimension(s) + (V == 0 || D >= Dg) || throw(ArgumentError( + "the field has $D components but the grid has $Dg directions; a lag needs a component per " * + "direction", )) - return (LA.tr(T) - LA.dot(r_hat, T, r_hat)) / (D - 1) + size(data, 1) == V * D + K || throw(DimensionMismatch( + "field has $(size(data, 1)) components, declared $V vector field(s) of width $D and $K " * + "scalar field(s), $(V * D + K) components", + )) + size(data, 2) == n_cells(s) || throw(DimensionMismatch( + "field holds $(size(data, 2)) cells, the grid $(n_cells(s))", + )) + return nothing +end + +"""The width a lag direction is expressed in: the vector fields' width, or the grid's without any.""" +@inline _direction_width(::Val{D}, ::Val{V}, ::Val{Dg}) where {D, V, Dg} = Val(V == 0 ? Dg : D) + +"""One pair's increment from the packed field: the plain vector for one vector field, else a multi-field.""" +@inline _lag_increment(::Val{D}, ::Val{1}, ::Val{0}, data::AbstractMatrix{T}, k, kp) where {D, T} = + SA.SVector{D, T}(ntuple(c -> @inbounds(data[c, kp] - data[c, k]), Val(D))) + +@inline function _lag_increment( + ::Val{D}, ::Val{V}, ::Val{K}, data::AbstractMatrix{T}, k, kp, +) where {D, V, K, T} + vectors = ntuple(Val(V)) do a + o = (a - 1) * D + SA.SVector{D, T}(ntuple(d -> @inbounds(data[o + d, kp] - data[o + d, k]), Val(D))) + end + scalars = ntuple(c -> @inbounds(data[V * D + c, kp] - data[V * D + c, k]), Val(K)) + return MF.FieldIncrement{D, V, K, T}(vectors, scalars) +end + +"""Split a transported packed increment into what the operator reads.""" +@inline _split_increment(::Val{D}, ::Val{1}, ::Val{0}, δ::SA.SVector{D}) where {D} = δ + +@inline function _split_increment(::Val{D}, ::Val{V}, ::Val{K}, δ::SA.SVector{W, T}) where {D, V, K, W, T} + vectors = ntuple(Val(V)) do a + o = (a - 1) * D + SA.SVector{D, T}(ntuple(d -> @inbounds(δ[o + d]), Val(D))) + end + scalars = ntuple(c -> @inbounds(δ[V * D + c]), Val(K)) + return MF.FieldIncrement{D, V, K, T}(vectors, scalars) end -"""Whether [`increment_tensor_value`](@ref) has a contraction for this operator.""" -@inline is_quadratic_operator(sf::SFT.AbstractStructureFunctionType) = false -@inline is_quadratic_operator(::SFT.SecondOrderStructureFunctionType) = true -@inline is_quadratic_operator(::SFT.ProjectedStructureFunctionType{2, 0}) = true -@inline is_quadratic_operator(::SFT.ProjectedStructureFunctionType{0, 2}) = true -@inline is_quadratic_operator(::SFT.TransverseComponentSecondOrderStructureFunctionType) = true +@inline _pair_value(sf, δu::SA.SVector, dx, r2) = SFT._sf_raw(sf, δu, dx, r2) +@inline _pair_value(sf, δu::MF.FieldIncrement, dx, r2) = sf(δu, dx / sqrt(r2)) + +# Which end of a lag's pairs is read first: the sign of the displacement along the first direction +# that separates the ends — unless that direction half-turns, when neither end comes first (see +# `pair_orientation`). An operator odd in a scalar increment takes this as a factor; the rest see 1. +@inline function _lag_orientation(dx, amb::NTuple{Dg, Bool}) where {Dg} + @inbounds for d in eachindex(dx) + iszero(dx[d]) && continue + return (d <= Dg && amb[d]) ? 0 : (dx[d] > 0 ? 1 : -1) + end + return 0 +end + +# --------------------------------------------------------------------------------------------------- +# Entry points +# --------------------------------------------------------------------------------------------------- + """ - gridded_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}, spectral_backend) + gridded_sweep!(sums, counts, sf, u, schedule, distance_bins[, axis_bins], ::Val{D}, spectral_backend; valid, weights, backend) + gridded_sweep!(sums, counts, sf, fields, schedule, distance_bins[, axis_bins], spectral_backend; valid, weights, backend) Accumulate the histogram of every pair `schedule` names, by the algorithm `spectral_backend` selects. +`valid` and `weights` are as on [`gridded_lag_sweep!`](@ref). Which algorithm sums the pairs is an axis of its own, orthogonal to which hardware runs it: the lag -sweep visits each lag and is exact for any pairwise operator, while a transform produces the -second-order increment tensor for every lag at once and so serves the operators that are quadratic -forms in `δu`. `AutoSpectralBackend` picks whichever does less work, and resolves to the lag sweep -unless a transform is loaded — an extension supplies the transform, and answers `Auto` with a cost -comparison because only it knows what a transform would cost. -""" -function gridded_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}, - spectral_backend; valid = AllValid()) where {D} - throw(ArgumentError( - "no method sums a gridded calculation with $(typeof(spectral_backend)). Load the package " * - "that supplies it — `using SpectralBackends` for the direct sum, and additionally an " * - "AbstractFFTs implementation (`using FFTW` on CPU) for a transform. Omitting the argument " * - "sweeps the lags, which needs neither.", - )) +sweep visits each lag and is exact for any pairwise operator, while a transform produces the increment +moment tensor of every lag at once and so serves the operators that are polynomials in `δu`. +`AutoSpectralBackend` picks whichever does less work, and resolves to the lag sweep unless a transform +is loaded — an extension supplies the transform, and answers `Auto` with a cost comparison because +only it knows what a transform would cost. `backend` names the hardware, as on the unstructured entry. + +With `axis_bins` the histogram is joint in separation and the angle a [`SeparationAngleAxis`](@ref) +reads from each lag; `sums` and `counts` are then `(n_distance, n_angle)`. +""" +gridded_sweep!(sums::AbstractVector, counts::AbstractVector, sf, data::AbstractMatrix, schedule, distance_bins, + ::Val{D}, ::Val{V}, ::Val{K}, ::Union{SB.AbstractDirectSumSpectralBackend, SB.AbstractAutoSpectralBackend}; kwargs...) where {D, V, K} = + gridded_lag_sweep!(sums, counts, sf, data, schedule, distance_bins, Val(D), Val(V), Val(K); kwargs...) + +gridded_sweep!(sums::AbstractMatrix, counts::AbstractMatrix, sf, data::AbstractMatrix, schedule, distance_bins, + axis_bins, ::Val{D}, ::Val{V}, ::Val{K}, ::Union{SB.AbstractDirectSumSpectralBackend, SB.AbstractAutoSpectralBackend}; kwargs...) where {D, V, K} = + gridded_lag_sweep!(sums, counts, sf, data, schedule, distance_bins, axis_bins, Val(D), Val(V), Val(K); kwargs...) + +gridded_sweep!(::AbstractVector, ::AbstractVector, sf, ::AbstractMatrix, schedule, distance_bins, ::Val{D}, ::Val{V}, + ::Val{K}, tag::SB.AbstractSpectralBackend; kwargs...) where {D, V, K} = _no_transform_loaded(tag, schedule) + +gridded_sweep!(::AbstractMatrix, ::AbstractMatrix, sf, ::AbstractMatrix, schedule, distance_bins, axis_bins, ::Val{D}, + ::Val{V}, ::Val{K}, tag::SB.AbstractSpectralBackend; kwargs...) where {D, V, K} = + _no_transform_loaded(tag, schedule) + +gridded_sweep!(::AbstractVector, ::AbstractVector, sf, ::AbstractMatrix, schedule, distance_bins, ::Val{D}, ::Val{V}, + ::Val{K}, spectral_backend; kwargs...) where {D, V, K} = _not_a_spectral_tag(spectral_backend) + +gridded_sweep!(::AbstractMatrix, ::AbstractMatrix, sf, ::AbstractMatrix, schedule, distance_bins, axis_bins, ::Val{D}, + ::Val{V}, ::Val{K}, spectral_backend; kwargs...) where {D, V, K} = _not_a_spectral_tag(spectral_backend) + +_not_a_spectral_tag(x) = throw(ArgumentError( + "spectral_backend must be a SpectralBackends tag — AutoSpectralBackend(), DirectSumSpectralBackend(), " * + "FastFourierTransformSpectralBackend() or a non-uniform FFT tag; got $(typeof(x)). Omitting it sweeps the lags.", +)) + +# The array and `Fields` forms of both sweeps route through `_packed`, so every kernel sees one layout. +function gridded_sweep!(sums::AbstractVector, counts::AbstractVector, sf, u::AbstractArray, schedule, + distance_bins, ::Val{D}, spectral_backend; kwargs...) where {D} + size(u, 1) == D || throw(DimensionMismatch("field has $(size(u, 1)) components, declared $D")) + return gridded_sweep!(sums, counts, sf, reshape(u, D, :), schedule, distance_bins, Val(D), Val(1), + Val(0), spectral_backend; kwargs...) +end + +gridded_sweep!(sums::AbstractVector, counts::AbstractVector, sf, f::MF.Fields{D, V, K}, schedule, + distance_bins, spectral_backend; kwargs...) where {D, V, K} = + gridded_sweep!(sums, counts, sf, MF.packed(f), schedule, distance_bins, Val(D), Val(V), Val(K), + spectral_backend; kwargs...) + +function gridded_sweep!(sums::AbstractMatrix, counts::AbstractMatrix, sf, u::AbstractArray, schedule, + distance_bins, axis_bins, ::Val{D}, spectral_backend; kwargs...) where {D} + size(u, 1) == D || throw(DimensionMismatch("field has $(size(u, 1)) components, declared $D")) + return gridded_sweep!(sums, counts, sf, reshape(u, D, :), schedule, distance_bins, axis_bins, + Val(D), Val(1), Val(0), spectral_backend; kwargs...) +end + +gridded_sweep!(sums::AbstractMatrix, counts::AbstractMatrix, sf, f::MF.Fields{D, V, K}, schedule, + distance_bins, axis_bins, spectral_backend; kwargs...) where {D, V, K} = + gridded_sweep!(sums, counts, sf, MF.packed(f), schedule, distance_bins, axis_bins, Val(D), Val(V), + Val(K), spectral_backend; kwargs...) + +function gridded_lag_sweep!(sums::AbstractVector, counts::AbstractVector, sf, u::AbstractArray, + schedule, distance_bins, ::Val{D}; kwargs...) where {D} + size(u, 1) == D || throw(DimensionMismatch("field has $(size(u, 1)) components, declared $D")) + return gridded_lag_sweep!(sums, counts, sf, reshape(u, D, :), schedule, distance_bins, Val(D), + Val(1), Val(0); kwargs...) +end + +gridded_lag_sweep!(sums::AbstractVector, counts::AbstractVector, sf, f::MF.Fields{D, V, K}, schedule, + distance_bins; kwargs...) where {D, V, K} = + gridded_lag_sweep!(sums, counts, sf, MF.packed(f), schedule, distance_bins, Val(D), Val(V), Val(K); + kwargs...) + +function gridded_lag_sweep!(sums::AbstractMatrix, counts::AbstractMatrix, sf, u::AbstractArray, + schedule, distance_bins, axis_bins, ::Val{D}; kwargs...) where {D} + size(u, 1) == D || throw(DimensionMismatch("field has $(size(u, 1)) components, declared $D")) + return gridded_lag_sweep!(sums, counts, sf, reshape(u, D, :), schedule, distance_bins, axis_bins, + Val(D), Val(1), Val(0); kwargs...) +end + +gridded_lag_sweep!(sums::AbstractMatrix, counts::AbstractMatrix, sf, f::MF.Fields{D, V, K}, schedule, + distance_bins, axis_bins; kwargs...) where {D, V, K} = + gridded_lag_sweep!(sums, counts, sf, MF.packed(f), schedule, distance_bins, axis_bins, Val(D), + Val(V), Val(K); kwargs...) + +# --------------------------------------------------------------------------------------------------- +# Schedules with a uniform direction +# --------------------------------------------------------------------------------------------------- + +""" + AbstractSeparableSchedule + +A pair enumeration with at least one uniform direction. The cells factor into *slabs*, one per index +on the remaining directions, and within a pair of slabs every pair of cells is named by an integer +lag along the uniform directions. Both sweeps run over `(slab, slab, lag)`: the direct one reduces +the field over each lag, the transform produces every lag of a slab pair at once. + +A schedule provides [`uniform_axes`](@ref), [`n_slabs`](@ref), `enumerated_pairs`, +[`separable_layout`](@ref), `lag_limits`, [`lag_transport`](@ref) and `lag_frame`. +""" +abstract type AbstractSeparableSchedule end + +# A transform's tag with no transform loaded: a separable schedule wants the AbstractFFTs extension; any +# other schedule has no lag to transform along. +_no_transform_loaded(tag, ::AbstractSeparableSchedule) = throw(ArgumentError( + "$(typeof(tag)) needs a transform this session has not loaded: `using FFTW: FFTW` on CPU, or another AbstractFFTs " * + "implementation, supplies it for every grid with a uniform direction. DirectSumSpectralBackend and " * + "AutoSpectralBackend need none.", +)) + +_no_transform_loaded(tag, schedule) = throw(ArgumentError( + "$(typeof(tag)) transforms along a uniform direction, and a $(nameof(typeof(schedule))) has none: its pairs " * + "share no lag. Omit the tag, or pass DirectSumSpectralBackend or AutoSpectralBackend, to enumerate the pairs.", +)) + +""" + IdentityTransport() + FrameTransport() + +How the two ends of a pair are compared. Under `IdentityTransport` the increment is the plain +difference `u(J, i+h) - u(I, i)` and the lag's displacement is its direction. Under `FrameTransport` +each end is first expressed in the pair's own frame, `B·u(J, i+h) - A·u(I, i)` with `W×W` matrices +fixed by the lag, and the longitudinal direction is `ê₁`. +""" +abstract type AbstractLagTransport end + +"""The transport of a flat schedule: the increment is the plain difference and the lag's displacement its direction; see [`AbstractLagTransport`](@ref).""" +struct IdentityTransport <: AbstractLagTransport end + +"""The transport of a curved schedule: each end is expressed in the pair's own frame before differencing; see [`AbstractLagTransport`](@ref).""" +struct FrameTransport <: AbstractLagTransport end + +""" + uniform_axes(schedule) -> UniformLagSchedule + +The uniform directions, in the order they run within a slab. +""" +function uniform_axes end + +""" + n_slabs(schedule) -> Int + +How many slabs the cells factor into; one for a schedule whose every direction is uniform. +""" +function n_slabs end + +""" + enumerated_pairs(schedule, r_max) + +The slab pairs `(I, J)`, `I ≤ J`, whose cells can come within `r_max` of each other. +""" +function enumerated_pairs end + +""" + separable_layout(schedule, data, valid, weights) -> (data, valid, weights) + +The packed field, its validity and its pair weights with slab `I` occupying columns +`(I-1)·N_u + 1 : I·N_u`, `N_u` the cells of a slab, and the uniform directions running column-major +within it. +""" +function separable_layout end + +""" + lag_limits(schedule, I, J, r_max) -> NTuple{Du, Int} + lag_limits(schedule, r_max) -> NTuple{Du, Int} + +The largest `|h_d|` along each uniform direction at which a pair of the two slabs can still lie +within `r_max`; the two-argument form bounds it over every slab pair. +""" +function lag_limits end + +""" + uniform_lag_box(schedule) -> Bool + +Whether [`lag_limits`](@ref)`(schedule, I, J, r_max)` is the same box for every slab pair, so a device +launch indexes its work items by division on one box. A schedule that answers `false` carries one box +per pair, and the launch is indexed through the prefix sum of their volumes. +""" +uniform_lag_box(::AbstractSeparableSchedule) = true + +""" + lag_transport(schedule) -> AbstractLagTransport + +See [`IdentityTransport`](@ref). +""" +function lag_transport end + +""" + lag_frame(schedule, I, J, h, ::Val{D}, ::Val{V}, ::Val{K}) -> (ok, r2, factor, geometry) + +The pairs lag `h` names between slabs `I` and `J`: whether their separation direction is defined, +their squared separation, the reading factor for operators odd in a scalar increment, and the +geometry [`with_frames`](@ref) turns into one `(dir, A, B)` frame per equal-length displacement. +""" +function lag_frame end + +""" + with_frames(f, transport, geometry) + +Call `f(frames)` with the lag's frames as a tuple whose length is a type parameter. `dir` is the +displacement under `IdentityTransport` and the unit longitudinal direction `ê₁` under +`FrameTransport`; `A`, `B` are the transport matrices, `nothing` where there are none. +""" +@inline function with_frames(f, ::IdentityTransport, g) + return _with_images(g.dx, g.amb) do images + f(map(_identity_frame, images)) + end +end + +@inline _identity_frame(dx) = (dir = dx, A = nothing, B = nothing) + +@inline function with_frames(f, ::FrameTransport, g) + g.two || return f(((dir = g.dir, A = g.A, B = g.B),)) + return f(((dir = g.dir, A = g.A, B = g.B), (dir = g.dir, A = g.A2, B = g.B2))) end """ @@ -116,7 +402,7 @@ the trailing axes of the field the schedule is swept over. `spacing` is signed, as a descending axis reports it; only its magnitude enters a separation. """ -struct UniformLagSchedule{Dg, T} +struct UniformLagSchedule{Dg, T} <: AbstractSeparableSchedule dims::NTuple{Dg, Int} spacing::NTuple{Dg, T} periodic::NTuple{Dg, Bool} @@ -124,6 +410,10 @@ end """Cells the schedule covers.""" @inline n_grid_cells(s::UniformLagSchedule) = prod(s.dims) +@inline n_cells(s::UniformLagSchedule) = prod(s.dims) + +"""Directions the schedule's lags span.""" +@inline grid_dimension(::UniformLagSchedule{Dg}) where {Dg} = Dg """Flat-index stride of each direction in a field stored `(component, cells...)`.""" @inline function grid_strides(s::UniformLagSchedule{Dg}) where {Dg} @@ -136,19 +426,24 @@ end end end +"""The largest `|h|` along direction `d` whose displacement stays within `r_max`.""" +@inline function _lag_limit(s::UniformLagSchedule, d::Integer, r_max) + step = abs(@inbounds s.spacing[d]) + return (isfinite(r_max) && step > 0) ? floor(Int, r_max / step) : typemax(Int) +end + """ - lag_range(schedule, d, r_max) + lag_range(schedule, d, lim::Integer) + lag_range(schedule, d, r_max::AbstractFloat) -Representative lags along direction `d`, one per distinct separation, bounded by `r_max`. +Representative lags along direction `d`, one per distinct separation, with `|h| ≤ lim`. A periodic direction of `n` cells has exactly `n` distinct offsets, and its representatives are taken in `-((n-1)÷2):(n÷2)`, so each is the minimum image and its magnitude is the true separation. A bounded direction reaches `±(n-1)`. """ -@inline function lag_range(s::UniformLagSchedule, d::Integer, r_max) +@inline function lag_range(s::UniformLagSchedule, d::Integer, lim::Integer) n = @inbounds s.dims[d] - step = abs(@inbounds s.spacing[d]) - lim = (isfinite(r_max) && step > 0) ? floor(Int, r_max / step) : typemax(Int) @inbounds if s.periodic[d] return (-min((n - 1) ÷ 2, lim)):min(n ÷ 2, lim) end @@ -156,11 +451,35 @@ A bounded direction reaches `±(n-1)`. return (-m):m end +@inline lag_range(s::UniformLagSchedule, d::Integer, r_max::AbstractFloat) = + lag_range(s, d, _lag_limit(s, d, r_max)) + +@inline uniform_axes(s::UniformLagSchedule) = s +@inline n_slabs(::UniformLagSchedule) = 1 +@inline enumerated_pairs(::UniformLagSchedule, r_max) = ((1, 1),) +@inline separable_layout(::UniformLagSchedule, data, valid, weights) = (data, valid, weights) +@inline lag_limits(s::UniformLagSchedule{Dg}, r_max) where {Dg} = + ntuple(d -> _lag_limit(s, d, r_max), Val(Dg)) +@inline lag_limits(s::UniformLagSchedule, I, J, r_max) = lag_limits(s, r_max) +@inline lag_transport(::UniformLagSchedule) = IdentityTransport() + +@inline function lag_frame( + s::UniformLagSchedule{Dg}, I, J, h::NTuple{Dg, Int}, ::Val{D}, ::Val{V}, ::Val{K}, +) where {Dg, D, V, K} + dx = _lag_displacement(s, h, _direction_width(Val(D), Val(V), Val(Dg))) + amb = _ambiguous_dirs(s, h) + return true, LA.dot(dx, dx), _lag_orientation(dx, amb), (dx = dx, amb = amb) +end + # The representative of `-h`. A periodic direction of even length has one half-turn offset that is # its own reverse, and a lag built only from those names each pair twice. @inline _lag_negate(s::UniformLagSchedule, d::Integer, h::Integer) = @inbounds (s.periodic[d] && iseven(s.dims[d]) && h == s.dims[d] ÷ 2) ? h : -h +"""The displacement a lag names, in the direction width `Dr`, zero along directions the grid lacks.""" +@inline _lag_displacement(s::UniformLagSchedule{Dg, T}, h::NTuple{Dg, Int}, ::Val{Dr}) where {Dg, T, Dr} = + SA.SVector{Dr, T}(ntuple(d -> d <= Dg ? T(h[d]) * @inbounds(s.spacing[d]) : zero(T), Val(Dr))) + """ _lag_segments(schedule, d, h, half) -> ((range, offset), (range, offset)) @@ -222,49 +541,288 @@ the `K` directions the lag half-turns. `K = 0` gives `dx` alone. end """ - _lag_reduce_images(sf, u_flat, ::Val{D}, ::Val{Dg}, schedule, strides, h, dx, r2, half_dim, amb) + _with_images(f, dx, ambiguous) + +Call `f(images)` with the lag's equal-length displacements as a tuple whose length is a type +parameter: the half-turn count is a value, and the counts a grid can produce are spelled out so each +resolves to its own `Val`. +""" +@generated function _with_images(f, dx, amb::NTuple{Dg, Bool}) where {Dg} + branches = [:(K == $k && return f(_lag_images(dx, amb, Val($k)))) for k in 0:(Dg - 1)] + return quote + K = count(amb) + $(branches...) + return f(_lag_images(dx, amb, Val($Dg))) + end +end + +""" + RectilinearLagSchedule(uniform, enumerated, axis_order) + +Lag enumeration for a rectilinear grid with some uniform directions and some given as coordinate +lists. `uniform` describes the uniform directions, `enumerated` holds one coordinate vector per +remaining direction, and `axis_order[k]` is the field direction at position `k` of +`(uniform..., enumerated...)`. + +Every pair of enumerated indices is a pair of slabs, within which the pairs are named by lags along +the uniform directions exactly as on a uniform grid; an enumerated direction never wraps. +""" +struct RectilinearLagSchedule{Du, De, N, T, C <: NTuple{De, AbstractVector{T}}} <: AbstractSeparableSchedule + uniform::UniformLagSchedule{Du, T} + enumerated::C + axis_order::NTuple{N, Int} + positions::NTuple{N, Int} + function RectilinearLagSchedule( + uniform::UniformLagSchedule{Du, T}, enumerated::C, axis_order::NTuple{N, Int}, + ) where {Du, T, De, C <: NTuple{De, AbstractVector{T}}, N} + N == Du + De || throw(DimensionMismatch( + "$Du uniform and $De enumerated directions, but axis_order names $N", + )) + sort(collect(axis_order)) == 1:N || throw(ArgumentError( + "axis_order must be a permutation of 1:$N; got $axis_order", + )) + positions = ntuple(d -> findfirst(==(d), axis_order)::Int, Val(N)) + return new{Du, De, N, T, C}(uniform, enumerated, axis_order, positions) + end +end + +@inline _enumerated_dims(s::RectilinearLagSchedule) = map(length, s.enumerated) +@inline n_slabs(s::RectilinearLagSchedule) = prod(_enumerated_dims(s)) +@inline n_cells(s::RectilinearLagSchedule) = n_cells(s.uniform) * n_slabs(s) +@inline grid_dimension(::RectilinearLagSchedule{Du, De, N}) where {Du, De, N} = N +@inline uniform_axes(s::RectilinearLagSchedule) = s.uniform +@inline lag_limits(s::RectilinearLagSchedule, r_max) = lag_limits(s.uniform, r_max) +@inline lag_limits(s::RectilinearLagSchedule, I, J, r_max) = lag_limits(s.uniform, r_max) +@inline lag_transport(::RectilinearLagSchedule) = IdentityTransport() + +"""The grid's cell counts in field order.""" +@inline function _field_dims(s::RectilinearLagSchedule{Du, De, N}) where {Du, De, N} + return ntuple(Val(N)) do d + k = @inbounds s.positions[d] + k <= Du ? (@inbounds s.uniform.dims[k]) : length(@inbounds s.enumerated[k - Du]) + end +end + +function separable_layout(s::RectilinearLagSchedule{Du, De, N}, data::AbstractMatrix, valid, weights) where {Du, De, N} + s.axis_order == ntuple(identity, Val(N)) && return data, valid, weights + dims = _field_dims(s) + W = size(data, 1) + perm = (1, (s.axis_order .+ 1)...) + dp = reshape(permutedims(reshape(data, W, dims...), perm), W, :) + vp = valid isa AllValid ? valid : vec(permutedims(reshape(valid, dims), s.axis_order)) + wp = weights isa NoWeights ? weights : vec(permutedims(reshape(weights, dims), s.axis_order)) + return dp, vp, wp +end + +# Squared distance between two slabs' enumerated coordinates; no pair of theirs is closer. +@inline function _slab_gap2(s::RectilinearLagSchedule{Du, De}, I::Int, J::Int) where {Du, De} + ce = CartesianIndices(_enumerated_dims(s)) + cI, cJ = ce[I], ce[J] + acc = zero(eltype(s.enumerated[1])) + @inbounds for e in 1:De + δ = s.enumerated[e][cJ[e]] - s.enumerated[e][cI[e]] + acc += δ * δ + end + return acc +end + +function enumerated_pairs(s::RectilinearLagSchedule, r_max) + n = n_slabs(s) + bound = r_max * r_max + return ((I, J) for I in 1:n for J in I:n if _slab_gap2(s, I, J) <= bound) +end + +@inline function lag_frame( + s::RectilinearLagSchedule{Du, De, N, T}, I, J, h::NTuple{Du, Int}, ::Val{D}, ::Val{V}, ::Val{K}, +) where {Du, De, N, T, D, V, K} + su = s.uniform + ce = CartesianIndices(_enumerated_dims(s)) + cI, cJ = ce[I], ce[J] + # displacement and half-turn flags in slab order, then in the field's order + dxp = ntuple(Val(N)) do k + if k <= Du + T(h[k]) * @inbounds(su.spacing[k]) + else + e = k - Du + @inbounds s.enumerated[e][cJ[e]] - s.enumerated[e][cI[e]] + end + end + ambp = _ambiguous_dirs(su, h) + dx = _ordered_displacement(dxp, s.positions, _direction_width(Val(D), Val(V), Val(N))) + amb = ntuple(d -> (k = @inbounds(s.positions[d]); k <= Du && @inbounds(ambp[k])), Val(N)) + return true, LA.dot(dx, dx), _lag_orientation(dx, amb), (dx = dx, amb = amb) +end + +@inline function _ordered_displacement(dxp::Tuple, positions::NTuple{N, Int}, ::Val{Dr}) where {N, Dr} + T = eltype(dxp) + return SA.SVector{Dr, T}(ntuple(d -> d <= N ? (@inbounds dxp[positions[d]]) : zero(T), Val(Dr))) +end + +# --------------------------------------------------------------------------------------------------- +# Work partition and execution +# --------------------------------------------------------------------------------------------------- + +""" + sweep_items(schedule, r_max, n_tasks, split_lags) -> Vector{NTuple{4, Int}} -[`_lag_reduce`](@ref) with the lag's equal-length displacements built first. The half-turn count is a -value, so it is resolved to a type parameter here — the counts a grid can produce are spelled out, -and any wider one still resolves through the same expression. +The independent units a sweep is split into: `(I, J, part, n_parts)` names slab pair `(I, J)` and, +with `split_lags`, the `part`-th of `n_parts` round-robin shares of its lags. A schedule with fewer +slab pairs than `n_tasks` splits each pair's lags so every task has work. """ -@inline function _lag_reduce_images( - sf, u_flat, valid, ::Val{D}, ::Val{Dg}, s, strides, h, dx, r2, half_dim::Int, - amb::NTuple{Dg, Bool}, -) where {D, Dg} - go(vk) = _lag_reduce(sf, u_flat, valid, Val(D), Val(Dg), s, strides, h, - _lag_images(dx, amb, vk), r2, half_dim) - K = count(amb) - K == 0 && return go(Val(0)) - K == 1 && return go(Val(1)) - K == 2 && return go(Val(2)) - K == 3 && return go(Val(3)) - return go(Val(K)) +function sweep_items(s::AbstractSeparableSchedule, r_max, n_tasks::Int, split_lags::Bool) + pairs = collect(enumerated_pairs(s, r_max)) + n_parts = (split_lags && length(pairs) < n_tasks && !isempty(pairs)) ? cld(n_tasks, length(pairs)) : 1 + items = Vector{NTuple{4, Int}}(undef, length(pairs) * n_parts) + k = 0 + for (I, J) in pairs, part in 1:n_parts + items[k += 1] = (I, J, part, n_parts) + end + return items end """ - _lag_reduce(sf, u_flat, ::Val{D}, ::Val{Dg}, schedule, strides, h, images, r2, half_dim) - -> (sum, n_pairs) + sweep_reduce!(sums, counts, backend, items, make_scratch, body!) + +Run `body!(sums, counts, item, scratch)` over every item on `backend`; a threaded backend gives each +task private histograms and its own `make_scratch()`, and adds the partials into `sums`/`counts`. +""" +function sweep_reduce!(sums, counts, ::CB.AbstractSerialBackend, items, make_scratch, body!) + scratch = make_scratch() + for it in items + body!(sums, counts, it, scratch) + end + return nothing +end + +sweep_reduce!(sums, counts, ::CB.AbstractThreadedBackend, items, make_scratch, body!) = + threaded_sweep_reduce!(sums, counts, items, make_scratch, body!) + +function sweep_reduce!(sums, counts, ::CB.AbstractAutoBackend, items, make_scratch, body!) + _gridded_threads() > 1 && return threaded_sweep_reduce!(sums, counts, items, make_scratch, body!) + return sweep_reduce!(sums, counts, CB.SerialBackend(), items, make_scratch, body!) +end + +sweep_reduce!(sums, counts, backend::CB.AbstractExecutionBackend, items, make_scratch, body!) = + throw(ArgumentError( + "a gridded sweep runs on the serial and threaded CPU backends; $(typeof(backend)) has no " * + "gridded method", + )) -Sum the operator over every pair one lag names, with the lag's equal-length displacements `images` -and squared separation `r2` already fixed. +threaded_sweep_reduce!(sums, counts, items, make_scratch, body!) = throw(ArgumentError( + "Threaded backend is unavailable. Load the OhMyThreads extension or use backend=CB.SerialBackend().", +)) + +""" + transform_engine(sf, data, schedule, distance_bins, ::Val{D}, ::Val{V}, ::Val{K}, valid, weights, tag; to = identity) + +The transform engine's prepared state for a field: the forward transforms of every masked, weighted +monomial of every slab — by FFT for a grid's slabs, by non-uniform FFT for a +[`ScatteredModesSchedule`](@ref), as the spectral `tag` names — the inverse columns and the lag +bookkeeping, every array moved by `to`. Supplied by the AbstractFFTs extension. +""" +function transform_engine end + +""" + device_transform_sweep!(sums, counts, backend, sf, data, schedule, distance_bins, plan, nb, ::Val{D}, ::Val{V}, ::Val{K}, valid, weights, tag, axis) + +The transform engine on a device backend, supplied by the KernelAbstractions extension together with +an AbstractFFTs implementation for the device's arrays. `axis` is `nothing` for the distance +histogram or `(axis_edges, n_angle, second_axis)` for the joint one. +""" +device_transform_sweep!(sums, counts, backend, args...) = throw(ArgumentError( + "a transform on $(typeof(backend)) needs `using KernelAbstractions` for the device lag kernel, and an " * + "AbstractFFTs implementation on the device's arrays (`using CUDA` supplies CUFFT) for the transforms.", +)) + +"""Tasks a backend sweeps with, which is how far the work is split.""" +@inline sweep_tasks(::CB.AbstractSerialBackend) = 1 +@inline sweep_tasks(::CB.AbstractThreadedBackend) = Threads.nthreads() +@inline sweep_tasks(::CB.AbstractAutoBackend) = _gridded_threads() +@inline sweep_tasks(::CB.AbstractExecutionBackend) = 1 + +@inline _gridded_threads() = _ohmythreads_loaded() ? Threads.nthreads() : 1 + +# --------------------------------------------------------------------------------------------------- +# The direct sweep +# --------------------------------------------------------------------------------------------------- + +""" + _lag_visit(sf, schedule, uniform, I, J, h, plan, nb, ::Val{D}, ::Val{V}, ::Val{K}) + -> (bin, r2, factor, geometry, self_reverse) or nothing + +What both sweeps need to know about one lag of one slab pair before touching the field: `nothing` +when the lag names no pair to bin. Within one slab only one of `±h` is visited and the lag equal to +its own reverse is flagged, since it names every pair twice. `factor` is the lag's reading for an +operator odd in a scalar increment and `1` for every other. +""" +@inline function _lag_visit( + sf, s::AbstractSeparableSchedule, su::UniformLagSchedule{Dg}, I::Int, J::Int, h::NTuple{Dg, Int}, + plan, nb::Int, ::Val{D}, ::Val{V}, ::Val{K}, +) where {Dg, D, V, K} + same = I == J + same && all(iszero, h) && return nothing + hn = ntuple(d -> _lag_negate(su, d, h[d]), Val(Dg)) + same && h < hn && return nothing + ok, r2, orientation, geometry = lag_frame(s, I, J, h, Val(D), Val(V), Val(K)) + ok || return nothing + b = squared_digitize(plan, r2) + 1 <= b <= nb || return nothing + factor = SFT.is_odd_in_scalars(sf) ? orientation : 1 + return b, r2, factor, geometry, same && h == hn +end + +"""The lags of slab pair `(I, J)` that can reach `r_max`, as a Cartesian range.""" +@inline function _pair_lags(s::AbstractSeparableSchedule, su::UniformLagSchedule{Dg}, I, J, r_max) where {Dg} + lims = lag_limits(s, I, J, r_max) + return CartesianIndices(ntuple(d -> lag_range(su, d, lims[d]), Val(Dg))) +end + +"""The operator on one pair, once per frame, as the transport defines the increment.""" +@inline function _lag_values( + ::IdentityTransport, sf, frames::NTuple{M, <:NamedTuple}, data, k, kp, r2, + ::Val{D}, ::Val{V}, ::Val{K}, ::Type{T}, +) where {M, D, V, K, T} + δu = _lag_increment(Val(D), Val(V), Val(K), data, k, kp) + return ntuple(m -> T(_pair_value(sf, δu, frames[m].dir, r2)), Val(M)) +end + +@inline function _lag_values( + ::FrameTransport, sf, frames::NTuple{M, <:NamedTuple}, data::AbstractMatrix{UT}, k, kp, r2, + ::Val{D}, ::Val{V}, ::Val{K}, ::Type{T}, +) where {M, UT, D, V, K, T} + W = V * D + K + uA = SA.SVector{W, UT}(ntuple(c -> @inbounds(data[c, k]), Val(W))) + uB = SA.SVector{W, UT}(ntuple(c -> @inbounds(data[c, kp]), Val(W))) + return ntuple(Val(M)) do m + f = @inbounds frames[m] + T(sf(_split_increment(Val(D), Val(V), Val(K), f.B * uB - f.A * uA), f.dir)) + end +end + +""" + _lag_reduce(transport, sf, data, valid, weights, ::Val{D}, ::Val{V}, ::Val{K}, ::Val{Dg}, uniform, strides, h, + frames, r2, half_dim, baseI, baseJ) -> (totals, n_pairs) + +Sum the operator over every pair one lag names between the slabs starting at columns `baseI` and +`baseJ`, once per frame in `frames`, with the squared separation `r2` already fixed. With `weights` +each pair carries `w_k · w_kp` in the totals and in the pair count. The lag's cells are swept as boxes of constant flat offset, so the innermost loop is unit-stride and -the whole lag contributes one number. A wrapped direction contributes a second box rather than a -per-cell branch. Each pair's value is the mean over `images`, which is one term — the displacement -itself — unless the lag half-turns a periodic direction. +the whole lag contributes one number per frame. A wrapped direction contributes a second box rather +than a per-cell branch. """ @inline function _lag_reduce( - sf::SFT.AbstractPairwiseStructureFunctionType, u_flat::AbstractMatrix{UT}, valid, - ::Val{D}, ::Val{Dg}, s::UniformLagSchedule, strides::NTuple{Dg, Int}, - h::NTuple{Dg, Int}, images::Tuple{Vararg{SA.SVector{D}, M}}, r2, half_dim::Int, -) where {UT, D, Dg, M} - total = zero(SFT._sf_raw(sf, SA.SVector{D, UT}(ntuple(_ -> zero(UT), Val(D))), images[1], r2)) - n_pairs = 0 - inv_m = inv(M) + transport::AbstractLagTransport, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix{UT}, valid, weights, ::Val{D}, ::Val{V}, ::Val{K}, ::Val{Dg}, su::UniformLagSchedule, + strides::NTuple{Dg, Int}, h::NTuple{Dg, Int}, frames::NTuple{M, <:NamedTuple}, r2, half_dim::Int, + baseI::Int, baseJ::Int, +) where {UT, D, V, K, Dg, M} + T = float(promote_type(UT, eltype(frames[1].dir))) + totals = ntuple(_ -> zero(T), Val(M)) + n_pairs = _zero_count(weights) @inbounds for combo in 0:((1 << Dg) - 1) segs = ntuple(Val(Dg)) do d - _lag_segments(s, d, h[d], d == half_dim)[1 + ((combo >> (d - 1)) & 1)] + _lag_segments(su, d, h[d], d == half_dim)[1 + ((combo >> (d - 1)) & 1)] end ranges = map(first, segs) any(isempty, ranges) && continue @@ -280,86 +838,195 @@ itself — unless the lag half-turns a periodic direction. base += (J[d - 1] - 1) * strides[d] end @simd for i1 in r1 - k = base + i1 - kp = k + off + k = baseI + base + i1 + kp = baseJ + base + i1 + off ok = valid[k] & valid[kp] - δu = SA.SVector{D, UT}(ntuple(c -> u_flat[c, kp] - u_flat[c, k], Val(D))) - v = zero(total) - for m in 1:M # `M` is a type parameter, so this unrolls - v += SFT._sf_raw(sf, δu, images[m], r2) - end - # selected, never multiplied by `ok`: an empty cell may hold NaN, and NaN * 0 is NaN - total += ok ? v * inv_m : zero(total) - n_pairs += ok + w = _pair_weight(weights, k, kp) + vals = _lag_values(transport, sf, frames, data, k, kp, r2, Val(D), Val(V), Val(K), T) + totals = _accumulate(totals, vals, ok, w) + n_pairs = _count_pair(n_pairs, ok, w) end end end - return total, n_pairs + return totals, n_pairs end +# Selected, never multiplied by `ok`: an empty cell may hold NaN, and NaN * 0 is NaN. A function of its +# own so the running totals are never a captured variable that is reassigned, which Julia would box. +# An unweighted pair carries the weight `true`, which the compiler folds away. +@inline _accumulate(totals::NTuple{M}, vals::NTuple{M}, ok::Bool, ::Bool) where {M} = + ntuple(m -> @inbounds(totals[m] + (ok ? vals[m] : zero(vals[m]))), Val(M)) +@inline _accumulate(totals::NTuple{M}, vals::NTuple{M}, ok::Bool, w) where {M} = + ntuple(m -> @inbounds(totals[m] + (ok ? w * vals[m] : zero(vals[m]))), Val(M)) + +@inline _pair_weight(::NoWeights, k::Int, kp::Int) = true +@inline _pair_weight(w::AbstractVector, k::Int, kp::Int) = @inbounds w[k] * w[kp] +@inline _zero_count(::NoWeights) = 0 +@inline _zero_count(w::AbstractVector) = zero(eltype(w)) +@inline _count_pair(n::Int, ok::Bool, ::Bool) = n + ok +@inline _count_pair(n, ok::Bool, w) = n + (ok ? w : zero(w)) + """ - gridded_lag_sweep!(sums, counts, sf, u, schedule, distance_bins, ::Val{D}) + gridded_lag_sweep!(sums, counts, sf, u, schedule, distance_bins[, axis_bins], ::Val{D}; valid, weights, backend, second_axis) + gridded_lag_sweep!(sums, counts, sf, fields, schedule, distance_bins[, axis_bins]; valid, weights, backend, second_axis) -Accumulate every pair `schedule` names into the 1-D distance histogram `sums`/`counts`. +Accumulate every pair `schedule` names into the distance histogram `sums`/`counts`, or with +`axis_bins` into the joint histogram over separation and the angle `second_axis` reads from each +lag's direction, `sums` and `counts` then being `(n_distance, n_angle)`. -`u` is stored `(component, cells...)` with its trailing axes matching `schedule.dims`, and `D` is its +`u` is stored `(component, cells...)` with its trailing axes matching the schedule, and `D` is its component count, which may exceed the grid's dimension — a lag then lies in the grid's directions -and is zero along the rest. `valid` says which cells hold a datum; a pair counts only when both of -its ends do (see [`field_validity`](@ref)). +and is zero along the rest. A a multi-field carries several fields the same way. `valid` says +which cells hold a datum; a pair counts only when both of its ends do (see [`field_validity`](@ref)). +`weights`, one finite weight per cell (`nothing` for none), multiplies each pair by `w_k · w_kp` in both +`sums` and `counts`, so the bin average is `Σ w w v / Σ w w` and `counts` must then be floating point; +[`cell_measure`](@ref) supplies a grid's cell areas. `backend` is the hardware, as on the unstructured +entry; a threaded backend splits the slab pairs +across tasks, and the lags of a schedule with a single slab. Exact, not approximate: each unordered pair is counted once, because lags are enumerated one per -distinct separation and only one of `±lag` is kept. A lag equal to its own reverse is swept over -half of one direction, which is one representative per pair. +distinct separation and within a slab only one of `±lag` is kept. A lag equal to its own reverse is +swept over half of one direction, which is one representative per pair. Where a periodic direction has an even cell count, its half-period offset joins two cells by two minimal paths of equal length and opposite sign, so the separation direction is not unique there. The operator is averaged over those equal-length displacements, which is the only choice that does not favour one of them; an operator odd in the separation direction therefore vanishes on the pairs -whose every offset half-turns, as it must when no direction is preferred. +whose every offset half-turns, as it must when no direction is preferred. In the joint histogram +such a lag's pairs are split between the two angle bins in equal halves, so `counts` must then hold +a floating-point type. """ function gridded_lag_sweep!( sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, - u::AbstractArray, s::UniformLagSchedule{Dg, T}, dist_be, ::Val{D}; - valid = AllValid(), -) where {OT, CT, Dg, T, D} - D >= Dg || throw(ArgumentError( - "the field has $D components but the grid has $Dg directions; a lag needs a component per " * - "direction", - )) - size(u)[2:end] == s.dims || throw(DimensionMismatch( - "field cells $(size(u)[2:end]) do not match the schedule's dims $(s.dims)", - )) - size(u, 1) == D || throw(DimensionMismatch( - "field has $(size(u, 1)) components, declared $D", - )) - + data::AbstractMatrix, s::AbstractSeparableSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}; + valid = AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {OT, CT, D, V, K} + _check_grid_field(sf, data, s, Val(D), Val(V), Val(K)) + w = _pair_weights(weights, size(data, 2), float(eltype(data))) + _check_weighted_counts(w, CT) plan = squared_digitize_plan(dist_be) nb = n_histogram_bins(plan) length(sums) == nb && length(counts) == nb || throw(DimensionMismatch( "sums and counts must have length $nb; got $(length(sums)) and $(length(counts))", )) - u_flat = reshape(u, D, n_grid_cells(s)) - strides = grid_strides(s) + su = uniform_axes(s) + T = eltype(su.spacing) r_max = _cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) - lags = ntuple(d -> lag_range(s, d, r_max), Val(Dg)) - - @inbounds for H in CartesianIndices(lags) - h = Tuple(H) - all(iszero, h) && continue # a cell paired with itself - hn = ntuple(d -> _lag_negate(s, d, h[d]), Val(Dg)) - h < hn && continue # keep one of `±lag` - dx = SA.SVector{D, T}(ntuple(d -> d <= Dg ? T(h[d]) * s.spacing[d] : zero(T), Val(D))) - r2 = LA.dot(dx, dx) - b = squared_digitize(plan, r2) - 1 <= b <= nb || continue - # A self-reverse lag pairs the two halves of any direction it half-turns, so sweeping one of - # them visits each pair once. - half_dim = (h == hn) ? findfirst(!iszero, h)::Int : 0 - total, n_pairs = _lag_reduce_images(sf, u_flat, valid, Val(D), Val(Dg), s, strides, h, dx, - r2, half_dim, _ambiguous_dirs(s, h)) - sums[b] += OT(total) + dp, vp, wp = separable_layout(s, data, valid, w) + transport = lag_transport(s) + items = sweep_items(s, r_max, sweep_tasks(backend), true) + body! = (ls, lc, it, _) -> _sweep_item!(ls, lc, sf, s, su, dp, vp, wp, it, plan, nb, r_max, transport, + Val(D), Val(V), Val(K)) + sweep_reduce!(sums, counts, backend, items, () -> nothing, body!) + return sums, counts +end + +function _sweep_item!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf, s, su::UniformLagSchedule{Dg}, data, valid, weights, + item::NTuple{4, Int}, plan, nb, r_max, transport, ::Val{D}, ::Val{V}, ::Val{K}, +) where {OT, CT, Dg, D, V, K} + I, J, part, n_parts = item + lags = _pair_lags(s, su, I, J, r_max) + strides = grid_strides(su) + Nu = n_cells(su) + baseI, baseJ = (I - 1) * Nu, (J - 1) * Nu + @inbounds for lin in part:n_parts:length(lags) + h = Tuple(lags[lin]) + v = _lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(V), Val(K)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + half_dim = self_reverse ? findfirst(!iszero, h)::Int : 0 + totals, n_pairs = with_frames(transport, geometry) do frames + _lag_reduce(transport, sf, data, valid, weights, Val(D), Val(V), Val(K), Val(Dg), su, strides, h, + frames, r2, half_dim, baseI, baseJ) + end + sums[b] += OT(factor * sum(totals) / length(totals)) counts[b] += CT(n_pairs) end + return nothing +end + +function gridded_lag_sweep!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::AbstractSeparableSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}; + valid = AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SeparationAngleAxis, +) where {OT, CT, D, V, K} + _check_grid_field(sf, data, s, Val(D), Val(V), Val(K)) + _require_directional(s) + w = _pair_weights(weights, size(data, 2), float(eltype(data))) + _check_weighted_counts(w, CT) + plan = squared_digitize_plan(dist_be) + nb = n_histogram_bins(plan) + axis_edges = BinEdges(axis_be) + na = n_histogram_bins(axis_edges) + size(sums) == (nb, na) && size(counts) == (nb, na) || throw(DimensionMismatch( + "sums and counts must be ($nb, $na); got $(size(sums)) and $(size(counts))", + )) + su = uniform_axes(s) + T = eltype(su.spacing) + r_max = _cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) + dp, vp, wp = separable_layout(s, data, valid, w) + transport = lag_transport(s) + items = sweep_items(s, r_max, sweep_tasks(backend), true) + body! = (ls, lc, it, _) -> _sweep_item!(ls, lc, sf, s, su, dp, vp, wp, it, plan, nb, r_max, transport, + axis_edges, na, second_axis, Val(D), Val(V), Val(K)) + sweep_reduce!(sums, counts, backend, items, () -> nothing, body!) return sums, counts end + +function _sweep_item!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, sf, s, su::UniformLagSchedule{Dg}, data, valid, weights, + item::NTuple{4, Int}, plan, nb, r_max, transport, axis_edges, na, second_axis, + ::Val{D}, ::Val{V}, ::Val{K}, +) where {OT, CT, Dg, D, V, K} + I, J, part, n_parts = item + lags = _pair_lags(s, su, I, J, r_max) + strides = grid_strides(su) + Nu = n_cells(su) + baseI, baseJ = (I - 1) * Nu, (J - 1) * Nu + @inbounds for lin in part:n_parts:length(lags) + h = Tuple(lags[lin]) + v = _lag_visit(sf, s, su, I, J, h, plan, nb, Val(D), Val(V), Val(K)) + v === nothing && continue + b, r2, factor, geometry, self_reverse = v + half_dim = self_reverse ? findfirst(!iszero, h)::Int : 0 + with_frames(transport, geometry) do frames + totals, n_pairs = _lag_reduce(transport, sf, data, valid, weights, Val(D), Val(V), Val(K), Val(Dg), su, + strides, h, frames, r2, half_dim, baseI, baseJ) + _scatter_joint!(sums, counts, b, factor, totals, n_pairs, map(f -> f.dir, frames), r2, + axis_edges, na, second_axis) + end + end + return nothing +end + +# A pair's direction on a sphere lives in its own geodesic frame, so an angle to one fixed reference +# axis is not a property of the pair. +_require_directional(s::AbstractSeparableSchedule) = _require_directional(lag_transport(s)) +_require_directional(::IdentityTransport) = nothing +_require_directional(::FrameTransport) = throw(ArgumentError( + "a joint histogram over the separation angle is not defined on a sphere: each pair's " * + "direction lives in its own geodesic frame, so an angle to one fixed reference axis is not a " * + "property of the pair. Ask for the 1-D histogram.", +)) + +# Each equal-length image carries its share of the lag's pairs to its own angle bin. +@inline function _scatter_joint!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, b, factor, totals::NTuple{M}, n_pairs, images, + r2, axis_edges, na, second_axis, +) where {OT, CT, M} + M > 1 && CT <: Integer && throw(ArgumentError( + "a lag that half-turns a periodic direction splits each pair between its two directions, " * + "so a joint histogram over angle needs a floating-point count type; got $CT", + )) + @inbounds for m in 1:M + bθ = SFH.digitize(axis_quantity(second_axis, images[m], r2), axis_edges) + 1 <= bθ <= na || continue + sums[b, bθ] += OT(factor * totals[m] / M) + counts[b, bθ] += CT(n_pairs / M) + end + return nothing +end diff --git a/src/Calculations/gridded_zonal.jl b/src/Calculations/gridded_zonal.jl index 509cee5..f0e2af9 100644 --- a/src/Calculations/gridded_zonal.jl +++ b/src/Calculations/gridded_zonal.jl @@ -1,7 +1,7 @@ # Lat-lon enumeration. A lag in (λ, φ) is not a constant separation, so the uniform lag sweep does not # apply — but the geodesic frame, written in each endpoint's own east/north basis, depends only on # (φ₁, φ₂, Δλ) and not on absolute longitude. So the geometry is computed once per latitude pair and -# longitude offset and reused around the whole circle, instead of once per pair. +# longitude offset and reused around the whole circle. """ ZonalLagSchedule(lats, n_lon, dlon, radius, lon_periodic) @@ -14,9 +14,10 @@ axis is a formula is not materialised to carry it. The field it sweeps is stored `(component, longitude, latitude)` with components in the local `(east, north[, radial])` basis, which is the basis the transport matrices are written in, so no -per-pair conversion to ambient coordinates happens. +per-pair conversion to ambient coordinates happens. Each latitude row is one slab and longitude is +the uniform direction, with the pair frame applied per lag (see [`FrameTransport`](@ref)). """ -struct ZonalLagSchedule{T, LV <: AbstractVector{T}} +struct ZonalLagSchedule{T, LV <: AbstractVector{T}} <: AbstractSeparableSchedule lats::LV n_lon::Int dlon::T @@ -26,6 +27,50 @@ end """Cells the schedule covers.""" @inline n_zonal_cells(s::ZonalLagSchedule) = s.n_lon * length(s.lats) +@inline n_cells(s::ZonalLagSchedule) = n_zonal_cells(s) +@inline grid_dimension(::ZonalLagSchedule) = 2 + +@inline uniform_axes(s::ZonalLagSchedule) = UniformLagSchedule((s.n_lon,), (s.dlon,), (s.lon_periodic,)) +@inline n_slabs(s::ZonalLagSchedule) = length(s.lats) +@inline separable_layout(::ZonalLagSchedule, data, valid, weights) = (data, valid, weights) +@inline lag_transport(::ZonalLagSchedule) = FrameTransport() + +# Two rows are never closer than their latitude difference, so a row pair beyond `r_max` contributes +# nothing at any longitude offset. +function enumerated_pairs(s::ZonalLagSchedule, r_max) + n = length(s.lats) + return ((I, J) for I in 1:n for J in I:n if s.radius * abs(s.lats[J] - s.lats[I]) <= r_max) +end + +# The separation of two points at latitudes φ₁, φ₂ grows with their longitude difference up to a half +# turn, by hav σ = hav Δφ + cos φ₁ cos φ₂ hav Δλ, so the offsets within `r_max` are those up to the +# Δλ that solves it; one is added so round-off at the boundary can only keep a lag the bin test drops. +function _zonal_lag_limit(s::ZonalLagSchedule{T}, phi1, phi2, r_max) where {T} + isfinite(r_max) || return typemax(Int) + σ_max = r_max / s.radius + σ_max >= π && return typemax(Int) + cc = cos(phi1) * cos(phi2) + cc > 0 || return typemax(Int) + rhs = (sin(σ_max / 2)^2 - sin((phi2 - phi1) / 2)^2) / cc + rhs >= 1 && return typemax(Int) + rhs <= 0 && return 1 + return floor(Int, 2 * asin(sqrt(rhs)) / abs(s.dlon)) + 1 +end + +@inline lag_limits(s::ZonalLagSchedule, I, J, r_max) = (_zonal_lag_limit(s, s.lats[I], s.lats[J], r_max),) + +# One parallel spans less distance the nearer it lies to a pole, so a row pair's longitude limit +# depends on the rows. +uniform_lag_box(::ZonalLagSchedule) = false + +# Every cross-row offset within `r_max` is within the larger of the two rows' own limits. +function lag_limits(s::ZonalLagSchedule, r_max) + lim = 0 + for I in eachindex(s.lats) + lim = max(lim, _zonal_lag_limit(s, s.lats[I], s.lats[I], r_max)) + end + return (lim,) +end # Ambient position and local east/north at longitude `lam`, latitude `phi`. @inline function _zonal_basis(lam::T, phi::T) where {T} @@ -44,7 +89,7 @@ Separation and the two transport matrices shared by every pair at latitudes `φ One computation serves the whole circle of such pairs, because the geodesic frame written in the endpoints' local bases does not depend on absolute longitude — checked against -[`pair_frame`](@ref) to `4e-15` over a full turn. It is evaluated at longitude zero, which is +[`SFH.pair_frame`](@ref) to `4e-15` over a full turn. It is evaluated at longitude zero, which is therefore representative. Row 1 of each matrix is the longitudinal projection and row 2 the transverse, matching @@ -58,115 +103,82 @@ scalar. pB, EB, NB = _zonal_basis(dlam, phi2) ok, r, frame = SFH.pair_frame(g, pA, pB) t_A, t_B, m̂ = frame[1], frame[2], frame[3] - rows(t, m̂, E, N) = (a, c) -> + return ok, r, _transport_rows(t_A, m̂, EA, NA, Val(D)), _transport_rows(t_B, m̂, EB, NB, Val(D)) +end + +# Row 1: the longitudinal tangent in the local basis; row 2: the transverse; row 3: the radial identity. +@inline function _transport_rows(t, m̂, E, N, ::Val{D}) where {D} + T = eltype(t) + return SA.SMatrix{D, D, T}(ntuple(Val(D * D)) do lin + a = (lin - 1) % D + 1 + c = (lin - 1) ÷ D + 1 a == 1 ? (c == 1 ? LA.dot(t, E) : c == 2 ? LA.dot(t, N) : zero(T)) : a == 2 ? (c == 1 ? LA.dot(m̂, E) : c == 2 ? LA.dot(m̂, N) : zero(T)) : (c == 3 ? one(T) : zero(T)) - fA = rows(t_A, m̂, EA, NA) - fB = rows(t_B, m̂, EB, NB) - A = SA.SMatrix{D, D, T}((fA(a, c) for a in 1:D, c in 1:D)...) - B = SA.SMatrix{D, D, T}((fB(a, c) for a in 1:D, c in 1:D)...) - return ok, r, A, B + end) end -"""Longitude offsets to visit for a latitude pair, one per distinct separation.""" -@inline function _zonal_lag_range(s::ZonalLagSchedule, same_row::Bool) - n = s.n_lon - s.lon_periodic || return same_row ? (1:(n - 1)) : (-(n - 1)):(n - 1) - # A full circle has `n` distinct offsets, taken as minimum images. Within one row a pair is named - # by both `+m` and `-m`, so only the positive half is kept. - return same_row ? (1:(n ÷ 2)) : (-((n - 1) ÷ 2)):(n ÷ 2) -end +""" + zonal_transport(geometry, φ₁, φ₂, Δλ, ::Val{D}, ::Val{V}, ::Val{K}) -> (ok, r, A, B) -# Longitude segments of constant index offset, as the uniform sweep uses: the part whose partner -# stays in range, and — on a full circle — the part that wraps. -@inline function _zonal_segments(s::ZonalLagSchedule, m::Int, half::Bool) - n = s.n_lon - half && return ((1:(n ÷ 2), m), (1:0, 0)) - if m >= 0 - return (s.lon_periodic && m > 0) ? - ((1:(n - m), m), (((n - m + 1):n), m - n)) : - ((1:(n - m), m), (1:0, 0)) +The transport of a packed field: the `D×D` block on each of the `V` vector fields and the identity +on the `K` scalar fields, as `W×W` matrices with `W = V·D + K`. A field with no vector field +carries only the separation. +""" +@inline function zonal_transport( + g::SFH.SphericalGeometry, phi1::T, phi2::T, dlam::T, ::Val{D}, ::Val{V}, ::Val{K}, +) where {T, D, V, K} + if V == 0 + ok, r, _, _ = zonal_transport(g, phi1, phi2, dlam, Val(2)) + I = SA.SMatrix{K, K, T}(LA.I) + return ok, r, I, I end - return s.lon_periodic ? - (((1 - m):n, m), (1:(-m), m + n)) : - (((1 - m):n, m), (1:0, 0)) + ok, r, A, B = zonal_transport(g, phi1, phi2, dlam, Val(D)) + return ok, r, _block_diagonal(A, Val(V), Val(K)), _block_diagonal(B, Val(V), Val(K)) end -""" - gridded_lag_sweep!(sums, counts, sf, u, schedule::ZonalLagSchedule, distance_bins, ::Val{D}; valid) +@inline function _block_diagonal(A::SA.SMatrix{D, D, T}, ::Val{V}, ::Val{K}) where {D, T, V, K} + W = V * D + K + return SA.SMatrix{W, W, T}(ntuple(Val(W * W)) do lin + i = (lin - 1) % W + 1 + j = (lin - 1) ÷ W + 1 + if i <= V * D && j <= V * D && (i - 1) ÷ D == (j - 1) ÷ D + @inbounds A[(i - 1) % D + 1, (j - 1) % D + 1] + else + T(i == j) + end + end) +end -Accumulate every pair on a lat-lon grid into the 1-D distance histogram. +@inline _zonal_geometry(s::ZonalLagSchedule, ::Val{D}, ::Val{V}) where {D, V} = + SFH.SphericalGeometry{V == 0 ? 2 : D}(SFH.SphericalDistance(s.radius), s.radius) -`u` is `(component, longitude, latitude)` in the local `(east, north[, radial])` basis. Latitude -pairs whose rows cannot come within the largest finite bin are skipped whole, and within a pair the -geometry is computed once per longitude offset rather than once per pair. -""" -function gridded_lag_sweep!( - sums::AbstractVector{OT}, counts::AbstractVector{CT}, - sf::SFT.AbstractPairwiseStructureFunctionType, - u::AbstractArray, s::ZonalLagSchedule{T}, dist_be, ::Val{D}; - valid = AllValid(), -) where {OT, CT, T, D} - n_lat = length(s.lats) - n_lon = s.n_lon - size(u) == (D, n_lon, n_lat) || throw(DimensionMismatch( - "u must be (component, longitude, latitude) = ($D, $n_lon, $n_lat); got $(size(u))", - )) - plan = squared_digitize_plan(dist_be) - nb = n_histogram_bins(plan) - length(sums) == nb && length(counts) == nb || throw(DimensionMismatch( - "sums and counts must have length $nb; got $(length(sums)) and $(length(counts))", - )) - uf = reshape(u, D, n_lon * n_lat) - geom = SFH.SphericalGeometry{D}(DI.SphericalAngle(), s.radius) - r_max = _cull_is_unbounded(dist_be) ? T(Inf) : T(float(last(dist_be))) - # On the sphere the pair frame IS the basis, so the longitudinal direction is ê₁ for every pair. - r_hat = SA.SVector{D, T}(ntuple(i -> i == 1 ? one(T) : zero(T), Val(D))) - - @inbounds for j1 in 1:n_lat, j2 in j1:n_lat - # Two rows are never closer than their latitude difference, so a row pair beyond the last - # finite bin contributes nothing at any longitude offset. - s.radius * abs(s.lats[j2] - s.lats[j1]) > r_max && continue - base1 = (j1 - 1) * n_lon - base2 = (j2 - 1) * n_lon - same_row = j1 == j2 - for m in _zonal_lag_range(s, same_row) - dlam = T(m) * s.dlon - ok, r, A, B = zonal_transport(geom, s.lats[j1], s.lats[j2], dlam, Val(D)) - ok || continue - b = squared_digitize(plan, r * r) - 1 <= b <= nb || continue - # A half-turn offset joins the two ends by two minimal paths of opposite sign, so the - # separation direction is not unique and the operator is averaged over both. - ambiguous = s.lon_periodic && iseven(n_lon) && abs(m) == n_lon ÷ 2 - A2, B2 = A, B - if ambiguous - _, _, A2, B2 = zonal_transport(geom, s.lats[j1], s.lats[j2], -dlam, Val(D)) - end - total = zero(OT) - n_pairs = 0 - for (rng, off) in _zonal_segments(s, m, same_row && ambiguous) - isempty(rng) && continue - for i in rng - k1 = base1 + i - k2 = base2 + i + off - okp = valid[k1] & valid[k2] - uA = SA.SVector{D, T}(ntuple(c -> uf[c, k1], Val(D))) - uB = SA.SVector{D, T}(ntuple(c -> uf[c, k2], Val(D))) - v = sf(B * uB - A * uA, r_hat) - ambiguous && (v = (v + sf(B2 * uB - A2 * uA, r_hat)) / 2) - total += okp ? OT(v) : zero(OT) - n_pairs += okp - end - end - sums[b] += total - counts[b] += CT(n_pairs) - end +# On the sphere the pair frame IS the basis, so the longitudinal direction is ê₁ for every pair. A +# half-turn offset joins the two ends by two minimal paths of opposite sign, so the operator is +# averaged over both frames. Read south to north; along one parallel west to east, where a half turn +# leaves neither end first. +@inline function lag_frame( + s::ZonalLagSchedule{T}, I, J, h::NTuple{1, Int}, ::Val{D}, ::Val{V}, ::Val{K}, +) where {T, D, V, K} + m = h[1] + dlam = T(m) * s.dlon + geom = _zonal_geometry(s, Val(D), Val(V)) + phi1, phi2 = T(@inbounds s.lats[I]), T(@inbounds s.lats[J]) + ok, r, A, B = zonal_transport(geom, phi1, phi2, dlam, Val(D), Val(V), Val(K)) + two = s.lon_periodic && iseven(s.n_lon) && abs(m) == s.n_lon ÷ 2 + A2, B2 = A, B + if two + _, _, A2, B2 = zonal_transport(geom, phi1, phi2, -dlam, Val(D), Val(V), Val(K)) end - return sums, counts + north = phi2 - phi1 + factor = !iszero(north) ? (north > 0 ? 1 : -1) : (two ? 0 : (dlam > 0 ? 1 : -1)) + Dr = _direction_width(Val(D), Val(V), Val(2)) + dir = _unit_east(Dr, T) + return ok, r * r, factor, (dir = dir, A = A, B = B, A2 = A2, B2 = B2, two = two) end +@inline _unit_east(::Val{Dr}, ::Type{T}) where {Dr, T} = + SA.SVector{Dr, T}(ntuple(i -> i == 1 ? one(T) : zero(T), Val(Dr))) """ ScatteredPairs(points, metric) @@ -174,10 +186,9 @@ end Pair enumeration for a grid with no structure to exploit: the points themselves, and the metric that measures between them. -A pixelized sphere, a curvilinear mesh, a node set, a stretched axis — none of these share a -separation between many pairs, so there is nothing to hoist and the honest thing is to enumerate the -pairs. That is what the unstructured path does, with culling, so this schedule routes to it rather -than reimplementing it. +A pixelized sphere, a curvilinear mesh, a node set, a grid with no uniform direction — none of these +share a separation between many pairs, so there is nothing to hoist and the pairs are enumerated. +That is what the unstructured path does, with culling, and this schedule routes to it. """ struct ScatteredPairs{X <: AbstractMatrix, M} points::X @@ -186,29 +197,74 @@ end """Cells the schedule covers.""" @inline n_scattered_cells(s::ScatteredPairs) = size(s.points, 2) +@inline n_cells(s::ScatteredPairs) = size(s.points, 2) +@inline grid_dimension(s::ScatteredPairs) = size(s.points, 1) """ - gridded_lag_sweep!(sums, counts, sf, u, schedule::ScatteredPairs, distance_bins, ::Val{D}; valid) + gridded_lag_sweep!(sums, counts, sf, u, schedule::ScatteredPairs, distance_bins, ::Val{D}; valid, backend) Accumulate every pair of a structureless grid, by enumerating them. -Cells holding nothing are dropped before the sweep rather than tested inside it: the pair loop has no -mask, and a point that takes part in no pair is simply not passed to it. +Cells holding nothing are dropped before the sweep: the pair loop carries no mask, and a point that +takes part in no pair is not passed to it. """ function gridded_lag_sweep!( sums::AbstractVector, counts::AbstractVector, sf::SFT.AbstractPairwiseStructureFunctionType, - u::AbstractArray, s::ScatteredPairs, dist_be, ::Val{D}; - valid = AllValid(), -) where {D} + data::AbstractMatrix, s::ScatteredPairs, dist_be, ::Val{D}, ::Val{V}, ::Val{K}; + valid = AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {D, V, K} n = n_scattered_cells(s) - uf = reshape(u, D, n) - size(uf, 2) == n || throw(DimensionMismatch( - "field holds $(size(uf, 2)) cells, the grid $n", + size(data) == (V * D + K, n) || throw(DimensionMismatch( + "field holds $(size(data, 2)) cells of $(size(data, 1)) components, the grid $n cells of " * + "$(V * D + K)", )) + w = _pair_weights(weights, n, float(eltype(data))) + _check_weighted_counts(w, eltype(counts)) keep = valid isa AllValid ? Colon() : findall(valid) x = valid isa AllValid ? s.points : s.points[:, keep] - uu = valid isa AllValid ? uf : uf[:, keep] - calculate_structure_function!(sums, counts, sf, x, uu, dist_be; distance_metric = s.metric) + uu = valid isa AllValid ? data : data[:, keep] + ww = w isa NoWeights ? nothing : w[keep] + if V == 1 && K == 0 + calculate_structure_function!(sums, counts, sf, x, uu, dist_be; + distance_metric = s.metric, backend, weights = ww) + else + f = MF.Fields{D, V, K, typeof(uu)}(uu) + calculate_structure_function!(sums, counts, sf, x, f, dist_be; + distance_metric = s.metric, backend, weights = ww) + end return sums, counts end + +# A structureless grid's tensor is the point tensor over its held cells; the point kernels take no weights. +function gridded_tensor_sweep!( + sums::AbstractArray, counts::AbstractVector, order::Val{P}, data::AbstractMatrix, s::ScatteredPairs, dist_be, + ::Val{D}, spectral_backend; + valid = AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {P, D} + weights === nothing || throw(ArgumentError( + "pair weights are not implemented on the point tensor kernels, which a structureless grid's tensor uses", + )) + n = n_scattered_cells(s) + size(data) == (D, n) || throw(DimensionMismatch( + "field holds $(size(data, 2)) cells of $(size(data, 1)) components, the grid $n cells of $D", + )) + keep = valid isa AllValid ? Colon() : findall(valid) + x = valid isa AllValid ? s.points : s.points[:, keep] + uu = valid isa AllValid ? data : data[:, keep] + calculate_structure_function_tensor!(sums, counts, order, x, uu, dist_be; distance_metric = s.metric, backend) + return sums, counts +end + +function gridded_lag_sweep!( + sums::AbstractMatrix, counts::AbstractMatrix, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::ScatteredPairs, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}; + valid = AllValid(), weights = nothing, backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + second_axis::SeparationAngleAxis, +) where {D, V, K} + throw(ArgumentError( + "a joint histogram over the separation angle on a structureless grid is the unstructured " * + "joint entry's job: pass the points and the field to `calculate_structure_function` with " * + "distance and angle bins.", + )) +end diff --git a/src/Calculations/harmonic.jl b/src/Calculations/harmonic.jl new file mode 100644 index 0000000..0dd6683 --- /dev/null +++ b/src/Calculations/harmonic.jl @@ -0,0 +1,567 @@ +# Kernel-binned pair statistics on a sphere from spherical-harmonic pseudo-coefficients: the +# truncated Legendre / Wigner-d series of the masked field's pseudo-spectra is, exactly, the pair sum +# with a soft kernel of width ~π/lmax in place of a hard bin. + +# --------------------------------------------------------------------------------------------------- +# Wigner small-d functions: d^l_{mn}(β) = ⟨l m| exp(−iβ J_y) |l n⟩, Condon–Shortley phase +# --------------------------------------------------------------------------------------------------- + +"""`log k!` for `k = 0:N` at `t[k + 1]`.""" +function _log_factorials(N::Integer) + t = zeros(Float64, N + 1) + for k in 1:N + t[k + 1] = t[k] + log(k) + end + return t +end + +# d^l_{mn}(β) at l = max(|m|, |n|), where one index is extreme and the sum over k has one term. +function _wigner_seed(l::Int, m::Int, n::Int, β::Real, lf::AbstractVector) + l == 0 && return 1.0 + c, s = cos(β / 2), sin(β / 2) + if abs(m) == l + A = exp((lf[2l + 1] - lf[l + n + 1] - lf[l - n + 1]) / 2) + return m > 0 ? A * c^(l + n) * (-s)^(l - n) : A * c^(l - n) * s^(l + n) + end + A = exp((lf[2l + 1] - lf[l + m + 1] - lf[l - m + 1]) / 2) + return n > 0 ? A * c^(l + m) * s^(l - m) : A * c^(l - m) * (-s)^(l + m) +end + +""" + wigner_d_column!(out, m, n, β, lmax, lf) -> out + +`out[l + 1] = d^l_{mn}(β)` for `l = 0:lmax`, zero below `max(|m|, |n|)`, by the three-term recurrence +in `l` from the closed form at the lowest degree; `lf` is [`_log_factorials`](@ref)`(2lmax)` or longer. +The recurrence is stable in the direction of increasing `l`. +""" +function wigner_d_column!(out::AbstractVector{Float64}, m::Integer, n::Integer, β::Real, lmax::Integer, lf) + fill!(out, 0.0) + l0 = max(abs(m), abs(n)) + l0 > lmax && return out + x = cos(β) + @inbounds out[l0 + 1] = _wigner_seed(l0, m, n, β, lf) + prev = 0.0 + @inbounds for l in l0:(lmax - 1) + cur = out[l + 1] + a = l == 0 ? 0.0 : (m * n) / (l * (l + 1)) + c1 = l == 0 ? 0.0 : sqrt(Float64((l^2 - m^2) * (l^2 - n^2))) / (l * (2l + 1)) + c2 = sqrt(Float64(((l + 1)^2 - m^2) * ((l + 1)^2 - n^2))) / ((l + 1) * (2l + 1)) + out[l + 2] = ((x - a) * cur - c1 * prev) / c2 + prev = cur + end + return out +end + +""" + wigner_d_column(m, n, β, lmax) -> Vector + +[`wigner_d_column!`](@ref) into a fresh vector. +""" +wigner_d_column(m::Integer, n::Integer, β::Real, lmax::Integer) = + wigner_d_column!(zeros(Float64, lmax + 1), m, n, β, lmax, _log_factorials(2lmax + 2)) + +# --------------------------------------------------------------------------------------------------- +# Pseudo-coefficients +# --------------------------------------------------------------------------------------------------- + +""" + pseudo_coefficients_direct(f, θ, φ, s, lmax) -> Matrix{ComplexF64} + +`C[l + 1, m + lmax + 1] = Σ_i f_i conj(ₛY_lm(θ_i, φ_i))` with `ₛY_lm = √((2l+1)/4π) d^l_{m,−s}(θ) e^{imφ}`, +by direct summation over the points: `O(N lmax²)`, and the reference every faster provider is checked +against. `θ` is colatitude and `φ` longitude, both in radians. +""" +function pseudo_coefficients_direct(f::AbstractVector{<:Number}, θ::AbstractVector, φ::AbstractVector, + s::Integer, lmax::Integer) + N = length(f) + length(θ) == length(φ) == N || throw(DimensionMismatch("f, θ and φ must have one entry per point")) + out = zeros(ComplexF64, lmax + 1, 2lmax + 1) + col = zeros(Float64, lmax + 1) + lf = _log_factorials(2lmax + 2) + norms = [sqrt((2l + 1) / (4π)) for l in 0:lmax] + @inbounds for i in 1:N + fi = ComplexF64(f[i]) + iszero(fi) && continue + for m in -lmax:lmax + wigner_d_column!(col, m, -s, θ[i], lmax, lf) + ph = fi * cis(-m * φ[i]) + for l in max(abs(m), abs(s)):lmax + out[l + 1, m + lmax + 1] += ph * norms[l + 1] * col[l + 1] + end + end + end + return out +end + +""" + direct_sum_provider(θ, φ, lmax) -> (f, s) -> coefficients + +The pseudo-coefficient provider of the direct sum, in the form every provider takes: a callable of a +complex point field and a spin. +""" +direct_sum_provider(θ::AbstractVector, φ::AbstractVector, lmax::Integer) = + (f, s) -> pseudo_coefficients_direct(f, θ, φ, s, lmax) + +# Spin-(−s) pseudo-coefficients of `conj(f)` from the spin-`s` ones of `f`: +# conj(ₛY_lm) = (−1)^{m+s} ₋ₛY_{l,−m}, so ₋ₛ[conj f]_lm = (−1)^{m+s} conj(ₛf_{l,−m}). +function _conjugate_field_coefficients(C::AbstractMatrix, s::Integer, lmax::Integer) + out = similar(C) + @inbounds for l in 0:lmax, m in -lmax:lmax + out[l + 1, m + lmax + 1] = (isodd(m + s) ? -1 : 1) * conj(C[l + 1, -m + lmax + 1]) + end + return out +end + +"""`X_l = (1/(2l+1)) Σ_m F_lm conj(G_lm)`, the cross pseudo-spectrum of two coefficient arrays.""" +function _cross_spectrum(F::AbstractMatrix, G::AbstractMatrix, lmax::Integer) + X = zeros(ComplexF64, lmax + 1) + @inbounds for l in 0:lmax + acc = zero(ComplexF64) + for m in -l:l + acc += F[l + 1, m + lmax + 1] * conj(G[l + 1, m + lmax + 1]) + end + X[l + 1] = acc / (2l + 1) + end + return X +end + +# (2l+1)/(4π) b_l d^l_{ss′}(β_k) for every degree and node, as (lmax + 1, n_nodes). +function _node_kernel(s::Integer, s′::Integer, nodes::HarmonicNodes, lf) + L = nodes.lmax + K = zeros(Float64, L + 1, length(nodes)) + col = zeros(Float64, L + 1) + for (k, β) in enumerate(nodes.separations) + wigner_d_column!(col, s, s′, β, L, lf) + for l in 0:L + K[l + 1, k] = (2l + 1) / (4π) * harmonic_taper(nodes.taper, l, L) * col[l + 1] + end + end + return K +end + +# --------------------------------------------------------------------------------------------------- +# An operator as a polynomial in the two ends' spin quantities +# --------------------------------------------------------------------------------------------------- +# +# In the pair's geodesic frame `u_L + i u_T = Ū`, where `Ū = U e^{−iψ}` is the spin-1 quantity +# `U = u_θ + i u_φ` rotated by the bearing `ψ` of the geodesic toward the other point. At the second +# point the frame continues the geodesic, so its tangent has bearing `ψ + π` and the frame components +# there are `−Ū`. Hence `δu_L + i δu_T = −(Ū_i + Ū_j)`; a radial component and a scalar difference as +# `w_j − w_i`, `θ_j − θ_i`. Every polynomial operator is a polynomial in these, and every monomial +# splits into a product at `i` and a product at `j`, each a spin-weighted monomial of the field. + +# A monomial of the point quantities at one end: powers of U_v, conj(U_v), the radial component of +# field v, and the scalar fields; its spin is Σ_v (a_v − b_v). +struct SiteMonomial{V, K} + a::NTuple{V, Int} + b::NTuple{V, Int} + r::NTuple{V, Int} + c::NTuple{K, Int} +end + +_spin(p::SiteMonomial) = sum(p.a; init = 0) - sum(p.b; init = 0) +_conjugate(p::SiteMonomial) = SiteMonomial(p.b, p.a, p.r, p.c) + +# Site variables of a pair, as positions in an exponent tuple: for field v the four +# (Ū_i, conj Ū_i, Ū_j, conj Ū_j), then (w_i, w_j) per field on a shell, then (θ_i, θ_j) per scalar. +struct SiteLayout{V, K, R} end +@inline _n_vars(::SiteLayout{V, K, R}) where {V, K, R} = Val(4V + (R ? 2V : 0) + 2K) +_exponent_type(::SiteLayout{V, K, R}) where {V, K, R} = NTuple{4V + (R ? 2V : 0) + 2K, Int} +_ubar(::SiteLayout, v, end_) = 4(v - 1) + (end_ == 1 ? 1 : 3) +_cubar(::SiteLayout, v, end_) = 4(v - 1) + (end_ == 1 ? 2 : 4) +_rad(::SiteLayout{V}, v, end_) where {V} = 4V + 2(v - 1) + end_ +_sca(::SiteLayout{V, K, R}, k, end_) where {V, K, R} = 4V + (R ? 2V : 0) + 2(k - 1) + end_ + +_unit_exponent(l::SiteLayout, i) = ntuple(j -> Int(j == i), _n_vars(l)) +_zero_exponent(l::SiteLayout) = ntuple(_ -> 0, _n_vars(l)) + +# The increment of packed component `comp` as a polynomial over the site variables. +function _increment_polynomial(l::SiteLayout{V}, comp::Int, D::Int) where {V} + p = Dict{_exponent_type(l), ComplexF64}() + if comp <= V * D + v = (comp - 1) ÷ D + 1 + d = (comp - 1) % D + 1 + if d == 1 + for e in (_ubar(l, v, 1), _ubar(l, v, 2), _cubar(l, v, 1), _cubar(l, v, 2)) + p[_unit_exponent(l, e)] = -0.5 + end + elseif d == 2 + for e in (_ubar(l, v, 1), _ubar(l, v, 2)) + p[_unit_exponent(l, e)] = 0.5im + end + for e in (_cubar(l, v, 1), _cubar(l, v, 2)) + p[_unit_exponent(l, e)] = -0.5im + end + else + p[_unit_exponent(l, _rad(l, v, 2))] = 1.0 + p[_unit_exponent(l, _rad(l, v, 1))] = -1.0 + end + else + k = comp - V * D + p[_unit_exponent(l, _sca(l, k, 2))] = 1.0 + p[_unit_exponent(l, _sca(l, k, 1))] = -1.0 + end + return p +end + +function _poly_mul(p::Dict{E, ComplexF64}, q::Dict{E, ComplexF64}) where {E} + out = Dict{E, ComplexF64}() + for (e1, c1) in p, (e2, c2) in q + e = e1 .+ e2 + out[e] = get(out, e, zero(ComplexF64)) + c1 * c2 + end + return out +end + +# The polynomial of `sf` in the site variables: Σ_a c_a Π_k δu_{a_k}, with `c_a` the coefficient of +# each monomial of the packed increment read off the operator's contraction of a basis moment tensor. +function _operator_polynomial(sf, ::Val{D}, ::Val{V}, ::Val{K}) where {D, V, K} + P = SFT.order(sf) + W = V * D + K + lay = SiteLayout{V, K, D == 3}() + ê₁ = SA.SVector{D, Float64}(ntuple(i -> i == 1 ? 1.0 : 0.0, Val(D))) + idx = SFT.symmetric_indices(Val(W), Val(P)) + N = length(idx) + incr = [_increment_polynomial(lay, comp, D) for comp in 1:W] + total = Dict{_exponent_type(lay), ComplexF64}() + for (n, a) in enumerate(idx) + E = SFT.SymmetricMoments{W, P}(SA.SVector{N, Float64}(ntuple(i -> i == n ? 1.0 : 0.0, Val(N)))) + c = SFT.moment_contract(sf, E, ê₁, Val(V), Val(K)) + iszero(c) && continue + mono = Dict{_exponent_type(lay), ComplexF64}(_zero_exponent(lay) => 1.0) + for comp in a + mono = _poly_mul(mono, incr[comp]) + end + for (e, coef) in mono + total[e] = get(total, e, zero(ComplexF64)) + c * coef + end + end + return total, lay +end + +# Split each monomial into the product at `i`, a spin-weighted monomial `F` of the field, and the +# product at `j`, which is the conjugate of a spin-weighted monomial `G`. Returns (F, G) => coefficient. +function _operator_terms(sf, vD::Val{D}, vV::Val{V}, vK::Val{K}) where {D, V, K} + poly, lay = _operator_polynomial(sf, vD, vV, vK) + radial = D == 3 + terms = Dict{Tuple{SiteMonomial{V, K}, SiteMonomial{V, K}}, ComplexF64}() + for (e, coef) in poly + F = SiteMonomial(ntuple(v -> e[_ubar(lay, v, 1)], Val(V)), ntuple(v -> e[_cubar(lay, v, 1)], Val(V)), + ntuple(v -> radial ? e[_rad(lay, v, 1)] : 0, Val(V)), ntuple(k -> e[_sca(lay, k, 1)], Val(K))) + G = SiteMonomial(ntuple(v -> e[_cubar(lay, v, 2)], Val(V)), ntuple(v -> e[_ubar(lay, v, 2)], Val(V)), + ntuple(v -> radial ? e[_rad(lay, v, 2)] : 0, Val(V)), ntuple(k -> e[_sca(lay, k, 2)], Val(K))) + key = (F, G) + terms[key] = get(terms, key, zero(ComplexF64)) + coef + end + return terms +end + +# --------------------------------------------------------------------------------------------------- +# The sweep +# --------------------------------------------------------------------------------------------------- + +# Point-wise values of a site monomial, weighted and masked: zero where the point holds nothing. +function _monomial_values(p::SiteMonomial, U::AbstractMatrix{ComplexF64}, R::AbstractMatrix, + Θ::AbstractMatrix, wm::AbstractVector) + N = length(wm) + out = Vector{ComplexF64}(undef, N) + @inbounds for i in 1:N + if iszero(wm[i]) + out[i] = 0 + continue + end + v = ComplexF64(wm[i]) + for c in eachindex(p.a) + v *= U[c, i]^p.a[c] * conj(U[c, i])^p.b[c] * R[c, i]^p.r[c] + end + for k in eachindex(p.c) + v *= Θ[k, i]^p.c[k] + end + out[i] = v + end + return out +end + +# Pseudo-coefficients of every site monomial the operator needs, one transform per distinct monomial +# of non-negative spin; a negative spin is the conjugate of a monomial already transformed. The mask's +# transform, taken at construction, fixes the coefficient array type. +mutable struct HarmonicTransforms{P, M <: SiteMonomial, AT <: AbstractMatrix{ComplexF64}} + provider::P + lmax::Int + cache::Dict{M, AT} + transforms::Int +end + +function HarmonicTransforms(provider, lmax::Int, mask::SiteMonomial, U, R, Θ, wm) + C = provider(_monomial_values(mask, U, R, Θ, wm), 0) + return HarmonicTransforms(provider, lmax, Dict{typeof(mask), typeof(C)}(mask => C), 1) +end + +function _coefficients!(ht::HarmonicTransforms, p::SiteMonomial, U, R, Θ, wm) + cached = get(ht.cache, p, nothing) + cached === nothing || return cached + s = _spin(p) + if s < 0 + C = _conjugate_field_coefficients(_coefficients!(ht, _conjugate(p), U, R, Θ, wm), -s, ht.lmax) + else + C = ht.provider(_monomial_values(p, U, R, Θ, wm), s) + ht.transforms += 1 + end + ht.cache[p] = C + return C +end + +@inline _spin_sign(s::Integer) = isodd(s) ? -1 : 1 + +""" + _sphere_angles(geometry, x) -> (θ, φ) + +Colatitude and longitude in radians of each point of `x`, given as `(lon, lat)` in the geometry's +metric's own angle unit. +""" +function _sphere_angles(g::SFH.SphericalGeometry, x::AbstractMatrix) + size(x, 1) == 2 || throw(DimensionMismatch("a point on a sphere is (lon, lat); got $(size(x, 1)) coordinates")) + N = size(x, 2) + θ = Vector{Float64}(undef, N) + φ = Vector{Float64}(undef, N) + @inbounds for i in 1:N + p = SFH.unit_position(g.metric, x[1, i], x[2, i]) + θ[i] = acos(clamp(p[3], -1.0, 1.0)) + φ[i] = mod(atan(p[2], p[1]), 2π) + end + return θ, φ +end + +""" + harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes, ::Val{D}, ::Val{V}, ::Val{K}, spectral_backend; valid) + +Accumulate the kernel-binned pair statistic of `sf` at the nodes' separations into `sums`, and the +kernel-weighted pair count into `counts`, from spherical-harmonic pseudo-coefficients of the masked, +weighted field. `x` is `(lon, lat)` per point in the metric's angle unit; `data` is the packed field +with vector fields in `(east, north[, radial])` components; `weights` one weight per point; `valid` +which points hold a datum. `spectral_backend` names what computes the pseudo-coefficients: the +direct sum, `O(N lmax²)`, or a fast spherical harmonic transform from an extension. + +For a spin-`s` monomial `F` at one end and a spin-`s′` monomial `G` at the other, rotated into the +pair's geodesic frame, + +``` +Σ_{ij} w_i w_j F̄_i conj(Ḡ_j) K^{ss′}(γ_ij, β) = (−1)^s Σ_l (2l+1)/(4π) b_l X^{FG}_l d^l_{ss′}(β), +K^{ss′}(γ, β) = (1/16π²) Σ_l (2l+1) b_l d^l_{ss′}(γ) d^l_{ss′}(β), +``` + +with `X^{FG}_l = (1/(2l+1)) Σ_m F̃_lm conj(G̃_lm)` the cross pseudo-spectrum, so every polynomial +operator is a finite sum of such series and the counts are the mask's own Legendre series. The +kernel tends to `(1/8π²) δ(cos γ − cos β)` as `lmax` grows, so the ratio `sums ./ counts` tends to +the hard-binned pair average. + +An operator odd in a scalar increment is refused: the kernel sum runs over both readings of every +pair, so such a moment is identically zero here. +""" +harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes::HarmonicNodes, ::Val{D}, ::Val{V}, ::Val{K}, + ::SB.AbstractDirectSumSpectralBackend; valid = AllValid()) where {D, V, K} = + _harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes, Val(D), Val(V), Val(K), valid, + direct_sum_provider) + +harmonic_sweep!(sums, counts, sf, geometry, x, weights, data, nodes::HarmonicNodes, ::Val{D}, ::Val{V}, ::Val{K}, + spectral_backend; valid = AllValid()) where {D, V, K} = _no_harmonic_provider(spectral_backend) + +_no_harmonic_provider(spectral_backend) = throw(ArgumentError( + "no method computes spherical harmonic pseudo-coefficients with $(typeof(spectral_backend)). " * + "DirectSumSpectralBackend() is the direct sum; `using NUFSHT` supplies the fast transform " * + "(NUFSHTSpectralBackend()).", +)) + +function _harmonic_sweep!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + g::SFH.SphericalGeometry, x::AbstractMatrix, weights::AbstractVector, data::AbstractMatrix, + nodes::HarmonicNodes, ::Val{D}, ::Val{V}, ::Val{K}, valid, make_provider, +) where {OT, CT <: AbstractFloat, D, V, K} + SFT.is_polynomial_operator(sf) || throw(ArgumentError( + "$(typeof(sf)) is not a polynomial in the increment, so no harmonic series produces it; " * + "the pair loop evaluates any pairwise operator.", + )) + SFT.is_odd_in_scalars(sf) && throw(ArgumentError( + "$(typeof(sf)) is odd in a scalar increment, and a harmonic kernel sums both readings of " * + "every pair, so the moment is identically zero on this route. Use the pair loop, which reads " * + "each pair once by its convention.", + )) + validate_fields(sf, Val(V), Val(K)) + (V == 0 || D == 2 || D == 3) || throw(ArgumentError( + "a vector field on a sphere has 2 components (east, north) or 3 (with radial); got $D", + )) + N = size(x, 2) + W = V * D + K + size(data) == (W, N) || throw(DimensionMismatch( + "field is $(size(data)); expected ($W, $N) for $N points", + )) + length(weights) == N || throw(DimensionMismatch("$(length(weights)) weights for $N points")) + nb = length(nodes) + length(sums) == nb && length(counts) == nb || throw(DimensionMismatch( + "sums and counts must have one entry per node, $nb; got $(length(sums)) and $(length(counts))", + )) + + θ, φ = _sphere_angles(g, x) + # the spin-1 quantity u_θ + i u_φ of each vector field: θ̂ is south, φ̂ is east + U = Matrix{ComplexF64}(undef, V, N) + R = Matrix{Float64}(undef, V, N) + Θ = Matrix{Float64}(undef, K, N) + wm = Vector{Float64}(undef, N) + @inbounds for i in 1:N + ok = valid[i] + wm[i] = ok ? Float64(weights[i]) : 0.0 + for v in 1:V + o = (v - 1) * D + U[v, i] = ok ? ComplexF64(-data[o + 2, i], data[o + 1, i]) : 0 + R[v, i] = (ok && D == 3) ? data[o + 3, i] : 0.0 + end + for k in 1:K + Θ[k, i] = ok ? data[V * D + k, i] : 0.0 + end + end + + L = nodes.lmax + lf = _log_factorials(2L + 2) + mask = SiteMonomial(ntuple(_ -> 0, Val(V)), ntuple(_ -> 0, Val(V)), ntuple(_ -> 0, Val(V)), ntuple(_ -> 0, Val(K))) + ht = HarmonicTransforms(make_provider(θ, φ, L), L, mask, U, R, Θ, wm) + Cm = _coefficients!(ht, mask, U, R, Θ, wm) + kernels = Dict{Tuple{Int, Int}, Matrix{Float64}}() + kernel(s, s′) = get!(kernels, (s, s′)) do + _node_kernel(s, s′, nodes, lf) + end + Xmm = _cross_spectrum(Cm, Cm, L) + K00 = kernel(0, 0) + @inbounds for k in 1:nb + acc = zero(ComplexF64) + for l in 0:L + acc += Xmm[l + 1] * K00[l + 1, k] + end + counts[k] += CT(real(acc)) + end + + acc = zeros(ComplexF64, nb) + for ((F, G), coef) in _operator_terms(sf, Val(D), Val(V), Val(K)) + s, s′ = _spin(F), _spin(G) + X = _cross_spectrum(_coefficients!(ht, F, U, R, Θ, wm), _coefficients!(ht, G, U, R, Θ, wm), L) + Kd = kernel(s, s′) + sign = _spin_sign(s) + @inbounds for k in 1:nb + series = zero(ComplexF64) + for l in 0:L + series += X[l + 1] * Kd[l + 1, k] + end + acc[k] += coef * sign * series + end + end + @inbounds for k in 1:nb + sums[k] += OT(real(acc[k])) + end + return sums, counts +end + +""" + calculate_structure_function(sf, x, u, nodes::HarmonicNodes, spectral_backend; distance_metric, weights, valid, output_type) + +The kernel-binned structure function of `u` sampled at the points `x` of a sphere, at the nodes' +separations, by spherical harmonic pseudo-coefficients (see [`harmonic_sweep!`](@ref)). `x` is +`(lon, lat)` in the angle unit of `distance_metric`, which must be spherical; `u` is a `(D, cells...)` +field of `(east, north[, radial])` components, a `(1, cells...)` scalar, or a multi-field, with +`prod(cells) == size(x, 2)`. `weights` default to +one per point; on a grid the cell measure makes the statistic an area average. + +The result's `distance` is the `HarmonicNodes` object itself, one value per node, and its counts are +the kernel-weighted pair counts, floating point. +""" +function calculate_structure_function( + sf::SFT.AbstractPairwiseStructureFunctionType, x::AbstractMatrix, u::Union{AbstractArray, MF.Fields}, + nodes::HarmonicNodes, spectral_backend; + distance_metric::DI.PreMetric = DI.SphericalAngle(), weights = nothing, valid = nothing, + output_type::Type{OT} = SFO.StructureFunction, verbose::Bool = true, show_progress::Bool = true, +) where {OT} + data, vD, vV, vK = _packed(u) + D = SFC_val_int(vD) + V = SFC_val_int(vV) + geometry = SFH.pair_geometry_for(distance_metric, Val(V == 0 ? 2 : D)) + geometry isa SFH.SphericalGeometry || throw(ArgumentError( + "a harmonic structure function lives on a sphere; $(typeof(distance_metric)) describes none. " * + "Pass SphericalAngle(), SphericalDistance(R) or Haversine(R).", + )) + N = size(x, 2) + w = weights === nothing ? ones(Float64, N) : weights + v = valid === nothing ? field_validity(data) : valid + nb = length(nodes) + sums = zeros(float(eltype(data)), nb) + counts = zeros(Float64, nb) + verbose && @info "harmonic structure function: $(nb) nodes, lmax = $(nodes.lmax), $(nameof(typeof(spectral_backend)))" + harmonic_sweep!(sums, counts, sf, geometry, x, w, data, nodes, vD, vV, vK, spectral_backend; valid = v) + return _finalize(SFO.StructureFunctionSumsAndCounts(sf, nodes, sums, counts), OT) +end + +# --------------------------------------------------------------------------------------------------- +# Pseudo-spectra +# --------------------------------------------------------------------------------------------------- + +""" + harmonic_spectra(x, u, lmax, spectral_backend; distance_metric, weights, valid) -> (l, C) or (l, EE, BB, EB) + +Pseudo-spectra of the masked, weighted field: `C̃_l = (1/(2l+1)) Σ_m |ũ_lm|²` for a `(1, N)` scalar; +for a `(2, N)` tangent vector in `(east, north)`, the gradient (`E`) and curl (`B`) spectra and their +cross spectrum from the spin-1 coefficients `₁U_lm` of `U = u_θ + i u_φ` and the spin-(−1) coefficients +`₋₁Ū_lm` of its conjugate, which follow from the first as `₋₁Ū_lm = (−1)^{m+1} conj(₁U_{l,−m})`: + +``` +Φ_lm = (₁U_lm − ₋₁Ū_lm) / (2√(l(l+1))), Ψ_lm = −i (₁U_lm + ₋₁Ū_lm) / (2√(l(l+1))), +C^E_l = l(l+1) (1/(2l+1)) Σ_m |Φ_lm|², C^B_l likewise from Ψ, C^{EB}_l from Φ conj(Ψ), +``` + +so that `Σ_l (2l+1)/(4π) (C^E_l + C^B_l)` is the mean square of `u` on a complete sphere with exact +quadrature weights. On a masked or unevenly sampled sphere these are the pseudo-spectra of the +window and the field together, the input to the kernel-binned statistics. +""" +harmonic_spectra(x::AbstractMatrix, u::AbstractMatrix, lmax::Integer, ::SB.AbstractDirectSumSpectralBackend; + distance_metric::DI.PreMetric = DI.SphericalAngle(), weights = nothing, valid = nothing) = + _harmonic_spectra(x, u, lmax, distance_metric, weights, valid, direct_sum_provider) + +harmonic_spectra(x::AbstractMatrix, u::AbstractMatrix, lmax::Integer, spectral_backend; + distance_metric::DI.PreMetric = DI.SphericalAngle(), weights = nothing, valid = nothing) = + _no_harmonic_provider(spectral_backend) + +function _harmonic_spectra(x::AbstractMatrix, u::AbstractMatrix, lmax::Integer, distance_metric, weights, + valid, make_provider) + D = size(u, 1) + D in (1, 2) || throw(ArgumentError( + "harmonic spectra are defined for a scalar (1, N) or a tangent vector (2, N) in (east, north); got $D rows", + )) + N = size(x, 2) + size(u, 2) == N || throw(DimensionMismatch("$N points and $(size(u, 2)) samples")) + g = SFH.pair_geometry_for(distance_metric, Val(2)) + g isa SFH.SphericalGeometry || throw(ArgumentError( + "harmonic spectra live on a sphere; $(typeof(distance_metric)) describes none.", + )) + θ, φ = _sphere_angles(g, x) + w = weights === nothing ? ones(Float64, N) : weights + v = valid === nothing ? field_validity(u) : valid + wm = [v[i] ? Float64(w[i]) : 0.0 for i in 1:N] + provider = make_provider(θ, φ, lmax) + l = 0:lmax + if D == 1 + f = [iszero(wm[i]) ? 0.0 : wm[i] * u[1, i] for i in 1:N] + C = provider(f, 0) + return (l = l, C = real.(_cross_spectrum(C, C, lmax))) + end + U = [iszero(wm[i]) ? zero(ComplexF64) : wm[i] * ComplexF64(-u[2, i], u[1, i]) for i in 1:N] + Cp = provider(U, 1) # ₁U, the spin-1 coefficients of u_θ + i u_φ + Cm = _conjugate_field_coefficients(Cp, 1, lmax) # ₋₁[conj U], those of u_θ − i u_φ + Φ = zeros(ComplexF64, lmax + 1, 2lmax + 1) + Ψ = zeros(ComplexF64, lmax + 1, 2lmax + 1) + @inbounds for ll in 1:lmax, m in -ll:ll + f = 1 / (2 * sqrt(ll * (ll + 1))) + Φ[ll + 1, m + lmax + 1] = (Cp[ll + 1, m + lmax + 1] - Cm[ll + 1, m + lmax + 1]) * f + Ψ[ll + 1, m + lmax + 1] = -im * (Cp[ll + 1, m + lmax + 1] + Cm[ll + 1, m + lmax + 1]) * f + end + weight = [Float64(ll * (ll + 1)) for ll in l] + EE = real.(_cross_spectrum(Φ, Φ, lmax)) .* weight + BB = real.(_cross_spectrum(Ψ, Ψ, lmax)) .* weight + EB = real.(_cross_spectrum(Φ, Ψ, lmax)) .* weight + return (l = l, EE = EE, BB = BB, EB = EB) +end diff --git a/src/Calculations/lag_moments.jl b/src/Calculations/lag_moments.jl new file mode 100644 index 0000000..7ca8fad --- /dev/null +++ b/src/Calculations/lag_moments.jl @@ -0,0 +1,232 @@ +# The lag algebra of the transform engine: which monomials a moment reads, how the inverted columns +# combine under the frames, and the operator on one lag. Pure functions of static sizes, shared by the +# host loop and the device kernel. + +"""A monomial key of any degree up to `Pm`, zero-padded.""" +@inline function _padded_key(::Val{Pm}, key::Tuple) where {Pm} + length(key) <= Pm || throw(ArgumentError("a monomial of degree $(length(key)) exceeds the cache's degree $Pm")) + return ntuple(i -> i <= length(key) ? Int(key[i]) : 0, Val(Pm)) +end + +"""Pairs a lag names between two complete slabs: every cell on a wrapping direction, the overlap on a bounded one.""" +@inline _lag_pair_count(s::UniformLagSchedule{Dg}, h::NTuple{Dg, Int}) where {Dg} = + prod(ntuple(d -> @inbounds(s.periodic[d]) ? @inbounds(s.dims[d]) : + @inbounds(s.dims[d]) - abs(h[d]), Val(Dg))) + +""" +Pairs a lag names between two slabs: the count column of the inverted transforms when the field is masked +or weighted (a weighted pair mass in the latter case), the slab overlap otherwise; halved on a lag equal +to its own reverse. +""" +@inline function _named_pairs(::Val{false}, masked::Bool, out, idx::Int, ncol::Int, su::UniformLagSchedule, h, + self_reverse::Bool) + n = masked ? round(Int, @inbounds(out[idx, ncol])) : _lag_pair_count(su, h) + return self_reverse ? n ÷ 2 : n +end + +@inline function _named_pairs(::Val{true}, ::Bool, out, idx::Int, ncol::Int, ::UniformLagSchedule, h, + self_reverse::Bool) + n = @inbounds out[idx, ncol] + return self_reverse ? n / 2 : n +end + +"""Whether a sweep carries pair weights, as a `Val` the kernels specialise on.""" +@inline _weighted_val(::NoWeights) = Val(false) +@inline _weighted_val(::AbstractVector) = Val(true) + +"""Column-major strides of a transform of size `P`.""" +@inline _lag_strides(P::NTuple{Dg, Int}) where {Dg} = + ntuple(d -> prod(ntuple(k -> P[k], d - 1); init = 1), Val(Dg)) + +"""Linear position of lag `h` in a transform of size `P`, wrapping the negative offsets.""" +@inline function _lag_index(h::NTuple{Dg, Int}, P::NTuple{Dg, Int}, strides::NTuple{Dg, Int}) where {Dg} + lin = 1 + @inbounds for d in 1:Dg + lin += mod(h[d], P[d]) * strides[d] + end + return lin +end + + +"""Every sorted multi-index of degree `0:P` over `W` components, zero-padded to `P`: the monomials a degree-`P` moment reads.""" +function _monomial_keys(::Val{W}, ::Val{P}) where {W, P} + keys = NTuple{P, Int}[] + for d in 0:P, k in SFT.symmetric_indices(Val(W), Val(d)) + push!(keys, _padded_key(Val(P), k)) + end + return keys +end + +# Raw cross-moments under frame transport: for k = 0..P, every sorted multi-index over the first slab +# of degree P − k with every sorted one over the second of degree k, in that order. +function _raw_columns(::Val{W}, ::Val{P}) where {W, P} + cols = Tuple{Tuple{Vararg{Int}}, Tuple{Vararg{Int}}}[] + for k in 0:P, cI in SFT.symmetric_indices(Val(W), Val(P - k)), cJ in SFT.symmetric_indices(Val(W), Val(k)) + push!(cols, (cI, cJ)) + end + return cols +end + +_n_raw(W::Int, P::Int) = sum(binomial(W + P - k - 1, P - k) * binomial(W + k - 1, k) for k in 0:P) + +# Each inverse column as the signed products `sign · conj(F_I[keyI]) · F_J[keyJ]` it sums; keys are +# positions in the monomial key list. +function _columns(::IdentityTransport, ::Val{W}, ::Val{P}, key_index::Dict) where {W, P} + cols = Vector{Vector{NTuple{3, Int}}}() + for j in SFT.symmetric_indices(Val(W), Val(P)) + terms = NTuple{3, Int}[] + for mask in 0:((1 << P) - 1) + primed = Tuple(j[k] for k in 1:P if (mask >> (k - 1)) & 1 == 1) + unprimed = Tuple(j[k] for k in 1:P if (mask >> (k - 1)) & 1 == 0) + sign = isodd(P - length(primed)) ? -1 : 1 + push!(terms, (sign, key_index[_padded_key(Val(P), unprimed)], key_index[_padded_key(Val(P), primed)])) + end + push!(cols, terms) + end + return cols +end + +_columns(::FrameTransport, ::Val{W}, ::Val{P}, key_index::Dict) where {W, P} = + [[(1, key_index[_padded_key(Val(P), cI)], key_index[_padded_key(Val(P), cJ)])] + for (cI, cJ) in _raw_columns(Val(W), Val(P))] + +_inverse_count(::IdentityTransport, W::Int, P::Int) = binomial(W + P - 1, P) +_inverse_count(::FrameTransport, W::Int, P::Int) = _n_raw(W, P) + +""" + _frame_moments(A, B, raw, scale, Val(W), Val(P)) -> SymmetricMoments{W, P} + +The symmetric increment moment tensor of one lag from its raw cross-moments under the frames `A`, +`B`: `Σ_S (−1)^{P−|S|} Π_{k∈S} B_{a_k c_k} Π_{k∉S} A_{a_k c_k} · X[m u_{c_{S^c}}, m u_{c_S}]`. For each +`k = |S|` the raw block is transformed mode by mode — `A` on the first `P − k` slots, `B` on the +rest — and read at every placement of `k` slots of the sorted multi-index. +""" +@generated function _frame_moments( + A::SA.SMatrix{W, W, TA}, B::SA.SMatrix{W, W, TB}, raw::SA.SVector{NR, TR}, scale, + ::Val{W}, ::Val{P}, +) where {W, TA, TB, NR, TR, P} + T = promote_type(TA, TB, TR) + L = W^P + cols = _raw_columns(Val(W), Val(P)) + col_of = Dict(c => n for (n, c) in enumerate(cols)) + sorted = SFT.symmetric_indices(Val(W), Val(P)) + N = length(sorted) + digits_of(lin) = ntuple(i -> (lin ÷ W^(i - 1)) % W + 1, P) + body = Expr[] + for k in 0:P + table = ntuple(L) do l + d = digits_of(l - 1) + col_of[(Tuple(sort(collect(d[1:(P - k)]))), Tuple(sort(collect(d[(P - k + 1):P]))))] + end + push!(body, :(for lin in 1:$L + dense[lin] = raw[$(table)[lin]] + end)) + for i in 1:P + mat = i <= P - k ? :A : :B + stride = W^(i - 1) + push!(body, quote + for lin in 0:$(L - 1) + d = (lin ÷ $stride) % $W + base = lin - d * $stride + acc = zero($T) + for b in 0:$(W - 1) + acc += $mat[d + 1, b + 1] * dense[base + b * $stride + 1] + end + tmp[lin + 1] = acc + end + dense, tmp = tmp, dense + end) + end + sign = isodd(P - k) ? -1 : 1 + for (n, a) in enumerate(sorted) + lins = Int[] + for mask in 0:((1 << P) - 1) + count_ones(mask) == k || continue + S = [i for i in 1:P if (mask >> (i - 1)) & 1 == 1] + Sc = [i for i in 1:P if (mask >> (i - 1)) & 1 == 0] + lin = 0 + for (i, slot) in enumerate(Sc) + lin += (a[slot] - 1) * W^(i - 1) + end + for (j, slot) in enumerate(S) + lin += (a[slot] - 1) * W^(P - k + j - 1) + end + push!(lins, lin + 1) + end + push!(body, :(for lin in $(Tuple(lins)) + m[$n] += $sign * dense[lin] + end)) + end + end + return quote + dense = SA.MVector{$L, $T}(undef) + tmp = SA.MVector{$L, $T}(undef) + m = zero(SA.MVector{$N, $T}) + @inbounds begin + $(body...) + end + return SFT.SymmetricMoments{$W, $P}(SA.SVector(m) * scale) + end +end + +# The moment tensor of one lag from the inverted columns; a self-reverse lag's columns hold each pair +# twice, with equal values, so `scale` halves them. +@inline function _lag_moments( + ::IdentityTransport, out, idx::Int, scale::T, A, B, ::Val{W}, ::Val{P}, ::Val{N}, +) where {T, W, P, N} + return SFT.SymmetricMoments{W, P}(SA.SVector{N, T}(ntuple(n -> T(@inbounds(out[idx, n])) * scale, Val(N)))) +end + +@inline function _lag_moments( + ::FrameTransport, out, idx::Int, scale::T, A, B, ::Val{W}, ::Val{P}, ::Val{N}, +) where {T, W, P, N} + raw = SA.SVector{N, T}(ntuple(n -> T(@inbounds(out[idx, n])), Val(N))) + return _frame_moments(A, B, raw, scale, Val(W), Val(P)) +end + +# The symmetric moment store of one lag, averaged over the lag's frames where the transport gives it +# more than one. +@inline function _lag_tensor( + tr::IdentityTransport, out, idx, scale::T, geometry, ::Val{W}, ::Val{P}, ::Val{N}, +) where {T, W, P, N} + return _lag_moments(tr, out, idx, scale, nothing, nothing, Val(W), Val(P), Val(N)).data +end + +@inline function _lag_tensor( + tr::FrameTransport, out, idx, scale::T, geometry, ::Val{W}, ::Val{P}, ::Val{N}, +) where {T, W, P, N} + return with_frames(tr, geometry) do frames + acc = _lag_moments(tr, out, idx, scale, frames[1].A, frames[1].B, Val(W), Val(P), Val(N)).data + for m in 2:length(frames) + f = frames[m] + acc += _lag_moments(tr, out, idx, scale, f.A, f.B, Val(W), Val(P), Val(N)).data + end + acc / length(frames) + end +end + +# The operator on one lag, averaged over the lag's frames. +@inline function _lag_value( + tr::IdentityTransport, sf, out, idx, scale::T, frames::NTuple{M, <:NamedTuple}, inv_r, + ::Val{W}, ::Val{P}, ::Val{N}, ::Val{V}, ::Val{K}, +) where {T, M, W, P, N, V, K} + Mo = _lag_moments(tr, out, idx, scale, nothing, nothing, Val(W), Val(P), Val(N)) + acc = zero(T) + for f in frames + acc += SFT.moment_contract(sf, Mo, f.dir * inv_r, Val(V), Val(K)) + end + return acc / M +end + +@inline function _lag_value( + tr::FrameTransport, sf, out, idx, scale::T, frames::NTuple{M, <:NamedTuple}, inv_r, + ::Val{W}, ::Val{P}, ::Val{N}, ::Val{V}, ::Val{K}, +) where {T, M, W, P, N, V, K} + acc = zero(T) + for f in frames + Mo = _lag_moments(tr, out, idx, scale, f.A, f.B, Val(W), Val(P), Val(N)) + acc += SFT.moment_contract(sf, Mo, f.dir, Val(V), Val(K)) + end + return acc / M +end + diff --git a/src/Calculations/multifields.jl b/src/Calculations/multifields.jl new file mode 100644 index 0000000..9b78be6 --- /dev/null +++ b/src/Calculations/multifields.jl @@ -0,0 +1,428 @@ +# Multi-field pair sweep. A field carrying more than one field forms its increment field by +# field — vectors transported, scalars differenced — and hands the whole multi-field to the operator, +# which reads the fields it names. + +""" + field_increment(::Fields{D,V,K}, data, geom, frame, r, i, j) -> FieldIncrement + +One pair's increment across every field of a packed field. + +Each vector field is transported into the pair's common frame before differencing, exactly as a +single-field case is; each scalar field is differenced where it stands, because a scalar has +nothing to transport. +""" +@inline function field_increment( + ::Val{F}, ::Val{V}, ::Val{K}, data::AbstractMatrix{T}, geom, frame, i::Integer, j::Integer, +) where {F, V, K, T} + vectors = ntuple(Val(V)) do c + o = (c - 1) * F + a = SA.SVector{F, T}(ntuple(d -> @inbounds(data[o + d, i]), Val(F))) + b = SA.SVector{F, T}(ntuple(d -> @inbounds(data[o + d, j]), Val(F))) + SFH.pair_delta(geom, frame, nothing, nothing, a, b) + end + scalars = ntuple(Val(K)) do c + @inbounds data[V * F + c, j] - data[V * F + c, i] + end + Dp = V == 0 ? 0 : length(first(vectors)) + return MF.FieldIncrement{Dp, V, K, T}(vectors, scalars) +end + +""" + _field_value(sf, ::Val{F}, ::Val{V}, ::Val{K}, data, geom, frame, r, i, j) + +One pair's operator value for a multi-field, with the pair read in its canonical orientation +(see `pair_orientation`): an operator odd in a scalar increment takes the orientation's sign. +""" +@inline function _field_value(sf, ::Val{F}, ::Val{V}, ::Val{K}, data, geom, frame, r, i, j) where {F, V, K} + inc = field_increment(Val(F), Val(V), Val(K), data, geom, frame, i, j) + v = sf(inc, SFH.pair_direction(geom, frame, r)) + return SFT.is_odd_in_scalars(sf) ? SFH.pair_orientation(geom, frame) * v : v +end + +""" + _kernel_fields(fields, geom, x) -> (x_kernel, packed_kernel, Val{F}) + +The field in the form the kernels index: every vector field widened by the geometry exactly as a +single-field case is, scalars untouched. + +On a sphere a velocity is carried as an ambient 3-vector, so a multi-field's vector fields must be +widened too — the same `prepare_pair_inputs` the array path uses, once per field, so there is no +second conversion to drift from it. +""" +function _kernel_fields(f::MF.Fields{D, V, K}, geom, x::AbstractMatrix) where {D, V, K} + data = MF.packed(f) + N = size(data, 2) + F = SFC_val_int(SFH.field_width(geom)) + if F == D + return SFH.prepare_coordinates(geom, x), data, Val(D) + end + T = float(eltype(data)) + out = Matrix{T}(undef, V * F + K, N) + @inbounds for c in 1:V + rows = ((c - 1) * D + 1):(c * D) + _, vk = SFH.prepare_pair_inputs(geom, x, @view(data[rows, :])) + out[((c - 1) * F + 1):(c * F), :] .= vk + end + @inbounds for c in 1:K + out[V * F + c, :] .= @view(data[V * D + c, :]) + end + return SFH.prepare_coordinates(geom, x), out, Val(F) +end + +""" + serial_calculate_structure_function!(sums, counts, sf, x, fields, distance_bins; kwargs...) + +Accumulate a multi-field's pairs into the 1-D distance histogram. + +A field of one vector field and no scalars is the array path — it forwards there, so a bare `u` and +`Fields(vectors = (u,))` give the same answer through the same kernel. Anything carrying more than +one field takes this sweep, which builds each pair's whole increment and hands it to the +operator; it is a scalar loop, where the single-field path is a SIMD compute/scatter split. +""" +function serial_calculate_structure_function!( + sums::AbstractVector, counts::AbstractVector, + sf::SFT.AbstractPairwiseStructureFunctionType, + x::AbstractMatrix, f::MF.Fields{D, 1, 0}, distance_bins; + kwargs..., +) where {D} + return serial_calculate_structure_function!(sums, counts, sf, x, MF.packed(f), distance_bins; + kwargs...) +end + +function serial_calculate_structure_function!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + x::AbstractMatrix, f::MF.Fields{D, V, K}, distance_bins; + distance_metric::DI.PreMetric = DI.Euclidean(), + culling::CullingPolicy = AutoCulling(), + weights = nothing, + verbose::Bool = true, + show_progress::Bool = true, +) where {OT, CT, D, V, K} + N = size(MF.packed(f), 2) + size(x, 2) == N || throw(DimensionMismatch( + "x covers $(size(x, 2)) points and the field $N", + )) + w = _pair_weights(weights, N, float(eltype(MF.packed(f)))) + _check_weighted_counts(w, CT) + if _on_a_line(_field_geometry(distance_metric, Val(D), Val(V), x), sf) + _cull_reject_unsupported(culling, "the sorted line route") + return sorted_line_sweep!(sums, counts, sf, _line_coordinates(x), MF.packed(f), distance_bins, + Val(D), Val(V), Val(K); weights = w) + end + geom, xk, data, vF, plan, grid, wk = field_setup(f, x, distance_bins, distance_metric, culling, w) + _field_run_blocks!(sums, counts, sf, xk, data, geom, vF, Val(V), Val(K), plan, + n_histogram_bins(plan), Val(SFC_val_int(SFH.coordinate_width(geom))), + 1:(N - 1), N, grid, wk) + return nothing +end + +"""Whether the pairs lie along a line and the operator is a polynomial the sorted route sums.""" +@inline _on_a_line(geom, sf) = geom isa SFH.FlatGeometry{1} && SFT.is_polynomial_operator(sf) + +"""The one coordinate per point of a `(1, N)` position matrix.""" +function _line_coordinates(x::AbstractMatrix) + size(x, 1) == 1 || throw(DimensionMismatch( + "points on a line carry one coordinate each; got $(size(x, 1)) rows of coordinates", + )) + return vec(x) +end + +""" + field_setup(fields, x, distance_bins, metric, culling, weights = NoWeights()) + -> (geom, xk, data, vF, plan, grid, weights) + +Everything a multi-field sweep needs before its first pair: the geometry, the widened coordinates +and fields, the digitize plan, and the cull grid with both arrays and the weights already permuted +into it. + +Shared by the serial and threaded drivers so the sort and the widening happen **once**, above any +task loop — doing them inside one would pay them per task. +""" +function field_setup(f::MF.Fields{D, V, K}, x::AbstractMatrix, distance_bins, + distance_metric, culling::CullingPolicy, weights = NoWeights()) where {D, V, K} + geom = _field_geometry(distance_metric, Val(D), Val(V), x) + xk, data, vF = _kernel_fields(f, geom, x) + W = SFC_val_int(SFH.coordinate_width(geom)) + plan = squared_digitize_plan(distance_bins) + xc = ntuple(d -> collect(view(xk, d, :)), Val(W)) + grid = culling isa NoCulling ? nothing : cull_grid_for(xc, geom, distance_bins, culling) + if grid !== nothing + xk = xk[:, grid.perm] + data = data[:, grid.perm] + weights = weights isa NoWeights ? weights : weights[grid.perm] + end + return geom, xk, data, vF, plan, grid, weights +end + +# The geometry's dimension is the velocity dimension where there is one; a field of scalars alone has +# none, and its points are located by however many coordinates they carry. +@inline _field_geometry(distance_metric, ::Val{D}, ::Val{V}, x::AbstractMatrix) where {D, V} = + V == 0 ? SFH.pair_geometry_for(distance_metric, Val(size(x, 1))) : + SFH.pair_geometry_for(distance_metric, Val(D)) + +# Dispatch on the grid so the kernel receives one concretely typed schedule, as the single-field +# path does. +@inline _field_run_blocks!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, ilist, N, + ::Nothing, weights) = + _field_pairs!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, + pair_blocks(N, ilist), weights) + +@inline _field_run_blocks!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, ilist, N, + grid::CellGrid, weights) = + _field_pairs!(sums, counts, sf, xk, data, geom, vF, vV, vK, plan, nb, vW, + pair_blocks(N, ilist; grid = grid), weights) + +""" + _field_pairs!(sums, counts, sf, xk, data, geom, ..., blocks, weights) -> nothing + +Accumulate the pairs `blocks` covers for a multi-field, each pair carrying +`weights[i] * weights[j]` in both sums and counts. + +Each block pair is worked to completion, so its columns stay cache-resident across the `i` sweep — +the reason the single-field kernel is blocked, and it applies here for the same reason. +""" +# Flat geometry: the separation IS the displacement, so the whole per-pair computation is arithmetic +# on stack values and the compute half vectorizes — the same compute/scatter split the single-field +# kernel uses, and for the same reason (a scatter in the loop body stops it vectorizing). +function _field_pairs!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + xk::AbstractMatrix, data::AbstractMatrix, geom::SFH.FlatGeometry, ::Val{F}, ::Val{V}, ::Val{K}, + plan::AbstractSquaredDigitizePlan, nb::Int, ::Val{W}, blocks, weights, +) where {OT, CT, F, V, K, W} + FTx = eltype(xk) + T = eltype(data) + N = size(xk, 2) + keybuf = Vector{FTx}(undef, N) + valbuf = Vector{OT}(undef, N) + idxbuf = Vector{Int32}(undef, N) + @inbounds for (ir, jr) in blocks + j_first, j_last = first(jr), last(jr) + for i in ir + jlo = max(i + 1, j_first) + jlo > j_last && continue + Xi = SA.SVector{W, FTx}(ntuple(d -> xk[d, i], Val(W))) + @simd for j in jlo:j_last + Xj = SA.SVector{W, FTx}(ntuple(d -> xk[d, j], Val(W))) + dx = Xj - Xi + r2 = LA.dot(dx, dx) + vectors = ntuple(Val(V)) do c + o = (c - 1) * F + SA.SVector{F, T}(ntuple(d -> data[o + d, j] - data[o + d, i], Val(F))) + end + scalars = ntuple(c -> data[V * F + c, j] - data[V * F + c, i], Val(K)) + inc = MF.FieldIncrement{F, V, K, T}(vectors, scalars) + sgn = SFT.is_odd_in_scalars(sf) ? SFH.pair_orientation(geom, dx) : 1 + keybuf[j] = digitize_key(plan, r2) + valbuf[j] = OT(sgn * sf(inc, dx / sqrt(r2))) + if has_vector_index(plan) + idxbuf[j] = squared_approx_index(plan, r2) + end + end + wi = _point_weight(weights, i) + for j in jlo:j_last + b = squared_bin(plan, keybuf[j], idxbuf[j]) + if 1 <= b <= nb + w = wi * _point_weight(weights, j) + sums[b] += w * valbuf[j] + counts[b] += CT(w) + end + end + end + end + return nothing +end + +function _field_pairs!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + xk::AbstractMatrix, data::AbstractMatrix, geom, ::Val{F}, ::Val{V}, ::Val{K}, + plan::AbstractSquaredDigitizePlan, nb::Int, ::Val{W}, blocks, weights, +) where {OT, CT, F, V, K, W} + FTx = eltype(xk) + @inbounds for (ir, jr) in blocks + j_first, j_last = first(jr), last(jr) + for i in ir + jlo = max(i + 1, j_first) + jlo > j_last && continue + Xi = SA.SVector{W, FTx}(ntuple(d -> xk[d, i], Val(W))) + wi = _point_weight(weights, i) + for j in jlo:j_last + Xj = SA.SVector{W, FTx}(ntuple(d -> xk[d, j], Val(W))) + ok, r, frame = SFH.pair_frame(geom, Xi, Xj) + ok || continue + b = squared_digitize(plan, r * r) + 1 <= b <= nb || continue + w = wi * _point_weight(weights, j) + sums[b] += w * OT(_field_value(sf, Val(F), Val(V), Val(K), data, geom, frame, r, i, j)) + counts[b] += CT(w) + end + end + end + return nothing +end + +@inline SFC_val_int(::Val{W}) where {W} = W + +""" + required_fields(operator) -> (n_vector, n_scalar) + +The highest vector and scalar field index an operator reads. + +Every operator that predates the multi-field reads the field itself, which is field 1 of the +vector side — that is what keeps `Fields(vectors = (u,))` identical to a bare `u`. +""" +@inline required_fields(::SFT.AbstractPairwiseStructureFunctionType) = (1, 0) +@inline required_fields(sf::SFT.ScalarStructureFunctionType) = (0, sf.field) +@inline required_fields(sf::SFT.MixedStructureFunctionType) = + (sf.vector_field, sf.scalar_field) +@inline required_fields(sf::SFT.VectorDotStructureFunctionType) = (max(sf.a, sf.b), 0) +@inline required_fields(sf::SFT.ScalarDotStructureFunctionType) = (0, max(sf.a, sf.b)) + +""" + validate_fields(operator, fields) + +Refuse an operator that reads a field the multi-field does not carry. + +Checked once at the entry, where a threaded backend has not yet opened a task: an error thrown +inside one surfaces wrapped in a `TaskFailedException`. +""" +validate_fields(sf::SFT.AbstractPairwiseStructureFunctionType, ::MF.Fields{D, V, K}) where {D, V, K} = + validate_fields(sf, Val(V), Val(K)) + +function validate_fields(sf::SFT.AbstractPairwiseStructureFunctionType, ::Val{V}, ::Val{K}) where {V, K} + nv, ns = required_fields(sf) + nv <= V || throw(ArgumentError( + "$(nameof(typeof(sf))) reads vector field $nv, but this field carries $V. Build the " * + "multi-field with that field, e.g. `Fields(vectors = (u, 𝓐u))`.", + )) + ns <= K || throw(ArgumentError( + "$(nameof(typeof(sf))) reads scalar field $ns, but this field carries $K. Build the " * + "multi-field with that field, e.g. `Fields(vectors = (u,), scalars = (θ,))`.", + )) + return nothing +end + +""" + field_partial(sf, x, fields, distance_bins, outer; kwargs...) -> (sums, counts) + +A worker's share of a multi-field sweep: the pairs whose lower index is in `outer`, in freshly +allocated accumulators. + +The outer lists partition `1:(N-1)`, so the partials add to the whole sweep exactly. Note the +indices are into the **culled ordering** when culling is on, which is a permutation of the input and +therefore still a partition. +""" +function field_partial( + sf::SFT.AbstractPairwiseStructureFunctionType, x::AbstractMatrix, f::MF.Fields{D, V, K}, + distance_bins, outer; + distance_metric::DI.PreMetric = DI.Euclidean(), + culling::CullingPolicy = AutoCulling(), + count_eltype::Type{CT} = UInt32, +) where {D, V, K, CT} + N = size(MF.packed(f), 2) + nb = n_histogram_bins(squared_digitize_plan(distance_bins)) + sums = zeros(float(eltype(MF.packed(f))), nb) + counts = zeros(CT, nb) + geom, xk, data, vF, plan, grid, wk = field_setup(f, x, distance_bins, distance_metric, culling) + _field_run_blocks!(sums, counts, sf, xk, data, geom, vF, Val(V), Val(K), plan, + n_histogram_bins(plan), Val(SFC_val_int(SFH.coordinate_width(geom))), + outer, N, grid, wk) + return sums, counts +end + +""" + distributed_calculate_structure_function!(sums, counts, sf, x, fields, bins; kwargs...) + +Accumulate a multi-field sweep across worker processes. Supplied by the Distributed extension. +""" +function distributed_calculate_structure_function!(sums, counts, sf, x, f::MF.Fields, bins; + kwargs...) + throw(ArgumentError( + "the distributed multi-field sweep needs Distributed: run `using Distributed` and add " * + "workers.", + )) +end + +""" + gpu_calculate_structure_function!(backend, sums, counts, sf, x, fields, bins; kwargs...) + +Accumulate a multi-field sweep on a device. Supplied by the KernelAbstractions extension. +""" +function gpu_calculate_structure_function_fields!(backend, sums, counts, sf, x, f::MF.Fields, + bins; kwargs...) + throw(ArgumentError( + "the GPU multi-field sweep needs KernelAbstractions: run `using KernelAbstractions` and " * + "a device backend such as CUDA.", + )) +end + +# Backend selection for a multi-field, mirroring the array path's: the concrete backends dispatch, +# and `Auto` takes the threaded one when there are threads to use and the extension supplying it is +# loaded. +@inline _field_dispatch!(::CB.AbstractSerialBackend, sums, counts, sf, x, f, bins; kwargs...) = + serial_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) + +@inline _field_dispatch!(::CB.AbstractThreadedBackend, sums, counts, sf, x, f, bins; kwargs...) = + threaded_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) + +@inline function _field_dispatch!(::CB.AbstractDistributedBackend, sums, counts, sf, x, f, bins; + kwargs...) + _refuse_weights(kwargs, "the distributed multi-field sweep") + return distributed_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) +end + +@inline function _field_dispatch!(be::CB.AbstractGPUBackend, sums, counts, sf, x, f, bins; kwargs...) + _refuse_weights(kwargs, "the GPU multi-field sweep") + return gpu_calculate_structure_function_fields!(be, sums, counts, sf, x, f, bins; kwargs...) +end + +function _field_dispatch!(::CB.AbstractAutoBackend, sums, counts, sf, x, f, bins; kwargs...) + if Threads.nthreads() > 1 && _ohmythreads_loaded() + return threaded_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) + end + return serial_calculate_structure_function!(sums, counts, sf, x, f, bins; kwargs...) +end + +""" + calculate_structure_function!(sums, counts, sf, x, fields, distance_bins; backend, kwargs...) + +Accumulate a multi-field's pairs into `sums`/`counts` on `backend`. +""" +function calculate_structure_function!( + sums, counts, sf::SFT.AbstractPairwiseStructureFunctionType, x::AbstractMatrix, f::MF.Fields, + distance_bins; backend::CB.AbstractExecutionBackend = CB.SerialBackend(), kwargs..., +) + _assert_counts_representable(eltype(counts), size(MF.packed(f), 2)) + validate_fields(sf, f) + _field_dispatch!(backend, sums, counts, sf, x, f, distance_bins; kwargs...) + return nothing +end + +""" + calculate_structure_function(sf, x, fields, distance_bins[, count_eltype]; kwargs...) + +Structure function of a multi-field: several quantities sampled at the same points, swept +together in one pass, so a mixed moment reads every field at each pair. +""" +function calculate_structure_function( + sf::SFT.AbstractPairwiseStructureFunctionType, + x::AbstractMatrix, + f::MF.Fields, + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunction, + kwargs..., +) where {OT, CT} + N = size(MF.packed(f), 2) + _assert_counts_representable(CT, N) + nb = n_histogram_bins(squared_digitize_plan(distance_bins)) + validate_fields(sf, f) + sums = zeros(float(eltype(MF.packed(f))), nb) + counts = zeros(CT, nb) + _field_dispatch!(backend, sums, counts, sf, x, f, distance_bins; kwargs...) + raw = SFO.StructureFunctionSumsAndCounts(sf, distance_bins, sums, counts) + return _finalize(raw, output_type) +end diff --git a/src/Calculations/pair_schedule.jl b/src/Calculations/pair_schedule.jl index 7bcd216..6e75454 100644 --- a/src/Calculations/pair_schedule.jl +++ b/src/Calculations/pair_schedule.jl @@ -185,8 +185,8 @@ CulledBlockPairs(grid::CellGrid{D}) where {D} = CulledBlockPairs{D, typeof(grid) Base.IteratorSize(::Type{<:CulledBlockPairs}) = Base.SizeUnknown() Base.eltype(::Type{<:CulledBlockPairs}) = PairBlock -# Cells adjacent along dimension 1 are contiguous in the sorted order, so a whole stencil row is -# one run: sweeping per row rather than per cell makes the inner loop `2*span+1` cells long. +# Cells adjacent along dimension 1 are contiguous in the sorted order, so a whole stencil row is one +# run and the inner loop is `2*span+1` cells long. # The outer walk is over OCCUPIED cells, so it never scales with the cell-id space. @inline function Base.iterate( b::CulledBlockPairs{D}, st::Tuple{Int, Int} = (1, 1), diff --git a/src/Calculations/scattered_modes.jl b/src/Calculations/scattered_modes.jl new file mode 100644 index 0000000..2828f04 --- /dev/null +++ b/src/Calculations/scattered_modes.jl @@ -0,0 +1,269 @@ +# The soft-binned pair statistic of scattered points: type-1 non-uniform FFTs of the masked, weighted +# monomials onto a periodic mode grid make the transform engine's lag-space products the pair sums +# with the mode set's periodic kernel in place of a hard lag. + +""" + ScatteredModesSchedule(points, r_max, modes; taper = NoTaper()) + +Scattered points `(Dg, N)` in the box that is their extent padded by `r_max` along every direction, +so that no pair within `r_max` wraps, mapped to `[0, 2π)^Dg`, with a periodic mode grid of `modes` +per direction. + +The transform engine takes the forward transforms of the masked, weighted monomials as type-1 +non-uniform FFTs onto that grid, so every lag-space product is the pair sum +`Σ_ij w_i w_j m_i m_j μ_i ν_j K(θ_j − θ_i − 2πh/M)` with the periodic kernel +`K(φ) = Π_d (1/M_d) Σ_k b_k e^{i k φ_d}` of the mode set in place of a delta at lag `h`: a soft bin of +width about `L_d/M_d`, whose sidelobes `taper` trades for width (`NoTaper()` is the Dirichlet kernel; +`GaussianTaper(σ)`, `σ` a length, weights mode `k` by `exp(−|k|²σ²/2)`). The statistic is **not +exact**: it converges to the hard-binned pair sum as the modes grow, and no finite mode set reproduces +it. Its pair count is the kernel-weighted pair mass, a floating-point number, so results carry +[`ModeBinEdges`](@ref) and need floating-point counts. Every point's pair with itself deposits half a +unit of that mass on the smallest lags, as the harmonic route's self term does; bins that start above +the kernel's width exclude it. The accuracy of the transforms themselves is the provider's, set on its +tag: [`NonuniformFFTsSpectralBackend`](@ref) or [`FINUFFTSpectralBackend`](@ref). +""" +struct ScatteredModesSchedule{Dg, T, X <: AbstractMatrix{T}, B <: AbstractTaper} <: AbstractSeparableSchedule + points::X + origin::NTuple{Dg, T} + box::NTuple{Dg, T} + modes::NTuple{Dg, Int} + taper::B +end + +function ScatteredModesSchedule(points::AbstractMatrix{T}, r_max::Real, modes::NTuple{Dg, <:Integer}; + taper::AbstractTaper = NoTaper()) where {T, Dg} + size(points, 1) == Dg || throw(DimensionMismatch( + "points have $(size(points, 1)) coordinates, modes name $Dg directions", + )) + all(m -> m >= 2, modes) || throw(ArgumentError("every direction needs at least two modes; got $modes")) + (isfinite(r_max) && r_max > 0) || throw(ArgumentError( + "r_max must be finite and positive: the box is the points' extent padded by it", + )) + taper isa Union{NoTaper, GaussianTaper} || throw(ArgumentError( + "$(nameof(typeof(taper))) has no mode-space form; use NoTaper() or GaussianTaper(σ)", + )) + origin = ntuple(d -> T(minimum(view(points, d, :))), Val(Dg)) + box = ntuple(d -> T(maximum(view(points, d, :)) - origin[d] + r_max), Val(Dg)) + return ScatteredModesSchedule{Dg, T, typeof(points), typeof(taper)}(points, origin, box, Int.(modes), taper) +end + +@inline n_cells(s::ScatteredModesSchedule) = size(s.points, 2) +@inline grid_dimension(::ScatteredModesSchedule{Dg}) where {Dg} = Dg +@inline uniform_axes(s::ScatteredModesSchedule{Dg}) where {Dg} = + UniformLagSchedule(s.modes, ntuple(d -> s.box[d] / s.modes[d], Val(Dg)), ntuple(_ -> true, Val(Dg))) +@inline n_slabs(::ScatteredModesSchedule) = 1 +@inline enumerated_pairs(::ScatteredModesSchedule, r_max) = ((1, 1),) +@inline separable_layout(::ScatteredModesSchedule, data, valid, weights) = (data, valid, weights) +@inline lag_limits(s::ScatteredModesSchedule, r_max) = lag_limits(uniform_axes(s), r_max) +@inline lag_limits(s::ScatteredModesSchedule, I, J, r_max) = lag_limits(uniform_axes(s), r_max) +@inline lag_transport(::ScatteredModesSchedule) = IdentityTransport() +@inline lag_frame(s::ScatteredModesSchedule, I, J, h, vD::Val, vV::Val, vK::Val) = + lag_frame(uniform_axes(s), I, J, h, vD, vV, vK) + +"""Whether a schedule's pair counts are a kernel-weighted mass read from the transforms' count column.""" +@inline _soft_binned(::AbstractSeparableSchedule) = false +@inline _soft_binned(::ScatteredModesSchedule) = true + +"""Points in `[0, 2π)` along each direction, as the non-uniform FFT wants them.""" +@inline function mode_coordinates(s::ScatteredModesSchedule{Dg, T}, d::Integer) where {Dg, T} + return T(2π) .* (view(s.points, d, :) .- s.origin[d]) ./ s.box[d] +end + +"""The angular wavenumber squared of mode `m` (integers, one per direction) of the schedule's box.""" +@inline function mode_wavenumber2(s::ScatteredModesSchedule{Dg, T}, m::NTuple{Dg}) where {Dg, T} + k2 = zero(T) + for d in 1:Dg + k = T(2π) * m[d] / s.box[d] + k2 += k * k + end + return k2 +end + +""" + mode_taper_weights(schedule, FT, dims, to) -> Array or nothing + +The schedule's taper on the real-to-complex half spectrum of size `dims` — mode integers `0:M₁÷2` along +the first direction, FFT order along the rest — in the array family `to` returns; `nothing` for `NoTaper()`. +""" +function mode_taper_weights(s::ScatteredModesSchedule{Dg, T}, ::Type{FT}, dims::NTuple{Dg, Int}, to) where {Dg, T, FT} + s.taper isa NoTaper && return nothing + b = Array{FT}(undef, dims) + for I in CartesianIndices(b) + m = ntuple(d -> _mode_integer(I[d], s.modes[d], d == 1), Val(Dg)) + b[I] = FT(mode_taper(s.taper, mode_wavenumber2(s, m))) + end + return to(b) +end + +"""The signed mode integer at position `i` of a direction of `M` modes: `i − 1` on the half-spectrum direction, FFT order on a full one.""" +@inline _mode_integer(i::Int, M::Int, half::Bool) = (half || i - 1 <= (M - 1) ÷ 2) ? i - 1 : i - 1 - M + +_no_lag_sweep(::ScatteredModesSchedule) = throw(ArgumentError( + "a ScatteredModesSchedule has no lags to sweep: its pairs are summed by a non-uniform FFT. Pass " * + "NonuniformFFTsSpectralBackend() or FINUFFTSpectralBackend() with the provider and an AbstractFFTs implementation " * + "loaded, or call the point entry without a schedule for the exact pair loop.", +)) + +function gridded_lag_sweep!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::ScatteredModesSchedule, dist_be, ::Val{D}, ::Val{V}, ::Val{K}; kwargs..., +) where {OT, CT, D, V, K} + _no_lag_sweep(s) +end + +function gridded_lag_sweep!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + data::AbstractMatrix, s::ScatteredModesSchedule, dist_be, axis_be, ::Val{D}, ::Val{V}, ::Val{K}; kwargs..., +) where {OT, CT, D, V, K} + _no_lag_sweep(s) +end + +# --------------------------------------------------------------------------------------------------- +# The providers of the non-uniform FFT, as tags +# --------------------------------------------------------------------------------------------------- + +""" + NonuniformFFTsSpectralBackend(; tolerance = 1e-12) + +The non-uniform FFT tag that names NonuniformFFTs.jl as the provider, on the CPU or on the device the +points live on; `using NonuniformFFTs` supplies it. `tolerance` is the relative accuracy asked of the +transforms; the provider's kernel half-support follows from it by [`nufft_half_support`](@ref), and is +also the least number of modes a direction of the schedule may have. +""" +struct NonuniformFFTsSpectralBackend <: SB.AbstractNonUniformFastFourierTransformSpectralBackend + tolerance::Float64 +end + +NonuniformFFTsSpectralBackend(; tolerance::Real = 1e-12) = NonuniformFFTsSpectralBackend(_nufft_tolerance(tolerance)) + +""" + FINUFFTSpectralBackend(; tolerance = 1e-12) + +The non-uniform FFT tag that names FINUFFT.jl as the provider — cuFINUFFT for points on a CUDA device; +`using FINUFFT` supplies it, with `using CUDA` for the device. `tolerance` is the relative accuracy the +transforms are asked for. +""" +struct FINUFFTSpectralBackend <: SB.AbstractNonUniformFastFourierTransformSpectralBackend + tolerance::Float64 +end + +FINUFFTSpectralBackend(; tolerance::Real = 1e-12) = FINUFFTSpectralBackend(_nufft_tolerance(tolerance)) + +function _nufft_tolerance(tolerance::Real) + 0 < tolerance < 1 || throw(ArgumentError("tolerance must lie in (0, 1); got $tolerance")) + return Float64(tolerance) +end + +""" + nufft_half_support(tag::NonuniformFFTsSpectralBackend) -> Int + +The kernel half-support `M` at which NonuniformFFTs' backwards Kaiser–Bessel kernel, of shape +`β = π γ M (2 − 1/σ)` (Potts & Steidl 2003, eq. 5.12) at its oversampling `σ = 2`, reaches the tag's +tolerance: its aliasing error is `ε = exp(−π M √((2 − 1/σ)² − 1/σ²)) = exp(−2π M √(1 − 1/σ))`, so +`M = ⌈−ln ε / (2π √(1 − 1/σ))⌉`; `γ ≤ 1` makes the realised error slightly better than the estimate. +The tolerance is floored at `eps(Float64)`, below which nothing is left to resolve, and `M` at 2. +`1e-7` gives 4, `1e-12` gives 7, `1e-15` gives 8. +""" +function nufft_half_support(tag::NonuniformFFTsSpectralBackend) + ε = max(tag.tolerance, eps(Float64)) + return max(ceil(Int, -log(ε) / (2π * sqrt(1 - 1 / 2))), 2) +end + +_nufft_package(::Type{NonuniformFFTsSpectralBackend}) = "NonuniformFFTs" +_nufft_package(::Type{FINUFFTSpectralBackend}) = "FINUFFT" + +""" + nufft_monomial_transforms(tag, schedule::ScatteredModesSchedule, data, valid, weights, keys, ::Val{Pm}; to = identity) -> Vector + +Type-1 non-uniform FFTs of the masked, weighted monomials `keys` of the packed point field onto the +schedule's mode grid, one array per key in the real-to-complex half-spectrum layout +`(M₁ ÷ 2 + 1, M₂, …)`, each weighted by the schedule's taper; the arrays in the family `to` returns. +`tag` is a provider tag, [`NonuniformFFTsSpectralBackend`](@ref) or [`FINUFFTSpectralBackend`](@ref); +supplied by the provider's extension. +""" +nufft_monomial_transforms(tag::SB.AbstractNonUniformFastFourierTransformSpectralBackend, args...; kwargs...) = + throw(ArgumentError(_nufft_missing(typeof(tag)))) + +_nufft_missing(::Type{T}) where {T <: Union{NonuniformFFTsSpectralBackend, FINUFFTSpectralBackend}} = + "$(nameof(T)) needs `using $(_nufft_package(T))`." +_nufft_missing(::Type{SB.NonUniformFastFourierTransformSpectralBackend}) = + "NonUniformFastFourierTransformSpectralBackend() names no provider; pass NonuniformFFTsSpectralBackend() or " * + "FINUFFTSpectralBackend()." +_nufft_missing(::Type{T}) where {T} = "no extension computes non-uniform FFTs for $(nameof(T))." + +""" + nufft_plan(tag::NonuniformFFTsSpectralBackend, FT, modes, x) + +NonuniformFFTs' type-1 plan for `modes` in precision `FT` on the device the array `x` lives on: the host +plan from the NonuniformFFTs extension for an `Array`, a device plan from its KernelAbstractions extension. +""" +nufft_plan(tag, ::Type, modes, x) = throw(ArgumentError(_needs_device_extension(tag, x))) + +""" + nufft_type1!(tag::FINUFFTSpectralBackend, full, strengths, θ, modes) + +FINUFFT's batched type-1 transform of the complex `strengths` `(N, ntrans)` at the points `θ` onto the +full FFT-ordered mode grid `full` `(modes…, ntrans)`: the host transform from the FINUFFT extension for +`Array`s, cuFINUFFT from its KernelAbstractions extension for arrays on a CUDA device. +""" +nufft_type1!(tag, full, strengths, θ, modes) = throw(ArgumentError(_needs_device_extension(tag, full))) + +_needs_device_extension(tag, x) = + "$(nameof(typeof(tag))) on $(typeof(x)) needs `using KernelAbstractions` beside " * + "`using $(_nufft_package(typeof(tag)))`, and `using CUDA` for a CUDA device." + +# A non-uniform FFT tag with no transform loaded: the route's inverse transforms come from the AbstractFFTs extension. +_no_nufft_route() = throw(ArgumentError( + "the non-uniform FFT route needs an AbstractFFTs implementation (`using FFTW` on CPU) for the inverse " * + "transforms, and a provider: `using NonuniformFFTs` or `using FINUFFT`.", +)) + +gridded_sweep!(::AbstractVector, ::AbstractVector, sf, ::AbstractMatrix, schedule, distance_bins, ::Val{D}, ::Val{V}, + ::Val{K}, ::SB.AbstractNonUniformFastFourierTransformSpectralBackend; kwargs...) where {D, V, K} = + _no_nufft_route() + +gridded_sweep!(::AbstractMatrix, ::AbstractMatrix, sf, ::AbstractMatrix, schedule, distance_bins, axis_bins, ::Val{D}, + ::Val{V}, ::Val{K}, ::SB.AbstractNonUniformFastFourierTransformSpectralBackend; kwargs...) where {D, V, K} = + _no_nufft_route() + +""" +The monomial `w_k Π_c data[c, k]` over the cells, zero where the cell holds nothing: selected by the +mask, never multiplied by it, since an empty cell may hold NaN. The weights are finite. +""" +function _held_monomial_vector(data::AbstractMatrix, valid, weights, key::Tuple, ::Type{FT}) where {FT} + out = fill!(similar(parent(data), FT, size(data, 2)), one(FT)) + for c in key + c == 0 && continue + out .*= view(data, c, :) + end + weights isa NoWeights || (out .*= weights) + valid isa AllValid || (out .= ifelse.(valid, out, zero(FT))) + return out +end + +""" + calculate_structure_function(sf, schedule::ScatteredModesSchedule, u, distance_bins, spectral_backend; weights, backend, output_type, verbose) + +The soft-binned structure function of scattered points by non-uniform FFT. `u` is `(D, N)` over the +`N` points of `schedule`, or a multi-field over them; `spectral_backend` is a provider tag, +[`NonuniformFFTsSpectralBackend`](@ref) or [`FINUFFTSpectralBackend`](@ref). Counts are +`Float64`, the kernel-weighted pair mass, and the result's `distance` is a [`ModeBinEdges`](@ref) +carrying the schedule. See [`ScatteredModesSchedule`](@ref) for what is and is not exact. +""" +function calculate_structure_function( + sf::SFT.AbstractPairwiseStructureFunctionType, s::ScatteredModesSchedule, u::Union{AbstractArray, MF.Fields}, + distance_bins::AbstractVector, spectral_backend; + weights = nothing, backend::CB.AbstractExecutionBackend = CB.AutoBackend(), + output_type::Type{OT} = SFO.StructureFunction, verbose::Bool = true, +) where {OT} + data, vD, vV, vK = _packed(u) + N = n_cells(s) + size(data, 2) == N || throw(DimensionMismatch("u covers $(size(data, 2)) points, the schedule $N")) + valid = field_validity(data) + nb = n_histogram_bins(squared_digitize_plan(distance_bins)) + sums = zeros(float(eltype(data)), nb) + counts = zeros(Float64, nb) + verbose && @info "soft-binned structure function by non-uniform FFT: $N points onto $(s.modes) modes" + gridded_sweep!(sums, counts, sf, data, s, distance_bins, vD, vV, vK, spectral_backend; valid, weights, backend) + return _finalize(SFO.StructureFunctionSumsAndCounts(sf, ModeBinEdges(distance_bins, s), sums, counts), OT) +end diff --git a/src/Calculations/second_axis.jl b/src/Calculations/second_axis.jl index a269a71..d0c21c2 100644 --- a/src/Calculations/second_axis.jl +++ b/src/Calculations/second_axis.jl @@ -32,7 +32,9 @@ two ends flips the separation, and no structure function distinguishes the two. signed azimuth is taken modulo `π`, giving `[0, π)`; in three or more the polar angle to the axis is taken from `|cos|`, giving `[0, π/2]`. -`reference_axis` need not be normalized. +`reference_axis` need not be normalized. A pair separated along the reference axis has angle exactly +`0`, and bins are `(lo, hi]`, so bins over this axis start just below zero — [`axis_bounds`](@ref) +does — or an axis-aligned pair falls in no bin. """ struct SeparationAngleAxis{V} <: AbstractSecondAxisSource reference_axis::V @@ -91,4 +93,4 @@ axis_bounds(::InvariantValueAxis) = throw(ArgumentError( "the operator's value has no range known ahead of the calculation; supply value bins, or scan " * "the data as the auto-binning entry does", )) -axis_bounds(::SeparationAngleAxis{V}) where {V} = (0.0, Float64(π)) +axis_bounds(::SeparationAngleAxis{V}) where {V} = (prevfloat(0.0), Float64(π)) diff --git a/src/Calculations/serial.jl b/src/Calculations/serial.jl index 0758223..067a770 100644 --- a/src/Calculations/serial.jl +++ b/src/Calculations/serial.jl @@ -9,38 +9,47 @@ function serial_calculate_structure_function!( distance_bins::AbstractVector; geometry = SFH.FlatGeometry{length(u_vecs)}(), culling::CullingPolicy = AutoCulling(), + weights = nothing, verbose::Bool = true, show_progress::Bool = true, ) where {OT, CT, T1, T2} distance_bins = BinEdges(distance_bins) + w = _pair_weights(weights, length(x_vecs[1]), OT) + _check_weighted_counts(w, CT) if verbose @info("calculating structure function (serial reduction)") end + D = length(u_vecs) + # A polynomial operator on a line: sorted once, every bin is an index range (sorted_line.jl). + if _on_a_line(geometry, structure_function_type) + _cull_reject_unsupported(culling, "the sorted line route") + return sorted_line_sweep!(output, counts, structure_function_type, x_vecs[1], + reshape(collect(u_vecs[1]), 1, :), distance_bins, Val(1), Val(1), Val(0); weights = w) + end # Fast path: flat D ∈ (2,3) uses the SIMD compute/scatter-split kernel (vectorizes the per-pair # compute over j; only the histogram scatter is scalar). Curved geometries take the scalar # per-i kernel, which forms the frame through `pair_frame`. - D = length(u_vecs) if geometry isa SFH.FlatGeometry && D == 2 return _pf_simd_run!(output, counts, structure_function_type, x_vecs, u_vecs, - distance_bins, Val(2); culling = culling) + distance_bins, Val(2); culling = culling, weights = w) elseif geometry isa SFH.FlatGeometry && D == 3 return _pf_simd_run!(output, counts, structure_function_type, x_vecs, u_vecs, - distance_bins, Val(3); culling = culling) + distance_bins, Val(3); culling = culling, weights = w) end _cull_reject_unsupported(culling, "the scalar per-point kernel that this geometry uses") PM.@showprogress enabled = show_progress for i in eachindex(x_vecs[1]) calculate_structure_function_i!( - output, counts, geometry, structure_function_type, i, x_vecs, u_vecs, distance_bins, + output, counts, geometry, structure_function_type, i, x_vecs, u_vecs, distance_bins, w, ) end return nothing end """ - _pf_simd_run!(output, counts, sf, x_vecs, u_vecs, dist_be, ::Val{D}) -> mutates buffers + _pf_simd_run!(output, counts, sf, x_vecs, u_vecs, dist_be, ::Val{D}; culling, weights) -> mutates buffers Point-field 1D (Euclidean) via the SIMD compute/scatter split. Materializes contiguous per-component vectors (so consecutive `j` are unit-stride → packed loads), then for each `i`: @@ -51,12 +60,16 @@ function _pf_simd_run!( output::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, dist_be, ::Val{D}; - culling::CullingPolicy = AutoCulling(), + culling::CullingPolicy = AutoCulling(), weights = NoWeights(), ) where {OT, CT, D} N = length(x_vecs[1]) - return _pf_simd_partial!(output, counts, sf, x_vecs, u_vecs, dist_be, Val(D), 1:(N - 1), culling) + return _pf_simd_partial!(output, counts, sf, x_vecs, u_vecs, dist_be, Val(D), 1:(N - 1), culling; weights) end +"""The weight a point carries into its pairs; `true` for an unweighted sweep, which the compiler folds away.""" +@inline _point_weight(::NoWeights, i::Int) = true +@inline _point_weight(w::AbstractVector, i::Int) = @inbounds w[i] + """ Points per `j` block in the CPU pair loop. Sized so one block's coordinates, fields and the three per-`j` buffers stay resident in a core's private cache while every `i` sweeps it. @@ -64,9 +77,10 @@ per-`j` buffers stay resident in a core's private cache while every `i` sweeps i const SF_CPU_PAIR_TILE = 65536 """ - _pf_simd_pairs!(output, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, blocks) + _pf_simd_pairs!(output, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, blocks, weights) -Accumulate the pairs `(i, j>i)` covered by `blocks` into `output`/`counts`. +Accumulate the pairs `(i, j>i)` covered by `blocks` into `output`/`counts`, each pair carrying +`weights[i] * weights[j]` in both. `blocks` yields `(i-block, j-block)` index ranges (see [`block_pairs`](@ref)); each is worked to completion, so the `j` block stays cache-resident across its whole `i` sweep. Under multi-core load @@ -87,7 +101,7 @@ function _pf_simd_pairs!( sf::SFT.AbstractPairwiseStructureFunctionType, xc::NTuple{D}, uc::NTuple{D}, plan::AbstractSquaredDigitizePlan, ::Val{D}, r2buf::AbstractVector, valbuf::AbstractVector, idxbuf::AbstractVector{Int32}, - blocks, + blocks, weights, ) where {OT, CT, D} nb = n_histogram_bins(plan) FTx = eltype(xc[1]) @@ -109,11 +123,13 @@ function _pf_simd_pairs!( idxbuf[j] = squared_approx_index(plan, r2) end end + wi = _point_weight(weights, i) for j in jlo:j_last b = squared_bin(plan, r2buf[j], idxbuf[j]) if 1 <= b <= nb - output[b] += valbuf[j] - counts[b] += one(CT) + w = wi * _point_weight(weights, j) + output[b] += w * valbuf[j] + counts[b] += CT(w) end end end @@ -140,6 +156,19 @@ Every pair can land in one bin, so that product is the only safe bound. `UInt32` return nothing end +# A floating-point count (a joint histogram over angle splits pairs between bins) is exact up to +# `maxintfloat`. +@inline function _assert_counts_representable(::Type{CT}, n_points::Integer) where {CT <: AbstractFloat} + n_pairs = (Int128(n_points) * (Int128(n_points) - 1)) ÷ 2 + n_pairs <= Int128(maxintfloat(CT)) || throw( + ArgumentError( + "count_eltype=$CT counts exactly only up to $(maxintfloat(CT)), below the worst-case pair " * + "count $n_pairs for N=$n_points; pass count_eltype=Float64.", + ), + ) + return nothing +end + """ _bin_average!(out, sums, counts) _bin_average(sums, counts) @@ -164,7 +193,7 @@ end """ _tensor_bin_average(sums, counts, ::Val{P}) -Tensor analogue of [`_bin_average`](@ref): `counts` (indexed by `(bin, aux...)`) broadcasts over +Tensor analogue of `_bin_average`: `counts` (indexed by `(bin, aux...)`) broadcasts over the `P` leading component axes of `sums` (shape `(D×P..., n_bins, aux...)`). Same empty-bin guard (`count == 0 → NaN`) and `eltype` preservation. Used by `_finalize` to average a tensor result. """ @@ -188,8 +217,14 @@ function _tensor_bin_average(sums::AbstractArray, counts::AbstractArray, ::Val{P return out end -# Non-mutating backends always return the raw accumulator (`StructureFunctionSumsAndCounts`); -# the public boundary picks the representation via `_finalize(raw, output_type)`. +""" + serial_calculate_structure_function(sf, x, u, distance_bins[, value_bins][, count_eltype]; kwargs...) + +The point-list structure function on the serial CPU backend, returning the raw +[`StructureFunctionSumsAndCounts`](@ref StructureFunctions.StructureFunctionObjects.StructureFunctionSumsAndCounts) +(or the joint `StructureFunction2DSumsAndCounts` with `value_bins`). Takes the arguments of +[`calculate_structure_function`](@ref) without `backend`; the public entry picks the output type. +""" function serial_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple{T1, Vararg{T1}}, @@ -283,6 +318,7 @@ function calculate_structure_function_i!( x_vecs::Tuple{T1, Vararg{T1}}, u_vecs::Tuple{T2, Vararg{T2}}, distance_bins::AbstractVector, + weights = NoWeights(), ) where {OT, T1, T2} FT1 = eltype(T1) FT2 = eltype(T2) @@ -294,6 +330,7 @@ function calculate_structure_function_i!( F = _val_int(vF) X1 = SA.SVector{W, FT1}(ntuple(k -> @inbounds(x_vecs[k][i]), vW)) U1 = SA.SVector{F, FT2}(ntuple(k -> @inbounds(u_vecs[k][i]), vF)) + wi = _point_weight(weights, i) iter_inds = eachindex(x_vecs[1]) # @inbounds: x_vecs[k] are strided views; the bounds checks on every component access @@ -306,8 +343,9 @@ function calculate_structure_function_i!( if ok && 1 <= bin < N3 U2 = SA.SVector{F, FT2}(ntuple(k -> u_vecs[k][j], vF)) δu, rh = SFH.pair_increments(geom, frame, distance, X1, X2, U1, U2) - output[bin] += structure_function_type(δu, rh) - counts[bin] += 1 + w = wi * _point_weight(weights, j) + output[bin] += w * structure_function_type(δu, rh) + counts[bin] += w end end return nothing @@ -385,21 +423,21 @@ function _partial_sums_counts( end """ - _pf_run_blocks!(sums, counts, sf, xc, uc, plan, ::Val{D}, bufs..., ilist, N, grid) + _pf_run_blocks!(sums, counts, sf, xc, uc, plan, ::Val{D}, bufs..., ilist, N, grid, weights) Run the pair kernel with the schedule `grid` selects. Whether a grid exists is decided from the data, so it arrives here as a `Union`; dispatching on it resolves that into one concretely typed schedule per method, which is what keeps the kernel statically specialized. """ @inline _pf_run_blocks!( - sums, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, ilist, N, ::Nothing, + sums, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, ilist, N, ::Nothing, weights, ) where {D} = _pf_simd_pairs!(sums, counts, sf, xc, uc, plan, Val(D), r2buf, valbuf, idxbuf, - pair_blocks(N, ilist)) + pair_blocks(N, ilist), weights) @inline _pf_run_blocks!( - sums, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, ilist, N, grid::CellGrid, + sums, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, ilist, N, grid::CellGrid, weights, ) where {D} = _pf_simd_pairs!(sums, counts, sf, xc, uc, plan, Val(D), r2buf, valbuf, idxbuf, - pair_blocks(N, ilist; grid = grid)) + pair_blocks(N, ilist; grid = grid), weights) """ _pf_simd_partial!(sums, counts, sf, x_vecs, u_vecs, dist_be, ::Val{D}, ilist; kwargs...) @@ -409,16 +447,18 @@ component vectors and scratch buffers this worker needs. Shared by the distribut hybrid drivers, whose inputs arrive as strided views. When `culling` yields a cull grid the points are sorted into it first; `ilist` then selects -positions in the sorted order, which leaves the union over workers unchanged. +positions in the sorted order, which leaves the union over workers unchanged. `weights`, one per +point, are sorted with them. """ function _pf_simd_partial!( sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, dist_be, ::Val{D}, ilist, culling::CullingPolicy = AutoCulling(); - geometry = SFH.FlatGeometry{D}(), + geometry = SFH.FlatGeometry{D}(), weights = NoWeights(), ) where {OT, CT, D} xc = ntuple(d -> collect(x_vecs[d]), Val(D)) # contiguous component vectors uc = ntuple(d -> collect(u_vecs[d]), Val(D)) + wc = weights isa NoWeights ? weights : collect(weights) N = length(xc[1]) plan = squared_digitize_plan(dist_be) r2buf = Vector{eltype(xc[1])}(undef, N) @@ -428,9 +468,10 @@ function _pf_simd_partial!( if !isnothing(grid) xc = apply_perm(xc, grid.perm) uc = apply_perm(uc, grid.perm) + wc = wc isa NoWeights ? wc : wc[grid.perm] end _pf_run_blocks!(sums, counts, sf, xc, uc, plan, Val(D), - r2buf, valbuf, idxbuf, ilist, N, grid) + r2buf, valbuf, idxbuf, ilist, N, grid, wc) return nothing end diff --git a/src/Calculations/serial_2d.jl b/src/Calculations/serial_2d.jl index 822f5c7..28d9160 100644 --- a/src/Calculations/serial_2d.jl +++ b/src/Calculations/serial_2d.jl @@ -34,7 +34,7 @@ function serial_calculate_structure_function!( second_axis isa InvariantValueAxis || throw(ArgumentError( "$(typeof(second_axis)) is supported on the flat D ∈ {2,3} path; this call has " * "$(nameof(typeof(geometry))) with D = $D, whose separation direction lives in each pair's " * - "own frame rather than a shared one.", + "own frame, not in a shared one.", )) PM.@showprogress enabled = show_progress for i in eachindex(x_vecs[1]) calculate_structure_function_2d_i!( diff --git a/src/Calculations/serial_single_pass.jl b/src/Calculations/serial_single_pass.jl index febc250..b9e8d23 100644 --- a/src/Calculations/serial_single_pass.jl +++ b/src/Calculations/serial_single_pass.jl @@ -68,12 +68,12 @@ function helmholtz_decompose_2d( F_prev = (D_TT[k-1] - D_LL[k-1]) / bin_mids[k-1] F_curr = (D_TT[k] - D_LL[k]) / bin_mids[k] ds = bin_mids[k] - bin_mids[k-1] - I[k] = I[k-1] + 0.5f0 * (F_prev + F_curr) * ds + I[k] = I[k-1] + (F_prev + F_curr) * ds / 2 end rotational_sums = zeros(OT, n_bins) divergent_sums = zeros(OT, n_bins) - rotational_counts = copy(L2_counts) + rotational_counts = copy(T2_counts) divergent_counts = copy(L2_counts) for k in 1:n_bins @@ -205,13 +205,13 @@ Fill the two derived invariant rows and replicate the shared count of a `(SINGLE accumulator. `T2 = S2 - L2` and `L1T2 = S3 - L3` hold for every pair, and a bin is a sum, so the pair loops store -only rows 1, 2, 4, 5 — four stores per pair instead of six — and these two are differenced once per -call. The count is identical across all six rows, so it is accumulated into row 1 and broadcast here. +only rows 1, 2, 4, 5 — four stores per pair — and these two are differenced once per call. The count +is identical across all six rows, so it is accumulated into row 1 and broadcast here. Uses `=`, never `+=`, so it is **idempotent**: correct whether a kernel runs once or many times over the same buffer, and correct under threaded/partial reduction because the derivation is linear -(`Σ(S2-L2) = ΣS2 - ΣL2`). That is why it belongs at the end of each pair kernel rather than at the -callers' assembly points, of which there are more than twenty. +(`Σ(S2-L2) = ΣS2 - ΣL2`). So it runs in one place, the end of each pair kernel, where the callers' +assembly points number more than twenty. """ @inline function _sp1d_derive_rows!(sums::AbstractMatrix, counts::AbstractMatrix) @inbounds for b in axes(sums, 2) @@ -537,8 +537,8 @@ function _dispatch_single_pass( x_mat = reshape(x, size(x, 1), size(x, 2)) u_mat = reshape(u, size(u, 1), size(u, 2)) # `serial_…single_pass` fills `ts`/`tc` in place; return those concretely-typed buffers - # (Matrix{OT}/Matrix{CT}) rather than the mutating chain's abstractly-typed return value, so - # the result type is concrete (the chain infers `counts::Matrix`, losing the element type). + # (Matrix{OT}/Matrix{CT}), so the result type is concrete: the mutating chain infers + # `counts::Matrix` and loses the element type. serial_calculate_structure_functions_single_pass(x_mat, u_mat, distance_bins, ts, tc; kwargs...) # Return the raw six-row accumulator; the public wrapper builds the Helmholtz entry once # (avoids the old double-compute and the 8-row copy, and matches the batched path's shape). @@ -655,8 +655,8 @@ end """ SINGLE_PASS_OPERATORS -The six native single-pass invariants in stacked-row order, keyed by short name. Used to label -each row of the single-pass `(sums, counts)` accumulator when building the result collection. +The six native single-pass invariants in stacked-row order, keyed by short name. It labels each row +of the single-pass `(sums, counts)` accumulator when the result collection is built. """ const SINGLE_PASS_OPERATORS = ( S2 = SFT.SecondOrderStructureFunctionType(), @@ -709,7 +709,7 @@ Compute the six native invariant structure functions (S2, L2, T2, S3, L3, L1T2) pass, returned as a `NamedTuple` keyed by invariant. Each entry is a single-operator result of the requested `output_type` (default the averaged `StructureFunction`; pass `StructureFunctionSumsAndCounts` for the raw sums+counts). For point-field input a `:helmholtz` -entry (a [`HelmholtzDecomposition2D`](@ref)) is included. +entry (a [`HelmholtzDecomposition2D`](@ref StructureFunctions.StructureFunctionObjects.HelmholtzDecomposition2D)) is included. !!! note "Why only six invariants (no L2T1 / T3)" The single-pass set is the six **isotropic** invariants. The directional third-order @@ -752,6 +752,13 @@ end # --- 2D Single Pass Functions --- +""" + serial_calculate_structure_functions_single_pass_2d(x, u, distance_bins, value_bins, sums_3d, counts_3d; kwargs...) + +Zero `sums_3d` and `counts_3d`, `(6, n_bins, n_val)` each, and accumulate the six invariants' joint +distance × value histograms into them through +[`calculate_structure_functions_single_pass_2d!`](@ref). +""" function serial_calculate_structure_functions_single_pass_2d( x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, @@ -768,6 +775,14 @@ function serial_calculate_structure_functions_single_pass_2d( ) end +""" + calculate_structure_functions_single_pass_2d!(sums_3d, counts_3d, x, u, distance_bins, value_bins; backend, distance_metric, kwargs...) + +Accumulate the six invariants' joint distance × value histograms of a point list into `sums_3d` +and `counts_3d`, `(6, n_bins, n_val)` each, on `backend`; the in-place form of +[`calculate_structure_functions_single_pass_2d`](@ref). `value_bins` is one edge vector for every +invariant or a tuple of six. +""" function calculate_structure_functions_single_pass_2d!( sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, @@ -862,8 +877,8 @@ The single-pass 2D accumulator, laid out `(sum|count, invariant, value_bin, dist Each pair writes all six invariants at ONE distance bin but six different value bins, so putting the value axis inside the distance axis keeps a pair's six updates inside one distance slab, and -interleaving sum with count puts each invariant's two updates on one cache line: 6 lines touched -per pair instead of 12, and the cost stops scaling with histogram size. +interleaving sum with count puts each invariant's two updates on one cache line, so a pair touches +6 lines and the cost stops scaling with histogram size. """ @inline _sp2d_histogram(::Type{OT}, n_bins::Int, n_val::Int) where {OT} = zeros(OT, 2, SINGLE_PASS_N, n_val, n_bins) @@ -910,10 +925,7 @@ function _sp2d_pairs!( u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) du, rh = SFH.pair_increments(geom, frame, r, x_i, x_j, u_i, u_j) du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 - vals = (du_norm2, du_L2, du_T2, du_L * du_norm2, du_L * du_L2, du_L * du_T2) + vals = single_pass_invariants(du_L, LA.dot(du, du)) _sp2d_scatter!(h, bin_idx, vals, value_bins, n_val) end end @@ -1249,8 +1261,8 @@ end Wrap the stacked 2D single-pass `(sums, counts)` (shape `(6, n_dist, n_val, aux...)`) into a `NamedTuple` keyed by invariant, each value a `StructureFunction2DSumsAndCounts` view into the -stacked accumulator. Unlike 1D, the per-cell counts genuinely differ per invariant (each -invariant's value lands in a different value-bin), so counts are taken per-invariant. The 2D joint +stacked accumulator. In 2-D each invariant's value lands in a different value bin, so the per-cell +counts differ per invariant and are taken per invariant. The 2D joint histogram has no averaged representation, so `OT` must be `StructureFunction2DSumsAndCounts`. """ function _single_pass_collection_2d( @@ -1272,7 +1284,7 @@ end Compute the six invariant 2D joint structure-function histograms in one pass, returned as a `NamedTuple` keyed by invariant (`S2, L2, T2, S3, L3, L1T2`). Each entry is a -[`StructureFunction2DSumsAndCounts`](@ref) view into the stacked accumulator (the 2D joint +[`StructureFunction2DSumsAndCounts`](@ref StructureFunctions.StructureFunctionObjects.StructureFunction2DSumsAndCounts) view into the stacked accumulator (the 2D joint histogram has no averaged form, so `output_type` must be `StructureFunction2DSumsAndCounts`). """ function calculate_structure_functions_single_pass_2d( diff --git a/src/Calculations/shapes.jl b/src/Calculations/shapes.jl index b7b510c..fb08a7d 100644 --- a/src/Calculations/shapes.jl +++ b/src/Calculations/shapes.jl @@ -6,13 +6,13 @@ Which array-rank pattern a validated `(x, u)` pair forms, with `D` the number of velocity components on axis 1 of `u`. Backends dispatch on this, so `D` reaches the kernels as a static method parameter. -- [`PointField`](@ref): `u` is `(D, N)`. -- [`SharedPositionField`](@ref): `u` is `(D, N, auxiliary...)` — one set of positions, many fields. -- [`VaryingPositionField`](@ref): `x` and `u` both carry matching auxiliary axes. +- `PointField`: `u` is `(D, N)`. +- `SharedPositionField`: `u` is `(D, N, auxiliary...)` — one set of positions, many fields. +- `VaryingPositionField`: `x` and `u` both carry matching auxiliary axes. The coordinate count on axis 1 of `x` is deliberately **not** here: it is fixed by the metric's geometry (see `HelperFunctions.coordinate_width`), so it is read off that geometry once `D` is -static rather than being restated as a shape parameter. +static. """ abstract type AbstractFieldShape{D} end struct PointField{D} <: AbstractFieldShape{D} end diff --git a/src/Calculations/sorted_line.jl b/src/Calculations/sorted_line.jl new file mode 100644 index 0000000..1f35fa3 --- /dev/null +++ b/src/Calculations/sorted_line.jl @@ -0,0 +1,197 @@ +# Exact pair statistics of polynomial operators on points along a line: sorted once, every bin of every +# point is one index range, and the moments over a range are prefix-sum differences of the monomials. + +""" + sorted_line_sweep!(sums, counts, sf, x, data, distance_bins, ::Val{D}, ::Val{V}, ::Val{K}; weights, backend) + +Accumulate `Σ w_i w_j sf(δu, r̂)` and `Σ w_i w_j` over the pairs of a one-dimensional point list into +the distance histogram `sums`/`counts`, exactly, in `O(N log N + N n_bins)`. + +`x` holds the coordinate of each point, `data` the packed fields `(V·D + K, N)` — `D = 1` for a +vector field — and `sf` a polynomial operator ([`SFT.is_polynomial_operator`](@ref)). Sorted by +coordinate, the partners of a point in one bin form an index range, found by pointers that advance +with the point and bin pairs with the `digitize` call and the `x_j − x_i` the pair loop uses, so the +counts equal the pair loop's exactly. The increment moments over a range are prefix-sum differences +of the weighted monomials, contracted by `moment_contract` with the pair read from the lower to the +upper coordinate, which is the canonical reading of an odd scalar increment. Threaded backends split +the points into consecutive blocks with private histograms. +""" +function sorted_line_sweep!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, + x::AbstractVector, data::AbstractMatrix, distance_bins, ::Val{D}, ::Val{V}, ::Val{K}; + weights = NoWeights(), backend::CB.AbstractExecutionBackend = CB.SerialBackend(), +) where {OT, CT, D, V, K} + SFT.is_polynomial_operator(sf) || throw(ArgumentError( + "$(typeof(sf)) is not a polynomial in the increment; the sorted line route sums increment moments " * + "and the pair loop evaluates any operator", + )) + validate_fields(sf, Val(V), Val(K)) + N = length(x) + size(data, 2) == N || throw(DimensionMismatch("x holds $N points and the field $(size(data, 2))")) + W = V * D + K + size(data, 1) == W || throw(DimensionMismatch( + "field has $(size(data, 1)) components, declared $V vector field(s) of width $D and $K scalar " * + "field(s), $W components", + )) + w = _pair_weights(weights, N, OT) + _check_weighted_counts(w, CT) + be = BinEdges(distance_bins) + nb = n_histogram_bins(be) + length(sums) == nb == length(counts) || throw(DimensionMismatch( + "$nb bins, but sums has $(length(sums)) entries and counts $(length(counts))", + )) + N < 2 && return nothing + xs, ds, ws = _sorted_line_inputs(x, data, w, OT) + P = SFT.order(sf) + return _sorted_line_run!(sums, counts, sf, xs, ds, ws, be, nb, Val(W), Val(P), Val(D), Val(V), Val(K), backend) +end + +"""The points in coordinate order, the field's columns and the weights permuted with them.""" +function _sorted_line_inputs(x::AbstractVector, data::AbstractMatrix, w, ::Type{OT}) where {OT} + xs = collect(float(eltype(x)), x) + ds = Matrix{OT}(data) + issorted(xs) && return xs, ds, (w isa NoWeights ? w : collect(w)) + perm = sortperm(xs) + return xs[perm], ds[:, perm], (w isa NoWeights ? w : w[perm]) +end + +function _sorted_line_run!( + sums::AbstractVector{OT}, counts, sf, xs::AbstractVector, ds::AbstractMatrix{OT}, w, be, nb::Int, + ::Val{W}, ::Val{P}, ::Val{D}, ::Val{V}, ::Val{K}, backend, +) where {OT, W, P, D, V, K} + N = length(xs) + S = _monomial_prefix_sums(ds, w, Val(W), Val(P)) + r̂ = _unit_line(_direction_width(Val(D), Val(V), Val(1)), OT) + n_tasks = max(1, sweep_tasks(backend)) + items = _consecutive_chunks(N - 1, n_tasks) + make_scratch = () -> Vector{Int}(undef, nb + 1) + vNK = _monomial_count(Val(W), Val(P)) + body! = (ls, lc, chunk, q) -> _sorted_line_chunk!(ls, lc, sf, xs, ds, w, S, be, nb, q, chunk, r̂, + Val(W), Val(P), Val(V), Val(K), vNK) + sweep_reduce!(sums, counts, backend, items, make_scratch, body!) + return nothing +end + +"""The number of monomial keys of degree `≤ P` over `W` components, as a `Val`.""" +@generated _monomial_count(::Val{W}, ::Val{P}) where {W, P} = :(Val($(length(_monomial_keys(Val(W), Val(P)))))) + +"""`1:n` cut into at most `k` consecutive ranges of near-equal length.""" +function _consecutive_chunks(n::Int, k::Int) + n < 1 && return UnitRange{Int}[] + k = clamp(k, 1, n) + return [((t - 1) * n ÷ k + 1):(t * n ÷ k) for t in 1:k] +end + +@inline _unit_line(::Val{Dr}, ::Type{T}) where {Dr, T} = + SA.SVector{Dr, T}(ntuple(d -> d == 1 ? one(T) : zero(T), Val(Dr))) + +""" +Every monomial of degree `≤ P` of one point's fields, in the order of `_monomial_keys`; the first +entry is the degree-zero monomial `1`. +""" +@generated function _line_monomials(u::SA.SVector{W, T}, ::Val{W}, ::Val{P}) where {W, T, P} + keys = _monomial_keys(Val(W), Val(P)) + terms = map(keys) do key + factors = [:(u[$c]) for c in key if c != 0] + isempty(factors) ? :(one($T)) : Expr(:call, :*, factors...) + end + return :(SA.SVector{$(length(keys)), $T}($(terms...))) +end + +""" + _monomial_prefix_sums(data, weights, Val(W), Val(P)) -> Matrix (n_keys, N + 1) + +`S[k, n + 1] = Σ_{j ≤ n} w_j μ_k(j)` for every monomial key `k` of degree `≤ P`, `S[:, 1] = 0`. +""" +_monomial_prefix_sums(ds::AbstractMatrix, w, ::Val{W}, ::Val{P}) where {W, P} = + _monomial_prefix_sums(ds, w, Val(W), Val(P), _monomial_count(Val(W), Val(P))) + +function _monomial_prefix_sums(ds::AbstractMatrix{OT}, w, ::Val{W}, ::Val{P}, ::Val{NK}) where {OT, W, P, NK} + N = size(ds, 2) + S = Matrix{OT}(undef, NK, N + 1) + acc = zero(SA.SVector{NK, OT}) + @inbounds S[:, 1] .= zero(OT) + @inbounds for j in 1:N + u = SA.SVector{W, OT}(ntuple(c -> ds[c, j], Val(W))) + acc += _line_monomials(u, Val(W), Val(P)) * OT(_point_weight(w, j)) + for k in 1:NK + S[k, j + 1] = acc[k] + end + end + return S +end + +""" + _line_moments(μi, Δ, Val(W), Val(P)) -> SymmetricMoments{W, P} + +The symmetric increment moment tensor of one point against a range of partners: `μi` the point's +monomials, `Δ` the range's summed monomials, combined as `Σ_S (−1)^{P−|S|} μ_{c_{Sᶜ}}(i) Δ[c_S]`. +""" +@generated function _line_moments(μi::SA.SVector{NK, T}, Δ::SA.SVector{NK, T}, ::Val{W}, ::Val{P}) where {NK, T, W, P} + keys = _monomial_keys(Val(W), Val(P)) + key_index = Dict(k => n for (n, k) in enumerate(keys)) + cols = _columns(IdentityTransport(), Val(W), Val(P), key_index) + entries = map(cols) do terms + Expr(:call, :+, [:($sign * μi[$a] * Δ[$b]) for (sign, a, b) in terms]...) + end + return :(SFT.SymmetricMoments{$W, $P}(SA.SVector{$(length(entries)), $T}($(entries...)))) +end + +"""The pair mass of a partner range: its length, or its summed weights.""" +@inline _range_mass(::NoWeights, S, lo::Int, hi::Int) = hi - lo +@inline _range_mass(::AbstractVector, S, lo::Int, hi::Int) = @inbounds S[1, hi + 1] - S[1, lo + 1] + +# The pairs whose lower coordinate lies in `chunk`. `q[b + 1]` is the last index `j ≥ i − 1` whose +# separation from `i` digitizes to a bin `≤ b`; the predicate is monotone in `j` and in `i`, so the +# pointers only advance. Bin `b` of point `i` is the range `(max(q[b], i), q[b + 1]]`. +function _sorted_line_chunk!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, sf, xs::AbstractVector, ds::AbstractMatrix{OT}, + w, S::AbstractMatrix{OT}, be, nb::Int, q::Vector{Int}, chunk::UnitRange{Int}, r̂, + ::Val{W}, ::Val{P}, ::Val{V}, ::Val{K}, ::Val{NK}, +) where {OT, CT, W, P, V, K, NK} + N = length(xs) + i0 = first(chunk) + @inbounds for b in 0:nb + q[b + 1] = _line_partner_bound(xs, be, i0, b, N) + end + @inbounds for i in chunk + xi = xs[i] + prev = i - 1 + for b in 0:nb + p = max(q[b + 1], prev) + while p < N && SFH.digitize(xs[p + 1] - xi, be) <= b + p += 1 + end + q[b + 1] = p + prev = p + end + ui = SA.SVector{W, OT}(ntuple(c -> ds[c, i], Val(W))) + μi = _line_monomials(ui, Val(W), Val(P)) + wi = OT(_point_weight(w, i)) + for b in 1:nb + lo = max(q[b], i) + hi = q[b + 1] + hi > lo || continue + Δ = SA.SVector{NK, OT}(ntuple(k -> S[k, hi + 1] - S[k, lo + 1], Val(NK))) + M = _line_moments(μi, Δ, Val(W), Val(P)) + sums[b] += wi * SFT.moment_contract(sf, M, r̂, Val(V), Val(K)) + counts[b] += CT(wi * _range_mass(w, S, lo, hi)) + end + end + return nothing +end + +"""The last index `j ∈ [i − 1, N]` whose separation from point `i` digitizes to a bin `≤ b`, by bisection.""" +function _line_partner_bound(xs::AbstractVector, be, i::Int, b::Int, N::Int) + lo, hi = i - 1, N + xi = @inbounds xs[i] + while lo < hi + mid = (lo + hi + 1) >> 1 + if SFH.digitize(@inbounds(xs[mid]) - xi, be) <= b + lo = mid + else + hi = mid - 1 + end + end + return lo +end diff --git a/src/Calculations/tensor.jl b/src/Calculations/tensor.jl index a335610..0b1545c 100644 --- a/src/Calculations/tensor.jl +++ b/src/Calculations/tensor.jl @@ -29,6 +29,46 @@ function calculate_structure_function_tensor( return _finalize(raw, output_type) end +""" + calculate_structure_function_tensor(order, x, u, distance_bins, axis_bins; second_axis, backend, output_type, count_eltype, distance_metric) + +The increment moment tensor joint in separation and the angle `second_axis` reads from each pair's +direction, `sums` of shape `(D, …, D, n_bins, n_axis)`: the tensor resolved by direction. One field +(no auxiliary axes), a flat metric, the CPU backends. +""" +function calculate_structure_function_tensor( + order::Val{P}, + x::AbstractArray{FT1}, + u::AbstractArray{FT2}, + distance_bins::AbstractVector, + axis_bins::AbstractVector; + second_axis::SeparationAngleAxis, + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + output_type::Type{OTT} = SFO.StructureFunctionTensor2DSumsAndCounts, + count_eltype::Type{CT} = UInt32, + distance_metric::DI.PreMetric = DI.Euclidean(), +) where {P, FT1, FT2, OTT, CT} + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) + D = spatial_dimension(shape) + OT = promote_type(float(FT1), float(FT2)) + sums = zeros(OT, ntuple(_ -> D, P)..., n_histogram_bins(distance_bins), n_histogram_bins(axis_bins)) + counts = zeros(CT, n_histogram_bins(distance_bins), n_histogram_bins(axis_bins)) + calculate_structure_function_tensor!( + sums, counts, order, x, u, distance_bins, axis_bins; second_axis, backend, distance_metric, + ) + raw = SFO.StructureFunctionTensor2DSumsAndCounts(order, distance_bins, axis_bins, sums, counts) + return _finalize(raw, output_type) +end + +""" + calculate_structure_function_tensor!(sums, counts, order, x, u, distance_bins[, axis_bins]; second_axis, backend, distance_metric) + +Accumulate the rank-`order` increment moment tensor of a point list into `sums` +`(D, …, D, n_bins[, n_axis], auxiliary...)` and `counts` `(n_bins[, n_axis], auxiliary...)` on +`backend`, the in-place form of [`calculate_structure_function_tensor`](@ref). With `axis_bins` the +tensor is binned jointly in separation and in the angle `second_axis` reads from each pair. +""" function calculate_structure_function_tensor!( sums::AbstractArray, counts::AbstractArray, @@ -48,6 +88,26 @@ function calculate_structure_function_tensor!( ) end +function calculate_structure_function_tensor!( + sums::AbstractArray, + counts::AbstractArray, + order::Val{P}, + x::AbstractArray, + u::AbstractArray, + distance_bins::AbstractVector, + axis_bins::AbstractVector; + second_axis::SeparationAngleAxis, + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + distance_metric::DI.PreMetric = DI.Euclidean(), +) where {P} + shape = _validate_array_shape(x, u, distance_metric) + axis_edges = BinEdges(axis_bins) + return _dispatch_tensor!( + backend, shape, sums, counts, order, x, u, distance_bins; + distance_metric = distance_metric, axis = (axis_edges, n_histogram_bins(axis_edges), second_axis), + ) +end + function _dispatch_tensor!( ::CB.AbstractSerialBackend, shape::AbstractFieldShape, @@ -167,24 +227,31 @@ function gpu_calculate_structure_function_tensor!(backend, sums, counts, order, end """ - _tensor_setup(order, shape, x, u, distance_bins, distance_metric) -> NamedTuple + _tensor_setup(order, shape, x, u, distance_bins, distance_metric[, axis]) -> NamedTuple Everything a tensor sweep needs before its first pair: the geometry, the widened coordinates and -field, the bin edges, and the flattened accumulator shapes. +field, the bin edges, and the flattened accumulator shapes. With `axis = (axis_edges, n_axis, +second_axis)` the sweep is joint in separation and angle, over one field on a flat metric. Shared by every backend so the preparation happens **once**, above any task or worker loop, and so there is one place where the shapes are validated. """ function _tensor_setup( order::Val{P}, shape::AbstractFieldShape{D}, sums, counts, x, u, distance_bins, distance_metric, + axis = nothing, ) where {P, D} - P == 2 || P == 3 || - throw(ArgumentError("tensor order $P is not implemented yet; supported orders are 2 and 3")) - n_bins = n_histogram_bins(distance_bins) auxiliary_dims = has_auxiliary_axes(shape) ? size(u)[3:end] : () - expected_sums = (ntuple(_ -> D, P)..., n_bins, auxiliary_dims...) - expected_counts = (n_bins, auxiliary_dims...) + if axis === nothing + expected_sums = (ntuple(_ -> D, P)..., n_bins, auxiliary_dims...) + expected_counts = (n_bins, auxiliary_dims...) + else + isempty(auxiliary_dims) || throw(ArgumentError( + "the joint tensor over the separation angle takes one field; sweep the auxiliary slices one by one", + )) + expected_sums = (ntuple(_ -> D, P)..., n_bins, axis[2]) + expected_counts = (n_bins, axis[2]) + end size(sums) == expected_sums || throw(DimensionMismatch("sums must have shape $expected_sums; got $(size(sums))")) size(counts) == expected_counts || @@ -196,6 +263,7 @@ function _tensor_setup( fixed_x = ndims(x) == 2 geom = SFH.pair_geometry_for(distance_metric, Val(D)) + axis === nothing || geom isa SFH.FlatGeometry || _require_directional(FrameTransport()) xk, uk = SFH.prepare_pair_inputs(geom, x, u) vW = SFH.coordinate_width(geom) vF = SFH.field_width(geom) @@ -203,15 +271,21 @@ function _tensor_setup( F = _val_int(vF) return (; n_bins, auxiliary_dims, dist_be, N, B, fixed_x, geom, xk, uk, vW, vF, W, F, - D = D, P = P) + D = D, P = P, axis) end -"""Flattened views of the accumulators, so the kernel indexes one auxiliary axis rather than many.""" -@inline _tensor_flat(sums, counts, s) = ( - reshape(sums, ntuple(_ -> s.D, s.P)..., s.n_bins, s.B), - reshape(counts, s.n_bins, s.B), -) +"""Flattened views of the accumulators, so the kernel indexes one auxiliary axis.""" +@inline _tensor_flat(sums, counts, s) = s.axis === nothing ? + (reshape(sums, ntuple(_ -> s.D, s.P)..., s.n_bins, s.B), reshape(counts, s.n_bins, s.B)) : + (sums, counts) + +""" + serial_calculate_structure_function_tensor!(sums, counts, order, shape, x, u, distance_bins; distance_metric, axis) +The serial pair loop behind [`calculate_structure_function_tensor!`](@ref): every pair's increment +in its pair frame, its `order`-fold outer product added to the bin of the pair's separation (and of +its angle when `axis` names one). +""" function serial_calculate_structure_function_tensor!( sums::AbstractArray, counts::AbstractArray, @@ -221,8 +295,9 @@ function serial_calculate_structure_function_tensor!( u::AbstractArray, distance_bins::AbstractVector; distance_metric::DI.PreMetric = DI.Euclidean(), + axis = nothing, ) where {P, D} - s = _tensor_setup(order, shape, sums, counts, x, u, distance_bins, distance_metric) + s = _tensor_setup(order, shape, sums, counts, x, u, distance_bins, distance_metric, axis) sums_flat, counts_flat = _tensor_flat(sums, counts, s) _tensor_pairs!(sums_flat, counts_flat, order, s, 1:s.N) return sums, counts @@ -235,9 +310,10 @@ Accumulate every pair `(i, j > i)` for `i` in `outer`. The outer list is a parameter so that one kernel serves every backend: serial passes the whole range, threaded and distributed pass a chunk of it, and the partial results add because a histogram -is order-independent. +is order-independent. With a second axis in `s` the pair's angle picks the second bin. """ function _tensor_pairs!(sums_flat, counts_flat, order::Val{P}, s, outer) where {P} + s.axis === nothing || return _tensor_pairs_joint!(sums_flat, counts_flat, order, s, outer) vW, vF, W, F = s.vW, s.vF, s.W, s.F geom, dist_be, n_bins, N, B = s.geom, s.dist_be, s.n_bins, s.N, s.B x_fixed = s.fixed_x ? reshape(s.xk, W, N) : nothing @@ -246,7 +322,8 @@ function _tensor_pairs!(sums_flat, counts_flat, order::Val{P}, s, outer) where { XT, UT = eltype(s.xk), eltype(s.uk) # The increment comes from `pair_delta`, so on a curved manifold the tensor components are in - # the pair's own transported frame rather than raw coordinate differences. + # the pair's own transported frame. An odd rank takes the canonical pair reading, as an odd + # scalar increment does. @inbounds for i in outer for j in (i + 1):N if s.fixed_x @@ -255,10 +332,11 @@ function _tensor_pairs!(sums_flat, counts_flat, order::Val{P}, s, outer) where { ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = SFH.digitize(dist, dist_be) if ok && 1 <= bin <= n_bins + sgn = _tensor_reading(order, geom, frame) for b in 1:B U1 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, i, b], vF)) U2 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, j, b], vF)) - du = SFH.pair_delta(geom, frame, X1, X2, U1, U2) + du = sgn * SFH.pair_delta(geom, frame, X1, X2, U1, U2) _accumulate_tensor_pair!(sums_flat, counts_flat, du, bin, b, order) end end @@ -271,7 +349,7 @@ function _tensor_pairs!(sums_flat, counts_flat, order::Val{P}, s, outer) where { if ok && 1 <= bin <= n_bins U1 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, i, b], vF)) U2 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, j, b], vF)) - du = SFH.pair_delta(geom, frame, X1, X2, U1, U2) + du = _tensor_reading(order, geom, frame) * SFH.pair_delta(geom, frame, X1, X2, U1, U2) _accumulate_tensor_pair!(sums_flat, counts_flat, du, bin, b, order) end end @@ -282,7 +360,49 @@ function _tensor_pairs!(sums_flat, counts_flat, order::Val{P}, s, outer) where { end """ - tensor_partial(order, shape, x, u, distance_bins, outer; distance_metric) -> (sums, counts) +The sign a pair's increment carries into an odd-rank tensor. In a fixed Cartesian frame the increment +flips when the pair is read from its other end, so an odd rank takes the canonical reading; in a +pair's own geodesic frame the axes flip with it and the components are read the same from either +end, so no sign is taken. An even rank takes none. +""" +@inline _tensor_reading(::Val{P}, geom::SFH.FlatGeometry, frame) where {P} = + isodd(P) ? SFH.pair_orientation(geom, frame) : 1 +@inline _tensor_reading(::Val{P}, ::SFH.SphericalGeometry, frame) where {P} = 1 + +"""The same rule for a lag: the lag's reading factor under identity transport, none under frame transport.""" +@inline _tensor_factor(::IdentityTransport, factor) = factor +@inline _tensor_factor(::FrameTransport, factor) = one(factor) + +# One field on a flat metric: the pair's displacement gives its angle to the reference axis, which +# picks the second bin in place of the auxiliary slot. +function _tensor_pairs_joint!(sums, counts, order::Val{P}, s, outer) where {P} + vW, vF, W, F = s.vW, s.vF, s.W, s.F + geom, dist_be, n_bins, N = s.geom, s.dist_be, s.n_bins, s.N + axis_edges, na, second_axis = s.axis + x_fixed = reshape(s.xk, W, N) + u_flat = reshape(s.uk, F, N) + XT, UT = eltype(s.xk), eltype(s.uk) + @inbounds for i in outer + X1 = SA.SVector{W, XT}(ntuple(d -> x_fixed[d, i], vW)) + U1 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, i], vF)) + for j in (i + 1):N + X2 = SA.SVector{W, XT}(ntuple(d -> x_fixed[d, j], vW)) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = SFH.digitize(dist, dist_be) + (ok && 1 <= bin <= n_bins) || continue + dx = X2 - X1 + bθ = SFH.digitize(axis_quantity(second_axis, dx, dist * dist), axis_edges) + 1 <= bθ <= na || continue + U2 = SA.SVector{F, UT}(ntuple(d -> u_flat[d, j], vF)) + du = _tensor_reading(order, geom, frame) * SFH.pair_delta(geom, frame, X1, X2, U1, U2) + _accumulate_tensor_pair!(sums, counts, du, bin, bθ, order) + end + end + return sums, counts +end + +""" + tensor_partial(order, shape, x, u, distance_bins, outer; distance_metric, count_eltype, axis) -> (sums, counts) A worker's share of a tensor sweep: the pairs whose lower index is in `outer`, in freshly allocated accumulators. @@ -291,42 +411,90 @@ The outer lists partition `1:N`, so the partials add to the whole sweep exactly. """ function tensor_partial( order::Val{P}, shape::AbstractFieldShape{D}, x, u, distance_bins, outer; - distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, + distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, axis = nothing, ) where {P, D, CT} n_bins = n_histogram_bins(distance_bins) - auxiliary_dims = has_auxiliary_axes(shape) ? size(u)[3:end] : () OT = promote_type(float(eltype(x)), float(eltype(u))) - sums = zeros(OT, ntuple(_ -> D, P)..., n_bins, auxiliary_dims...) - counts = zeros(CT, n_bins, auxiliary_dims...) - s = _tensor_setup(order, shape, sums, counts, x, u, distance_bins, distance_metric) + if axis === nothing + auxiliary_dims = has_auxiliary_axes(shape) ? size(u)[3:end] : () + sums = zeros(OT, ntuple(_ -> D, P)..., n_bins, auxiliary_dims...) + counts = zeros(CT, n_bins, auxiliary_dims...) + else + sums = zeros(OT, ntuple(_ -> D, P)..., n_bins, axis[2]) + counts = zeros(CT, n_bins, axis[2]) + end + s = _tensor_setup(order, shape, sums, counts, x, u, distance_bins, distance_metric, axis) sf, cf = _tensor_flat(sums, counts, s) _tensor_pairs!(sf, cf, order, s, outer) return sums, counts end -@inline function _accumulate_tensor_pair!(sums, counts, du, bin::Int, b::Int, ::Val{2}) - D = length(du) - @inbounds for a in 1:D - dua = du[a] - for c in 1:D - sums[a, c, bin, b] += dua * du[c] - end +# One pair's `δu^{⊗P}` added at `[…, bin, b]`, the loops over the P component indices unrolled to +# the order at compile time. +@generated function _accumulate_tensor_pair!(sums, counts, du, bin::Int, b::Int, ::Val{P}) where {P} + idx = [Symbol(:i, k) for k in 1:P] + prod_ex = Expr(:call, :*, [:(du[$(idx[k])]) for k in 1:P]...) + body = :(sums[$(idx...), bin, b] += $prod_ex) + for k in P:-1:1 + body = :(for $(idx[k]) in 1:D + $body + end) + end + return quote + D = length(du) + @inbounds $body + @inbounds counts[bin, b] += one(eltype(counts)) + return nothing end - @inbounds counts[bin, b] += one(eltype(counts)) - return nothing end -@inline function _accumulate_tensor_pair!(sums, counts, du, bin::Int, b::Int, ::Val{3}) - D = length(du) - @inbounds for a in 1:D - dua = du[a] - for c in 1:D - duac = dua * du[c] - for e in 1:D - sums[a, c, e, bin, b] += duac * du[e] - end - end +# --------------------------------------------------------------------------------------------------- +# Tensors on grids: the transform engine's per-lag symmetric moment store, binned without contraction. +# --------------------------------------------------------------------------------------------------- + +""" + gridded_tensor_sweep!(sums, counts, order, data, schedule, distance_bins[, axis_bins], ::Val{D}, spectral_backend; valid, weights, backend[, second_axis]) + +Accumulate the rank-`P` increment moment tensor of a field's vector field over every lag +`schedule` names, by the transform `spectral_backend` names, into `sums` `(D, …, D, n_bins[, n_axis])` +and `counts` `(n_bins[, n_axis])`. Supplied by the AbstractFFTs extension for every separable +schedule, the non-uniform FFT provider included. +""" +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule::AbstractSeparableSchedule, + distance_bins, ::Val{D}, ::SB.AbstractDirectSumSpectralBackend; kwargs...) where {D} = + _no_tensor_sum() + +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule::AbstractSeparableSchedule, + distance_bins, axis_bins, ::Val{D}, ::SB.AbstractDirectSumSpectralBackend; + kwargs...) where {D} = _no_tensor_sum() + +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule::AbstractSeparableSchedule, + distance_bins, ::Val{D}, tag::SB.AbstractSpectralBackend; kwargs...) where {D} = + _no_transform_loaded(tag, schedule) + +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule::AbstractSeparableSchedule, + distance_bins, axis_bins, ::Val{D}, tag::SB.AbstractSpectralBackend; kwargs...) where {D} = + _no_transform_loaded(tag, schedule) + +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule, distance_bins, ::Val{D}, + spectral_backend; kwargs...) where {D} = _not_a_spectral_tag(spectral_backend) + +gridded_tensor_sweep!(sums, counts, order::Val, data::AbstractMatrix, schedule, distance_bins, axis_bins, ::Val{D}, + spectral_backend; kwargs...) where {D} = _not_a_spectral_tag(spectral_backend) + +# A gridded tensor has one algorithm, the transform; the pair loop over the grid's points is the point entry. +_no_tensor_sum() = throw(ArgumentError( + "a gridded tensor structure function is computed by transform: pass FastFourierTransformSpectralBackend() or " * + "AutoSpectralBackend() on a grid, or a non-uniform FFT tag on a ScatteredModesSchedule. The pair loop is the " * + "point entry over the grid's points.", +)) + +"""Add the symmetric store `sym` `(n_entries, bins…)` into the dense tensor `dense` `(D, …, D, bins…)`.""" +function _expand_symmetric!(dense::AbstractArray, sym::AbstractArray, ::Val{D}, ::Val{P}) where {D, P} + comps = CartesianIndices(ntuple(_ -> D, Val(P))) + rest = CartesianIndices(size(sym)[2:end]) + @inbounds for r in rest, I in comps + dense[I, r] += sym[SFT.symmetric_rank(Val(D), Val(P), Tuple(I)), r] end - @inbounds counts[bin, b] += one(eltype(counts)) - return nothing + return dense end diff --git a/src/Calculations/transforms.jl b/src/Calculations/transforms.jl index 46193be..c7a70f8 100644 --- a/src/Calculations/transforms.jl +++ b/src/Calculations/transforms.jl @@ -96,7 +96,7 @@ Covariance matrix over `points`, evaluating the covariance function `(separation distance by linear interpolation and holding it constant outside the sampled range. A covariance matrix must be positive semi-definite, and one built this way need not be, so it is -checked rather than assumed. Two different things trip the check and the message distinguishes them: +checked. Two different things trip the check and the message distinguishes them: a covariance function that is not a valid kernel at all, and one that is valid but sampled too coarsely — interpolating a kernel does not preserve positive-definiteness, and the error falls as the square of the separation spacing. `check_posdef = false` returns the matrix regardless. @@ -167,6 +167,87 @@ function helmholtz_spectra( return (rotational = rot, divergent = div) end +""" + helmholtz_spectra(L2, T2, wavenumbers; asymptote) + +Rotational and divergent spectral densities of a two-dimensional field from its longitudinal and +transverse second-order structure functions, binned on the same edges. + +The sum and the difference of the two projections transform separately, + +```math +P_E + P_B = -\\frac{1}{4π} ∫_0^∞ (D_{LL} + D_{TT} - a)\\, J_0(kr)\\, r\\, dr, \\qquad +P_E - P_B = \\frac{1}{4π} ∫_0^∞ (D_{LL} - D_{TT})\\, J_2(kr)\\, r\\, dr, +``` + +with `E` the divergent (gradient) part and `B` the rotational (curl) part, on the convention that a +density integrates over `d²k` to the variance. The first line is [`isotropic_spectrum`](@ref) of the +trace and needs the trace's large-separation limit `a`, which defaults to its largest value; the +second needs none, since `D_LL − D_TT` decays on its own. Both kernels need `Bessels`. + +Its error is the truncation of the Hankel integrals at the last separation, which is a different +error from the one the real-space route through [`helmholtz_decompose_2d`](@ref) carries. +""" +function helmholtz_spectra( + L2::SFO.AbstractStructureFunction, T2::SFO.AbstractStructureFunction, wavenumbers::AbstractVector; + asymptote = nothing, +) + _assert_projection(L2.operator, 2, 0, "longitudinal") + _assert_projection(T2.operator, 0, 2, "transverse") + r, dll, dtt = _paired_bins(L2, T2) + asym = asymptote === nothing ? maximum(dll .+ dtt) : asymptote + total = isotropic_spectrum(SFT.S2SFType(), r, dll .+ dtt, wavenumbers, Val(2); asymptote = asym) + diff = _hankel(Val(2), r, dll .- dtt, wavenumbers) ./ (4π) + return (rotational = (total .- diff) ./ 2, divergent = (total .+ diff) ./ 2) +end + +function _assert_projection(op, NL::Int, NT::Int, name::String) + op isa SFT.ProjectedStructureFunctionType{NL, NT} && return nothing + throw(ArgumentError( + "the $name argument must be the second-order $name projection, " * + "ProjectedStructureFunctionType{$NL, $NT}; got $(nameof(typeof(op))).", + )) +end + +"""Abscissa and values of a result, restricted to bins that hold a value.""" +function _binned(sf::SFO.StructureFunction) + keep = findall(isfinite, sf.values) + return collect(midpoints(sf.distance)), collect(sf.values), keep +end + +function _binned(sf::SFO.StructureFunctionSumsAndCounts) + keep = findall(>(0), sf.counts) + vals = [c > 0 ? s / c : oftype(float(s), NaN) for (s, c) in zip(sf.sums, sf.counts)] + return collect(midpoints(sf.distance)), vals, keep +end + +# Two results on one set of edges, reduced to the bins both hold. +function _paired_bins(a::SFO.AbstractStructureFunction, b::SFO.AbstractStructureFunction) + a.distance == b.distance || throw(ArgumentError( + "the two structure functions must share their distance bins", + )) + r, va, ka = _binned(a) + _, vb, kb = _binned(b) + keep = intersect(ka, kb) + isempty(keep) && throw(ArgumentError("no bin holds a value in both structure functions")) + return r[keep], va[keep], vb[keep] +end + +"""`∫₀^∞ f(r) J_N(kr) r dr` at each wavenumber, by the same quadrature as [`isotropic_spectrum`](@ref).""" +function _hankel(::Val{N}, separations::AbstractVector, values::AbstractVector, wavenumbers::AbstractVector) where {N} + FT = float(promote_type(eltype(separations), eltype(values), eltype(wavenumbers))) + out = Vector{FT}(undef, length(wavenumbers)) + @inbounds for (j, k) in pairs(wavenumbers) + acc = zero(FT) + for i in eachindex(separations) + r = FT(separations[i]) + acc += FT(values[i]) * bessel_kernel(Val(N), k * r) * r * _quad_width(separations, i) + end + out[j] = acc + end + return out +end + function _component_spectrum(op, r, sums, counts, wavenumbers, asymptote) keep = findall(>(0), counts) isempty(keep) && throw(ArgumentError("every bin of the $(nameof(typeof(op))) component is empty")) @@ -210,6 +291,7 @@ spectrum; converting from them needs the isotropy relation between longitudinal components, which this transform does not apply. Orders other than two are fluxes, not spectra. """ assert_invertible(::SFT.SecondOrderStructureFunctionType) = nothing +assert_invertible(::SFT.ScalarStructureFunctionType{2}) = nothing function assert_invertible(op::SFT.ProjectedStructureFunctionType{NL, NT}) where {NL, NT} if NL + NT == 2 @@ -314,6 +396,188 @@ function isotropic_spectrum(sf::SFO.StructureFunctionSumsAndCounts, wavenumbers: return isotropic_spectrum(sf.operator, collect(r)[keep], values, wavenumbers, Val(D); kwargs...) end +""" + isotropic_spectrum(result, geometry::SphericalGeometry, lmax) -> (l, C) + +Angular power spectrum `C_l`, `l = 1:lmax`, of a scalar or of the trace on a sphere, from a +second-order structure function binned in separation `r = R σ`. + +The isotropic correlation is `C(σ) = Σ_l (2l+1)/(4π) C_l P_l(cos σ)` and `D(σ) = 2[C(0) − C(σ)]`, so by +the orthogonality of the Legendre polynomials + +```math +C_l = -π ∫_0^π D(σ)\\, P_l(\\cos σ)\\, \\sin σ\\, dσ, \\qquad l ≥ 1, +``` + +with no variance needed: the constant `C(0)` is orthogonal to every `P_l` but `P_0`, which is the +one degree lost — the sphere's `k = 0`. Each bin's value is taken as constant across the bin and the +kernel is integrated over the bin in closed form, so the only error is that of the binning itself. +Every bin must hold a value: the integral runs over the whole sphere. A kernel-binned result on +[`HarmonicNodes`](@ref) integrates by the nodes' quadrature weights. +""" +function isotropic_spectrum(sf::SFO.AbstractStructureFunction, g::SFH.SphericalGeometry, lmax::Integer) + assert_invertible(sf.operator) + D, Q = _legendre_quadrature(sf, sf.distance, g, lmax) # values, and ∫ P_l sin σ dσ over each value's support, l = 0:lmax + C = [-π * sum(D[i] * Q[i, l + 1] for i in eachindex(D)) for l in 1:lmax] + return (l = 1:lmax, C = C) +end + +""" + helmholtz_spectra(L2, T2, geometry::SphericalGeometry, lmax; variance) -> (l, E, B) + +Gradient (`E`) and curl (`B`) angular power spectra, `l = 1:lmax`, of a tangent vector field on a +sphere, from its longitudinal and transverse second-order structure functions binned in `r = R σ`. + +In the geodesic frame `ξ₊ = C_LL + C_TT = Σ_l (2l+1)/(4π) (C^E_l + C^B_l) d^l_{11}(σ)` and +`ξ₋ = C_LL − C_TT = −Σ_l (2l+1)/(4π) (C^E_l − C^B_l) d^l_{1,−1}(σ)`, and the Wigner functions are +orthogonal with `∫₀^π d^l_{ss'} d^{l'}_{ss'} sin σ dσ = 2δ_{ll'}/(2l+1)`, so + +```math +C^E_l - C^B_l = π ∫_0^π (D_{LL} - D_{TT})\\, d^l_{1,-1}\\, \\sin σ\\, dσ, \\qquad +C^E_l + C^B_l = 2π ∫_0^π \\Big(⟨‖u‖²⟩ - \\frac{D_{LL} + D_{TT}}{2}\\Big)\\, d^l_{11}\\, \\sin σ\\, dσ . +``` + +The difference needs no constant because `C_LL(0) = C_TT(0)`; the sum needs the field's mean square +`⟨‖u‖²⟩`, which a structure function cannot supply, so `variance` is required. Bins are integrated in +closed form as in [`isotropic_spectrum`](@ref) on a sphere, nodes by their quadrature weights. +""" +function helmholtz_spectra( + L2::SFO.AbstractStructureFunction, T2::SFO.AbstractStructureFunction, g::SFH.SphericalGeometry, + lmax::Integer; variance::Real, +) + _assert_projection(L2.operator, 2, 0, "longitudinal") + _assert_projection(T2.operator, 0, 2, "transverse") + L2.distance == T2.distance || throw(ArgumentError( + "the two structure functions must share their distance bins", + )) + DLL, Gp, Gm = _wigner_quadrature(L2, L2.distance, g, lmax) # values, ∫ d^l_{11} sin σ dσ and ∫ d^l_{1,-1} sin σ dσ, l = 1:lmax + DTT, _, _ = _wigner_quadrature(T2, T2.distance, g, lmax) + E = Vector{Float64}(undef, lmax) + B = Vector{Float64}(undef, lmax) + for l in 1:lmax + diff = π * sum((DLL[i] - DTT[i]) * Gm[i, l] for i in eachindex(DLL)) + total = 2π * sum((variance - (DLL[i] + DTT[i]) / 2) * Gp[i, l] for i in eachindex(DLL)) + E[l] = (total + diff) / 2 + B[l] = (total - diff) / 2 + end + return (l = 1:lmax, E = E, B = B) +end + +# Bin values and edges in central angle, every bin holding a value. +function _spherical_bins(sf::SFO.AbstractStructureFunction, g::SFH.SphericalGeometry) + _, vals, keep = _binned(sf) + length(keep) == length(vals) || throw(ArgumentError( + "every bin must hold a value to integrate over the sphere; bins $(setdiff(eachindex(vals), keep)) are empty", + )) + edges = collect(sf.distance) ./ g.radius + last(edges) <= π * (1 + 1e-12) || throw(ArgumentError( + "the bins reach a central angle of $(last(edges)) on a sphere of radius $(g.radius); the largest " * + "separation on a sphere is π·R", + )) + return vals, edges +end + +# Every node's value, in the nodes' order. +function _node_values(sf::SFO.AbstractStructureFunction) + _, vals, keep = _binned(sf) + length(keep) == length(vals) || throw(ArgumentError( + "every node must hold a value to integrate over the sphere; nodes $(setdiff(eachindex(vals), keep)) have none", + )) + return vals +end + +# The values and, for l = 0:L, `∫ P_l(cos σ) sin σ dσ` over each value's support as (n_values, L + 1): +# closed-form bin integrals for edges, quadrature weights for nodes. +function _legendre_quadrature(sf, edges, g, L) + D, e = _spherical_bins(sf, g) + return D, _legendre_bin_integrals(e, L) +end + +function _legendre_quadrature(sf, nodes::HarmonicNodes, g, L) + D = _node_values(sf) + Q = Matrix{Float64}(undef, length(nodes), L + 1) + for k in eachindex(D) + Q[k, :] .= nodes.weights[k] .* _legendre_values(cos(nodes.separations[k]), L) + end + return D, Q +end + +# Likewise `∫ d^l_{11} sin σ dσ` and `∫ d^l_{1,−1} sin σ dσ`, l = 1:L. +function _wigner_quadrature(sf, edges, g, L) + D, e = _spherical_bins(sf, g) + Gp, Gm = _wigner_bin_integrals(e, L) + return D, Gp, Gm +end + +function _wigner_quadrature(sf, nodes::HarmonicNodes, g, L) + D = _node_values(sf) + Gp = Matrix{Float64}(undef, length(nodes), L) + Gm = Matrix{Float64}(undef, length(nodes), L) + for k in eachindex(D) + β = nodes.separations[k] + Gp[k, :] .= nodes.weights[k] .* @view(wigner_d_column(1, 1, β, L)[2:end]) + Gm[k, :] .= nodes.weights[k] .* @view(wigner_d_column(1, -1, β, L)[2:end]) + end + return D, Gp, Gm +end + +# P_0 … P_L at x by the three-term recurrence. +function _legendre_values(x::Real, L::Integer) + P = Vector{typeof(float(x))}(undef, L + 1) + P[1] = one(x) + L >= 1 && (P[2] = x) + for l in 1:(L - 1) + P[l + 2] = ((2l + 1) * x * P[l + 1] - l * P[l]) / (l + 1) + end + return P +end + +# ∫ P_l dx = (P_{l+1} − P_{l−1})/(2l+1) for l ≥ 1, and x for l = 0; `P` holds P_0 … P_{L+1}. +@inline _legendre_antiderivative(P, l, x) = l == 0 ? x : (P[l + 2] - P[l]) / (2l + 1) + +# ∫_{σ_i}^{σ_{i+1}} P_l(cos σ) sin σ dσ for every bin and l = 0:L, as (n_bins, L + 1). +function _legendre_bin_integrals(edges::AbstractVector, L::Integer) + x = cos.(edges) + nb = length(edges) - 1 + Q = Matrix{Float64}(undef, nb, L + 1) + Plo = _legendre_values(x[1], L + 1) + for i in 1:nb + Phi = _legendre_values(x[i + 1], L + 1) + for l in 0:L + Q[i, l + 1] = _legendre_antiderivative(Plo, l, x[i]) - _legendre_antiderivative(Phi, l, x[i + 1]) + end + Plo = Phi + end + return Q +end + +# ∫_{σ_i}^{σ_{i+1}} d^l_{11} sin σ dσ and ∫ d^l_{1,−1} sin σ dσ for l = 1:L, from +# d^l_{11} = P_l + (1 − x) P_l'/(l(l+1)), d^l_{1,−1} = −P_l + (1 + x) P_l'/(l(l+1)) and +# ∫ x P_l' dx = x P_l − ∫ P_l dx. +function _wigner_bin_integrals(edges::AbstractVector, L::Integer) + x = cos.(edges) + nb = length(edges) - 1 + Gp = Matrix{Float64}(undef, nb, L) + Gm = Matrix{Float64}(undef, nb, L) + anti(P, l, xx) = begin + Ql = _legendre_antiderivative(P, l, xx) + Pl = P[l + 1] + (Ql + ((1 - xx) * Pl + Ql) / (l * (l + 1)), -Ql + ((1 + xx) * Pl - Ql) / (l * (l + 1))) + end + Plo = _legendre_values(x[1], L + 1) + for i in 1:nb + Phi = _legendre_values(x[i + 1], L + 1) + for l in 1:L + plo, mlo = anti(Plo, l, x[i]) + phi, mhi = anti(Phi, l, x[i + 1]) + Gp[i, l] = plo - phi + Gm[i, l] = mlo - mhi + end + Plo = Phi + end + return Gp, Gm +end + """ shell_spectrum(P, wavenumbers, ::Val{D}) @@ -328,28 +592,30 @@ shell_spectrum(P::AbstractVector, wavenumbers::AbstractVector, ::Val{D}) where { """ assert_advective(operator) -Refuse a structure function that is not a cross-channel moment, so cannot be an advective one. +Refuse a structure function that is not a cross-field moment, so cannot be an advective one. A flux relation consumes `⟨δφ δ𝓐_φ⟩` for a quantity `φ` and its advection `𝓐_φ = u·∇φ`, which is a -moment across two channels. The diagonal `(a, a)` is a variance — `VectorDotSFType(1,1)` is `S2SF` — +moment across two fields. The diagonal `(a, a)` is a variance — `VectorDotSFType(1,1)` is `S2SF` — and carries no flux. -Whether the second channel really holds the advection of the first is the caller's construction, not -something a moment can report; this checks only that two distinct channels were asked for. +Whether the second field really holds the advection of the first is the caller's construction, not +something a moment can report; this checks only that two distinct fields were asked for. """ function assert_advective(op::Union{SFT.VectorDotStructureFunctionType, SFT.ScalarDotStructureFunctionType}) op.a == op.b && throw(ArgumentError( "$(nameof(typeof(op)))($(op.a), $(op.b)) is a diagonal moment, which is a variance and not " * - "a flux. A flux relation needs two distinct channels, a quantity and its advection.", + "a flux. A flux relation needs two distinct fields, a quantity and its advection.", )) return nothing end assert_advective(op) = throw(ArgumentError( - "$(nameof(typeof(op))) is not a cross-channel moment. A spectral flux follows from an " * + "$(nameof(typeof(op))) is not a cross-field moment. A spectral flux follows from an " * "advective structure function ⟨δφ δ𝓐_φ⟩, built with `VectorDotSFType(a, b)` or " * - "`ScalarDotSFType(a, b)` over a field carrying the quantity and its advection as two channels.", + "`ScalarDotSFType(a, b)` over a field carrying the quantity and its advection as two fields. " * + "The third-order routes are the `spectral_flux` methods on `S3SFType`, `L3SFType` (with `S3`) " * + "and `MixedSFType{1,0,2}`.", )) """ @@ -364,39 +630,29 @@ Interscale flux at each of `wavenumbers`, from an advective structure function s `SF_A` is the advective structure function averaged over the directions of the separation, so the same uniform-direction assumption [`isotropic_spectrum`](@ref) carries applies here. The relation -itself assumes no isotropy of the flow, which is what these estimators are for. +itself assumes no isotropy of the flow, which is what these estimators are for. The integral is the +trapezoid rule over the samples from the origin, where the integrand vanishes, to the last separation. The kernel's first peak sets which separations carry the most weight at a given wavenumber: `J₁` peaks at `Kr ≈ 1.84`, so the flux at `K` is reported on mostly by separations near `1.84/K`. That is a statement about weighting, not about where `Π` itself is largest — the explicit factor of `K` means `|Π|` keeps growing with `K` for a fixed feature. -This is the `J₁` relation, which takes the advective structure function. The companion relations -built on third-order structure functions use `J₂` and `J₃` with their own prefactors and carry -boundary terms that do not generally vanish, so they are not reachable by swapping the kernel order -here. +This is the `J₁` relation, which takes the advective structure function and assumes no isotropy of +the flow. The companion relations on third-order structure functions are the methods on +`S3SFType`, `L3SFType` and `MixedSFType{1,0,2}`, each with the boundary term its integration by +parts leaves at the last separation. """ function spectral_flux( operator, separations::AbstractVector, values::AbstractVector, wavenumbers::AbstractVector, ) assert_advective(operator) - length(separations) == length(values) || throw(DimensionMismatch( - "separations and values must agree in length; got $(length(separations)) and $(length(values))", - )) - issorted(separations) || throw(ArgumentError("separations must be sorted")) - - FT = float(promote_type(eltype(separations), eltype(values), eltype(wavenumbers))) - out = Vector{FT}(undef, length(wavenumbers)) - @inbounds for (j, K) in pairs(wavenumbers) - acc = zero(FT) - for i in eachindex(separations) - acc += FT(values[i]) * bessel_kernel(Val(1), K * FT(separations[i])) * - _quad_width(separations, i) - end - out[j] = -FT(K) * acc / 2 - end - return out + FT = _flux_samples(separations, values) + return [begin + K = FT(K0) + -K * _flux_quadrature(r -> bessel_kernel(Val(1), K * r), separations, values, FT) / 2 + end for K0 in wavenumbers] end function spectral_flux(sf::SFO.StructureFunction, wavenumbers::AbstractVector) @@ -414,23 +670,199 @@ function spectral_flux(sf::SFO.StructureFunctionSumsAndCounts, wavenumbers::Abst wavenumbers) end +# One sorted abscissa with every series sampled on it; returns the common float type. +function _flux_samples(separations::AbstractVector, series::AbstractVector...) + for v in series + length(v) == length(separations) || throw(DimensionMismatch( + "separations and values must agree in length; got $(length(separations)) and $(length(v))", + )) + end + issorted(separations) || throw(ArgumentError("separations must be sorted")) + isempty(separations) && throw(ArgumentError("no separation to integrate over")) + return float(promote_type(eltype(separations), map(eltype, series)...)) +end + +# ∫₀^R values(r) g(r) dr by the trapezoid rule over the samples from the origin, where every flux +# integrand vanishes; `g` is the kernel with its powers of r. +function _flux_quadrature(g, separations::AbstractVector, values::AbstractVector, ::Type{FT}) where {FT} + acc = zero(FT) + r0 = zero(FT) + f0 = zero(FT) + @inbounds for i in eachindex(separations) + r = FT(separations[i]) + f = FT(values[i]) * g(r) + acc += (f0 + f) * (r - r0) / 2 + r0, f0 = r, f + end + return acc +end + +# Π_K = −(K²/4) ∫₀^R S(r) J₂(Kr) dr − (K/4) S(R) J₁(KR), for S = ⟨δu_L ‖δu‖²⟩ or ⟨δu_L (δθ)²⟩. +function _j2_flux(separations::AbstractVector, S::AbstractVector, wavenumbers::AbstractVector) + FT = _flux_samples(separations, S) + R, SR = FT(last(separations)), FT(last(S)) + return [begin + K = FT(K0) + integral = _flux_quadrature(r -> bessel_kernel(Val(2), K * r), separations, S, FT) + -K^2 * integral / 4 - K * SR * bessel_kernel(Val(1), K * R) / 4 + end for K0 in wavenumbers] +end + +""" + spectral_flux(::S3SFType, separations, S3, wavenumbers) + +Interscale energy flux of a two-dimensional isotropic flow from `S3 = ⟨δu_L ‖δu‖²⟩`, sampled at +`separations` up to `R`: + +``` +Π_K = -(K²/4) ∫₀^R S3(r) J₂(Kr) dr - (K/4) S3(R) J₁(KR) +``` + +The `J₁` relation integrated by parts with `SF_A = (1/2r) d(r S3)/dr`, the isotropic divergence of +`⟨δu ‖δu‖²⟩`. The boundary term at `R` does not vanish at any finite `R` and is kept. `J₂` peaks at +`Kr ≈ 3.05`, so the flux at `K` is reported on mostly by separations near `3.05/K`. +""" +spectral_flux(::SFT.S3SFType, separations::AbstractVector, S3::AbstractVector, wavenumbers::AbstractVector) = + _j2_flux(separations, S3, wavenumbers) + +""" + spectral_flux(::MixedSFType{1,0,2}, separations, S, wavenumbers) + +Interscale flux of the variance of a scalar `θ` (enstrophy, for the vorticity) in a two-dimensional +isotropic flow from `S = ⟨δu_L (δθ)²⟩`, sampled at `separations` up to `R`: + +``` +Π_K = -(K²/4) ∫₀^R S(r) J₂(Kr) dr - (K/4) S(R) J₁(KR) +``` + +The `J₁` relation on `⟨δθ δ𝓐_θ⟩ = (1/2r) d(r S)/dr` integrated by parts, boundary term kept. +""" +spectral_flux(::SFT.MixedStructureFunctionType{1, 0, 2}, separations::AbstractVector, S::AbstractVector, + wavenumbers::AbstractVector) = _j2_flux(separations, S, wavenumbers) + +""" + spectral_flux(::L3SFType, separations, L3, S3, wavenumbers) + +Interscale energy flux of a two-dimensional isotropic flow from `L3 = ⟨δu_L³⟩`, with `S3 = ⟨δu_L ‖δu‖²⟩` +on the same `separations` for the boundary term: + +``` +Π_K = -(K³/12) ∫₀^R L3(r) J₃(Kr) r dr - (K²/12) [ R L3(R) J₂(KR) + (3/K) S3(R) J₁(KR) ] +``` + +The `S3` relation integrated by parts once more with `S3 = (1/3r²) d(r³ L3)/dr`, which holds for an +isotropic incompressible two-dimensional flow. Both boundary terms are kept. `J₃` peaks at `Kr ≈ 4.20`. +""" +function spectral_flux(::SFT.L3SFType, separations::AbstractVector, L3::AbstractVector, S3::AbstractVector, + wavenumbers::AbstractVector) + FT = _flux_samples(separations, L3, S3) + R, LR, SR = FT(last(separations)), FT(last(L3)), FT(last(S3)) + return [begin + K = FT(K0) + integral = _flux_quadrature(r -> bessel_kernel(Val(3), K * r) * r, separations, L3, FT) + -K^3 * integral / 12 - + K^2 * (R * LR * bessel_kernel(Val(2), K * R) + 3 * SR * bessel_kernel(Val(1), K * R) / K) / 12 + end for K0 in wavenumbers] +end + +""" + spectral_flux(L3, S3, wavenumbers) + +The `L3` route on two result objects sharing their distance bins, over the bins both hold. +""" +function spectral_flux(L3::SFO.AbstractStructureFunction, S3::SFO.AbstractStructureFunction, + wavenumbers::AbstractVector) + L3.operator isa SFT.L3SFType || throw(ArgumentError( + "the first structure function must be ⟨δu_L³⟩ (L3SFType); got $(nameof(typeof(L3.operator)))", + )) + S3.operator isa SFT.S3SFType || throw(ArgumentError( + "the second structure function must be ⟨δu_L ‖δu‖²⟩ (S3SFType); got $(nameof(typeof(S3.operator)))", + )) + r, vL, vS = _paired_bins(L3, S3) + return spectral_flux(L3.operator, r, vL, vS, wavenumbers) +end + +""" + enstrophy_flux(operator::VectorDotSFType, separations, SF_Au, wavenumbers) + enstrophy_flux(result, wavenumbers) + +Interscale enstrophy flux of a two-dimensional isotropic flow from the velocity's advective structure +function `SF_Au = ⟨δu · δ𝓐_u⟩`, `𝓐_u = u·∇u`, sampled at `separations` up to `R`: + +``` +Π^ω_K = (K³/2) ∫₀^R SF_Au(r) [J₃(Kr) - J₁(Kr)]/2 dr + (K²/2) [ SF_Au(R) J₂(KR) + (1/K) SF_Au'(R) J₁(KR) ] +``` + +The `J₁` relation on `⟨δω δ𝓐_ω⟩ = -∇² SF_Au` integrated by parts twice; `[J₃ - J₁]/2 = -J₂'`. The +slope `SF_Au'(R)` is the one-sided difference of the last two samples, so the boundary term is +sensitive to noise in the last bins. `operator` must name two distinct fields, the velocity and +its advection. +""" +function enstrophy_flux(op::SFT.VectorDotStructureFunctionType, separations::AbstractVector, + SF_Au::AbstractVector, wavenumbers::AbstractVector) + assert_advective(op) + FT = _flux_samples(separations, SF_Au) + length(separations) >= 2 || throw(ArgumentError( + "the boundary term needs the slope of SF_Au at the last separation; give at least two", + )) + R, AR = FT(last(separations)), FT(last(SF_Au)) + dA = (FT(SF_Au[end]) - FT(SF_Au[end - 1])) / (R - FT(separations[end - 1])) + return [begin + K = FT(K0) + integral = _flux_quadrature(r -> (bessel_kernel(Val(3), K * r) - bessel_kernel(Val(1), K * r)) / 2, + separations, SF_Au, FT) + K^3 * integral / 2 + K^2 * (AR * bessel_kernel(Val(2), K * R) + dA * bessel_kernel(Val(1), K * R) / K) / 2 + end for K0 in wavenumbers] +end + +function enstrophy_flux(sf::SFO.AbstractStructureFunction, wavenumbers::AbstractVector) + r, vals, keep = _binned(sf) + isempty(keep) && throw(ArgumentError("no finite structure function value to transform")) + return enstrophy_flux(sf.operator, r[keep], vals[keep], wavenumbers) +end + +""" + AbstractMissingLagPolicy + +What a lag-space spectrum does with a lag no pair of held cells names. `RefuseMissingLags()` throws, +since the structure function is undefined there. `ZeroDeviationAtMissingLags()` sets the +autocovariance to zero at that lag, which is what a taper does at the lags beyond its reach. +""" +abstract type AbstractMissingLagPolicy end +struct RefuseMissingLags <: AbstractMissingLagPolicy end +struct ZeroDeviationAtMissingLags <: AbstractMissingLagPolicy end + """ - gridded_spectrum(u, schedule, ::Val{D}, spectral_backend; valid) -> (wavenumbers, density) + gridded_spectrum(u, schedule, ::Val{D}, spectral_backend; valid, weights, taper, missing_lags) -> (wavenumbers, density) Spectral density of a gridded field, by transforming its structure function over the whole lag space. No direction is averaged over and no separation is binned, so this carries none of the angular -assumption [`isotropic_spectrum`](@ref) makes and is exact on a rectilinear grid. It reads the field -only through its structure function, so it accepts a field with cells missing, which is the case -where the field's own transform is meaningless while the pair average is still unbiased. +assumption [`isotropic_spectrum`](@ref) makes. It reads the field only through its structure function +and the variance of its held cells, so it accepts a field with cells missing, which is the case where +the field's own transform is meaningless while the pair average is still unbiased. + +On a complete periodic grid the result is the field's own spectrum to round-off. With cells missing, +or on a bounded direction, it is an **estimate**: the exact transform of the exact masked structure +function, equal to the complete field's spectrum in expectation, with a statistical error set by the +pair count behind each lag. A bounded direction is padded so the transform of the lags `|h| < n` is +their linear transform; `wavenumbers` then has the padded length along it. `taper` weights the lags +(see [`AbstractTaper`](@ref)) and `missing_lags` says what to do with a lag no held pair names (see +[`AbstractMissingLagPolicy`](@ref)). `weights`, one per cell, makes every pair sum and pair count a +`w_k w_kp`-weighted one and the variance a weighted variance, so the estimate is that of the weighted +structure function. `wavenumbers` is one angular-wavenumber vector per grid direction; `density` is the `Dg`-dimensional array over those, on the same convention as [`isotropic_spectrum`](@ref) — integrating it over -`d^D k` returns the variance, so `sum(density) * prod(step)` does, with `step` the wavenumber -spacing of each direction. +`d^D k` returns the variance of the held cells, so `sum(density) * prod(step)` does exactly, with +`step` the wavenumber spacing of each direction. The `k = 0` value is the sum of the weighted +autocovariance over the lags: zero to round-off on a complete periodic grid, where no pair sees the +mean, and the estimator's own low-wavenumber value otherwise. """ -function gridded_spectrum(u, schedule, ::Val{D}, spectral_backend; valid = AllValid()) where {D} +function gridded_spectrum(u, schedule, ::Val{D}, spectral_backend; valid = AllValid(), weights = nothing, + taper::AbstractTaper = NoTaper(), + missing_lags::AbstractMissingLagPolicy = RefuseMissingLags()) where {D} throw(ArgumentError( "no method transforms a gridded structure function with $(typeof(spectral_backend)). " * "Load an AbstractFFTs implementation — `using FFTW` on CPU.", diff --git a/src/Calculations/workspace.jl b/src/Calculations/workspace.jl index f8bcfaa..38e9a25 100644 --- a/src/Calculations/workspace.jl +++ b/src/Calculations/workspace.jl @@ -27,10 +27,8 @@ Reusable CPU scratch for the batch drivers: the batch-leading working copies of accumulator per task, and the full-width reduction accumulator. Pass to a batch entry point as `workspace = ...` to make repeated calls allocation-free. -Without it a batch call allocates one accumulator per task — tens of MiB at large `B` — on every -call. That does not slow the fastest call, but the resulting GC pauses land on *some* calls, so the -typical call is far slower than the best one and the spread is wide. Reusing the buffers removes -the pauses, not the peak. +Without it a batch call allocates one accumulator per task, tens of MiB at large `B`, on every +call; the GC pauses that follow land on some calls and widen the spread of call times. `kind` matches [`GPUSFWorkspace`](@ref): `:sf1d`, `:joint2d`, `:single_pass` or `:single_pass_2d`. It is a type parameter, so the accumulator rank is fixed at construction and every field is @@ -140,13 +138,12 @@ function reset_histogram!(ws::CPUSFWorkspace) return ws end -# --- Buffer providers for the batch drivers (the `::Nothing` fallbacks live in batch_leading.jl, -# which loads before this type exists) --- +# --- Buffer providers for the batch drivers --- @inline _ws_ub(ws::CPUSFWorkspace) = ws.ub @inline _ws_xb(ws::CPUSFWorkspace) = ws.xb -function _bl_accum_pool(ws::CPUSFWorkspace, ::F, widths::Vector{Int}) where {F} +function _bl_accum_pool(ws::CPUSFWorkspace, ::F, widths::AbstractVector{Int}) where {F} ws.widths == widths || throw(ArgumentError( "CPUSFWorkspace holds accumulators of batch widths $(ws.widths); this call needs $widths. \ Rebuild it with the same inputs, backend and n_tasks as the call.")) @@ -183,7 +180,6 @@ per-call `KA.zeros` allocation and repeated edge uploads. concretely typed — matching [`CPUSFWorkspace`](@ref). Use the matching constructor overload; `reset_histogram!(ws)` zeroes device outputs before each launch. The constructors live in `StructureFunctionsKernelAbstractionsExt` and need `using KernelAbstractions`. -See [`gpu/SP2D_HTP_EJ.md`](../gpu/SP2D_HTP_EJ.md). """ struct GPUSFWorkspace{kind, FT, BE, DB, VB, S, C, VE, DE, VP, ST, K, L} backend::BE @@ -238,7 +234,7 @@ end The tile-pair schedule a kernel with `tile`-point tiles enumerates: the full upper triangle when `cull` is `nothing`, otherwise the memo's device work list for that tile size, built and uploaded on first use and kept for later calls. Each kernel family picks its own tile, so the list is derived -from the grid at the size asked for rather than fixed when the memo is built. +from the grid at the size asked for, not fixed when the memo is built. """ schedule_for(::Nothing, n_points::Int, tile::Int) = FullUpperTriangle(cld(n_points, tile)) diff --git a/src/Channels.jl b/src/Channels.jl deleted file mode 100644 index ce33cbc..0000000 --- a/src/Channels.jl +++ /dev/null @@ -1,118 +0,0 @@ -""" -Multi-channel fields: several quantities sampled at the same points, differenced together. - -A structure function is a statement about one pair and any number of quantities carried at its two -ends. Velocity is a **vector** channel, parallel-transported by the geometry before differencing; a -tracer, a vorticity, a temperature is a **scalar** channel, differenced as it stands. Both are the -same pair sweep, so they belong in one field rather than in separate calls. -""" -module Channels - -using StaticArrays: StaticArrays as SA - -export Fields, ChannelIncrement, n_vector_channels, n_scalar_channels, channel_dimension - -""" - Fields(; vectors = (), scalars = ()) - -Several quantities sampled at one set of points: `vectors` are parallel-transported before being -differenced, `scalars` are differenced as they stand. - -```julia -Fields(vectors = (u,)) # a velocity — what a bare `u` already means -Fields(vectors = (u,), scalars = (θ,)) # velocity and a tracer, for the mixed laws -Fields(vectors = (u, 𝓐u)) # velocity and its advection -Fields(scalars = (ω, 𝓐ω)) # a scalar and its advection -``` - -Each vector is `(D, N)` and each scalar is `(N,)` or `(1, N)`. They are packed once, at construction, -into the single `(V·D + K, N)` array the kernels already load — so a pair costs one contiguous read -whatever it carries, and the channel counts are type parameters, so the kernel specialises on them. - -The name says what it is: these are the fields; those ones are vector fields; those are scalar -fields. Which is transported and which is not follows from that, and from nothing else. -""" -struct Fields{D, V, K, A <: AbstractMatrix} - data::A -end - -"""Velocity-like channels, each parallel-transported.""" -@inline n_vector_channels(::Fields{D, V, K}) where {D, V, K} = V - -"""Tracer-like channels, each differenced without transport.""" -@inline n_scalar_channels(::Fields{D, V, K}) where {D, V, K} = K - -"""Components in each vector channel.""" -@inline channel_dimension(::Fields{D}) where {D} = D - -@inline packed(f::Fields) = f.data - -@inline Base.size(f::Fields) = size(f.data) -@inline Base.eltype(::Fields{D, V, K, A}) where {D, V, K, A} = eltype(A) - -function Fields(; vectors = (), scalars = ()) - V = length(vectors) - K = length(scalars) - V * K >= 0 || throw(ArgumentError("channel counts cannot be negative")) - V + K > 0 || throw(ArgumentError( - "a field needs at least one channel; got no vectors and no scalars", - )) - D = V == 0 ? 0 : size(first(vectors), 1) - for (i, v) in enumerate(vectors) - ndims(v) == 2 || throw(ArgumentError( - "vector channel $i must be (D, N); got an array of $(ndims(v)) dimensions", - )) - size(v, 1) == D || throw(DimensionMismatch( - "vector channel $i has $(size(v, 1)) components, channel 1 has $D; every vector " * - "channel is transported by the same geometry and so must have the same dimension", - )) - end - N = V > 0 ? size(first(vectors), 2) : length(first(scalars)) - for (i, v) in enumerate(vectors) - size(v, 2) == N || throw(DimensionMismatch( - "vector channel $i covers $(size(v, 2)) points, expected $N", - )) - end - for (i, s) in enumerate(scalars) - length(s) == N || throw(DimensionMismatch( - "scalar channel $i covers $(length(s)) points, expected $N", - )) - end - - T = promote_type((eltype(v) for v in vectors)..., (eltype(s) for s in scalars)...) - data = Matrix{T}(undef, V * D + K, N) - @inbounds for (i, v) in enumerate(vectors), n in 1:N, d in 1:D - data[(i - 1) * D + d, n] = v[d, n] - end - @inbounds for (i, s) in enumerate(scalars), n in 1:N - data[V * D + i, n] = s[n] - end - return Fields{D, V, K, typeof(data)}(data) -end - -""" - ChannelIncrement(vectors, scalars) - -One pair's increment across every channel: each vector channel already transported into the pair's -common frame, each scalar channel already differenced. - -An operator reads the channels it names. A field of one vector channel and no scalars does **not** -produce one of these — its increment is the plain `SVector` every existing operator already takes, so -the single-channel path is unchanged down to the instruction. -""" -struct ChannelIncrement{D, V, K, T} - vectors::NTuple{V, SA.SVector{D, T}} - scalars::NTuple{K, T} -end - -"""The `i`-th transported vector increment.""" -@inline vector_channel(c::ChannelIncrement, i::Integer) = @inbounds c.vectors[i] - -"""The `i`-th scalar increment.""" -@inline scalar_channel(c::ChannelIncrement, i::Integer) = @inbounds c.scalars[i] - -@inline n_vector_channels(::ChannelIncrement{D, V, K}) where {D, V, K} = V -@inline n_scalar_channels(::ChannelIncrement{D, V, K}) where {D, V, K} = K -@inline channel_dimension(::ChannelIncrement{D}) where {D} = D - -end # module Channels diff --git a/src/HelperFunctions.jl b/src/HelperFunctions.jl index 4229e7d..ff599ff 100644 --- a/src/HelperFunctions.jl +++ b/src/HelperFunctions.jl @@ -24,8 +24,6 @@ export digitize, AbstractTransverseBasisConvention, CanonicalTransverseBasis, ReferenceAxisTransverseBasis, - CoordinateGaugeTransverseBasis, - UserTransverseBasis, r̂, n̂, δr, @@ -35,6 +33,7 @@ export digitize, geodesic_increments, FlatGeometry, SphericalGeometry, + SphericalDistance, coordinate_width, input_coordinate_width, field_width, @@ -43,6 +42,7 @@ export digitize, pair_frame, pair_direction, pair_delta, + pair_orientation, pair_invariants, pair_increments, pair_geometry, @@ -77,20 +77,17 @@ function remove_nans(x_mat::AbstractMatrix{FT}, u_mat::AbstractMatrix{FT}) where return x_mat[:, valid_mask], u_mat[:, valid_mask] end +""" + digitize(x, bins) -> Int + +The index of the bin `(bins[i], bins[i + 1]]` holding `x`: `0` below the first edge and `length(bins)` +above the last. A vector `x` gives one index per element. The bins are right-inclusive. +""" @inline function digitize(x, bins::AbstractVector) - """ - Return the index of the bin that x belongs to - (see np.digitize and https://discourse.julialang.org/t/find-the-index-of-a-bin-where-a-value-between-two-bin-value/32080/2?u=jbphyswx ) - Note that the bins are right inclusive, the bins are (a,b] - """ searchsortedfirst(bins, x) - 1 end @inline function digitize(x::AbstractVector, bins::AbstractVector) - """ - Return the indices of the bins that x belongs to - (see np.digitize and https://discourse.julialang.org/t/find-the-index-of-a-bin-where-a-value-between-two-bin-value/32080/2?u=jbphyswx ) - """ digitize.(x, Ref(bins)) end @@ -112,8 +109,7 @@ end end @inline r̂(x1, x2, ::DI.Euclidean, distance) = δr(x1, x2) / distance -# NOTE: LA.normalize is fast here because the vector is a StaticArray.SVector. -# If dynamic Vectors are ever used, LA.normalize would be ~2.5x slower due to scaling checks. +# `LA.normalize` is cheap here because the vector is an `SVector`: no scaling checks. @inline r̂(x1, x2, ::DI.PreMetric, distance) = LA.normalize(δr(x1, x2)) # ----------------------------------------------------------------------------- @@ -147,9 +143,9 @@ Smallest `sin²σ` for which the separation direction is still representable. This guards only against `1/0`, NOT against a physical scale: the normalization is exact in the `σ → 0` limit (`t_A ≈ d` has magnitude `O(σ)` and `inv_s ≈ 1/σ`, so the product stays `O(1)`), so -short pairs are fine and must not be dropped. `eps(T)` would be catastrophically wrong here — -`sin²σ` for a 1 km separation on Earth is `2.5e-8`, below `eps(Float32)`, which would silently -discard every pair closer than ~2 km in Float32. +short pairs are fine and must not be dropped. The tolerance is `floatmin`, not `eps`: `sin²σ` for a +1 km separation on Earth is `2.5e-8`, below `eps(Float32)`, so an `eps` guard silently discards every +`Float32` pair closer than about 2 km. """ @inline _geodesic_degeneracy_tol(::Type{T}) where {T} = floatmin(T) @@ -160,8 +156,7 @@ Smallest `‖p̂+q̂‖²` for which the separation direction still carries info [`_geodesic_degeneracy_tol`](@ref) guards `σ → 0`, where the cancellation in `t_A = d − (d·p̂)p̂` is exact in structure and short pairs are computed perfectly. At `σ → π` it is not: `d ≈ −2p̂` and `d·p̂ ≈ −2`, so `t_A` is the difference of two `O(2)` quantities and the direction's error grows as -`ε/(π−σ)` — measured against `BigFloat` at 3.7e-11 for `π−σ = 1e-5`, 3.5e-3 for `1e-13`, and **0.385** -for `1e-15`, i.e. a unit vector wrong by 38%. +`ε/(π−σ)`: against `BigFloat` it reaches 0.385 at `π−σ = 1e-15`, a unit vector wrong by 38 %. `‖p̂+q̂‖ = 2cos(σ/2) ≈ π−σ` near that root, so requiring `eps(T)` here bounds the direction error at about `sqrt(eps(T))`. Antipodal points are joined by infinitely many great circles, so no tie-break @@ -181,8 +176,8 @@ of that circle, hence tangent to the sphere at each of them, and it is parallel Both tangents also share one normalizer, since `‖q̂ − (p̂·q̂)p̂‖² = ‖(p̂·q̂)q̂ − p̂‖² = 1 − (p̂·q̂)²`. So the whole frame costs one `sqrt`. -`σ` uses the tangent-half-angle form `2·atan(‖p̂−q̂‖, ‖p̂+q̂‖)`, which is accurate for every `σ` -including antipodal, unlike `acos(p̂·q̂)` (which loses half the mantissa near `σ=0` — fatal in Float32). +`σ` uses the tangent-half-angle form `2·atan(‖p̂−q̂‖, ‖p̂+q̂‖)`, accurate for every `σ` including +antipodal. `acos(p̂·q̂)` loses half the mantissa near `σ=0`, which is fatal in `Float32`. `ok` is `false` for coincident (`σ=0`) and antipodal (`σ=π`) pairs, where the direction is genuinely undefined — antipodal points are joined by infinitely many great circles, so parallel transport @@ -237,8 +232,8 @@ SphericalGeometry{D}(metric::M, radius::T) where {D, M, T} = SphericalGeometry{D coordinate_width(geometry) -> Val{W} How many numbers locate one point in the form the kernels consume, as a `Val` so callers can build a -statically-sized load. This is not the velocity dimension: a point on a shell takes three ambient -components whether or not the velocity carries a radial one. +statically-sized load. It is the coordinate count, never the velocity dimension: a point on a shell +takes three ambient components whether or not the velocity carries a radial one. See [`input_coordinate_width`](@ref) for the width a caller supplies and [`prepare_pair_inputs`](@ref) for the conversion between the two. @@ -317,8 +312,8 @@ On the sphere the frame IS the basis, so the longitudinal direction is `ê₁` b pair_invariants(geometry, frame, r, u1, u2) -> (δu_L, ‖δu‖²) The only two scalars the six isotropic invariants consume: every one of them is built from `δu_L`, -`δu_L²` and `δu_T² = ‖δu‖² − δu_L²`. Kernels that need no separation direction call this instead of -[`pair_increments`](@ref) and never form `r̂`. +`δu_L²` and `δu_T² = ‖δu‖² − δu_L²`. A kernel that needs no separation direction calls this and never +forms `r̂`; [`pair_increments`](@ref) is the form that does. """ @inline function pair_invariants(::FlatGeometry, frame, r, u1, u2) δu = u2 - u1 @@ -332,6 +327,33 @@ end return δu[1], LA.dot(δu, δu) end +""" + pair_orientation(geometry, frame) -> Int + +Which end of a pair is read first: `+1` when the pair as given runs from the lower to the upper end +along the first coordinate that separates its points, `-1` when it runs the other way, `0` when +neither end comes first. On a sphere a pair is read from south to north, and along one parallel from +west to east by the shorter way round. Only operators odd in a scalar increment see this sign; every +vector quantity is the same read either way. +""" +@inline function pair_orientation(::FlatGeometry, dx) + @inbounds for d in eachindex(dx) + iszero(dx[d]) || return dx[d] > 0 ? 1 : -1 + end + return 0 +end + +@inline function pair_orientation(::SphericalGeometry, frame) + p̂, q̂ = frame[4], frame[5] + north = q̂[3] - p̂[3] # exact for two points on one parallel + iszero(north) || return north > 0 ? 1 : -1 + east = p̂[1] * q̂[2] - p̂[2] * q̂[1] # (p̂ × q̂)·ẑ, the sense of the shorter turn about ẑ + iszero(east) || return east > 0 ? 1 : -1 + return 0 +end + +pair_orientation(geometry, frame) = 1 + """ pair_delta(geometry, frame, x1, x2, u1, u2) -> δu @@ -379,7 +401,7 @@ fixed-position batch), in which case its single slice supplies the basis for all prepare_coordinates(geometry, x) -> x_kernel The coordinate half of [`prepare_pair_inputs`](@ref), for a caller that has no field to convert -alongside — a field of scalar channels only has nothing to transport, but its points still have to +alongside — a field of scalar fields only has nothing to transport, but its points still have to reach the form the kernels index. """ @inline prepare_coordinates(::Any, x) = x @@ -466,8 +488,8 @@ end pair_geometry_for(metric, ::Val{D}) -> geometry Geometry implied by `metric` for user-facing dimension `D`. A distance function alone does not define -a direction or a transport rule, so there is deliberately **no generic method**: an unrecognized -metric raises rather than silently assuming flat space. Add a method here (and a +a direction or a transport rule, so there is deliberately **no generic method** and an unrecognized +metric raises. Add a method here (and a [`pair_geometry`](@ref) method for the geometry it returns) to support another manifold. """ pair_geometry_for(::DI.Euclidean, ::Val{D}) where {D} = FlatGeometry{D}() @@ -475,14 +497,34 @@ pair_geometry_for(m::DI.Haversine, ::Val{D}) where {D} = SphericalGeometry{D}(m, # SphericalAngle reports the central angle itself, i.e. a unit sphere. pair_geometry_for(m::DI.SphericalAngle, ::Val{D}) where {D} = SphericalGeometry{D}(m, 1) +""" + SphericalDistance(radius) + +Great-circle distance on a sphere of the given `radius` between points given as `(longitude, +latitude)` in **radians**: `radius` times `Distances.SphericalAngle`. The one metric a +spherical grid of known radius hands to every route, so separations come out in the radius's unit +on each of them. +""" +struct SphericalDistance{T <: Real} <: DI.Metric + radius::T +end + +@inline (m::SphericalDistance)(x, y) = m.radius * DI.SphericalAngle()(x, y) + +DI.result_type(m::SphericalDistance, ::Type{T1}, ::Type{T2}) where {T1 <: Number, T2 <: Number} = + float(promote_type(typeof(m.radius), T1, T2)) + +pair_geometry_for(m::SphericalDistance, ::Val{D}) where {D} = SphericalGeometry{D}(m, m.radius) + """ unit_position(metric, lon, lat) -> SVector{3} local_east_north(metric, lon, lat) -> (Ê, N̂) Ingest helpers that take the angle unit from the metric's own documented convention: -`Distances.Haversine` is **degrees**, `Distances.SphericalAngle` is **radians**. Confusing the two +`Distances.Haversine` is **degrees**, `Distances.SphericalAngle` and [`SphericalDistance`](@ref) are +**radians**. Confusing the two silently rescales every separation by a factor of ~57, so the convention is pinned next to the metric -that defines it rather than repeated at each call site. +that defines it. """ @inline unit_position(::DI.Haversine, lon, lat) = unit_position(lon, lat) @inline local_east_north(::DI.Haversine, lon, lat) = local_east_north(lon, lat) @@ -490,6 +532,9 @@ that defines it rather than repeated at each call site. _unit_position(sincos(lon)..., sincos(lat)...) @inline local_east_north(::DI.SphericalAngle, lon, lat) = _local_east_north(sincos(lon)..., sincos(lat)...) +@inline unit_position(::SphericalDistance, lon, lat) = _unit_position(sincos(lon)..., sincos(lat)...) +@inline local_east_north(::SphericalDistance, lon, lat) = + _local_east_north(sincos(lon)..., sincos(lat)...) pair_geometry_for(m, ::Val{D}) where {D} = throw(ArgumentError( "no pair geometry is defined for distance_metric=$(typeof(m)). A distance function fixes which " * @@ -524,11 +569,14 @@ end Oriented transverse unit vector for the longitudinal unit vector `r_hat`. 2D: `n̂ = ẑ × r̂ = (−r̂₂, r̂₁)`, the counterclockwise quarter turn, so `(r̂, n̂, ẑ)` is right-handed. -3D: `n̂ = normalize(ẑ × r̂)`, the same rule with `ẑ = (0,0,1)` as the reference axis. +3D: `n̂ = normalize(ẑ × r̂)`, the same rule with `ẑ = (0,0,1)` as the reference axis; along `ẑ`, where +that product vanishes (`‖ẑ × r̂‖² ≤ eps`), the rule continues with `x̂` as the axis, `n̂ = normalize(x̂ × r̂)`, +which is `−ŷ` at `r̂ = ẑ` and `+ŷ` at `r̂ = −ẑ`. Only operators odd in the transverse component see this sign — `ProjectedStructureFunctionType{2,1}` and `{0,3}`. Everything else consumes `δu_T²` (see [`transverse_norm2`](@ref)) and is sign-blind. -The 3D form is singular when `r̂ ∥ ẑ`; [`ReferenceAxisTransverseBasis`](@ref) is the guarded version. +As a convention carried by an operator this rule is [`CanonicalTransverseBasis`](@ref); one with a +chosen axis is [`ReferenceAxisTransverseBasis`](@ref). """ @inline function n̂(r_hat::AbstractVector{FT}) where {FT} ND::Int = length(r_hat) @@ -536,10 +584,7 @@ The 3D form is singular when `r̂ ∥ ẑ`; [`ReferenceAxisTransverseBasis`](@re if ND == 2 return SA.SVector{2, FT}(-r_hat[2], r_hat[1]) # assume normalized elseif ND == 3 - k_hat = SA.SVector{3, FT}(0, 0, 1) - return LA.normalize( - LA.cross(k_hat, SA.SVector{3, FT}(r_hat[1], r_hat[2], r_hat[3])), - ) + return n̂(SA.SVector{3, FT}(r_hat[1], r_hat[2], r_hat[3])) else throw(ArgumentError( "an oriented transverse direction is defined here only for D = 2 (the quarter turn) " * @@ -551,9 +596,19 @@ The 3D form is singular when `r̂ ∥ ẑ`; [`ReferenceAxisTransverseBasis`](@re end @inline n̂(r_hat::SA.SVector{2, T}) where {T} = SA.SVector{2, T}(-r_hat[2], r_hat[1]) -@inline n̂(r_hat::SA.SVector{3, T}) where {T} = LA.normalize( - LA.cross(SA.SVector{3, T}(0, 0, 1), SA.SVector{3, T}(r_hat[1], r_hat[2], r_hat[3])), -) + +"""Squared-norm floor below which `ẑ × r̂` is taken as vanishing and the transverse rule falls to `x̂`.""" +@inline _transverse_degeneracy_tol(::Type{T}) where {T} = eps(T) + +@inline function n̂(r_hat::SA.SVector{3, T}) where {T} + c = LA.cross(SA.SVector{3, T}(0, 0, 1), r_hat) + c2 = LA.dot(c, c) + if c2 <= _transverse_degeneracy_tol(T) + c = LA.cross(SA.SVector{3, T}(1, 0, 0), r_hat) + c2 = LA.dot(c, c) + end + return c / sqrt(c2) +end @inline n̂(r_hat::NTuple{2, T}) where {T} = (-r_hat[2], r_hat[1]) @@ -568,27 +623,33 @@ and Cho convention. return n̂(r̂(x1, x2)) end +""" + AbstractTransverseBasisConvention + +A rule giving the transverse basis of a pair from its unit separation: `transverse_basis(rule, r̂)` +returns a tuple of unit vectors perpendicular to `r̂` and to each other, whose first vector is odd +under `r̂ ↦ −r̂`. Operators odd in the transverse component read that first vector, and its oddness +is what makes them read the same from either end of a pair. A new rule is a subtype with that one +method. +""" abstract type AbstractTransverseBasisConvention end """ CanonicalTransverseBasis() -The canonical oriented transverse basis in 2D, equivalent to [`n̂`](@ref). -It is intentionally undefined for 3D because there is no unique oriented -transverse direction without extra information. +The transverse direction [`n̂`](@ref): in 2-D the quarter turn of `r̂`; in 3-D the turn about `ẑ`, +continued about `x̂` where `r̂ ∥ ẑ`, followed by `r̂ × n̂`. Every projected operator carries this +convention unless constructed with another. """ struct CanonicalTransverseBasis <: AbstractTransverseBasisConvention end """ - ReferenceAxisTransverseBasis(axis; parallel_tol=1e-12) + ReferenceAxisTransverseBasis(axis; parallel_tol = 1e-12) -Project a physical reference axis into the plane perpendicular to `r̂` and -normalize it to get the first transverse basis vector. In 3D, the second -transverse vector is `cross(r̂, e₁)`. - -If the reference axis is parallel or nearly parallel to `r̂`, construction of -the per-pair basis throws `ArgumentError`. The tolerance is explicit because -this is a physical convention, not a hidden computational replacement. +The rule of [`n̂`](@ref) about a chosen axis `a` in 3-D: `e₁ = normalize(a × r̂)` and `e₂ = r̂ × e₁`. +With `a = ẑ` it is [`CanonicalTransverseBasis`](@ref) without the continuation along `ẑ`: where +`‖a × r̂‖² ≤ parallel_tol²` it throws `ArgumentError`. Refused in 2-D, where the transverse line is +`n̂` and an axis adds nothing. """ struct ReferenceAxisTransverseBasis{A, T} <: AbstractTransverseBasisConvention axis::A @@ -598,26 +659,6 @@ end ReferenceAxisTransverseBasis(axis; parallel_tol = 1e-12) = ReferenceAxisTransverseBasis(axis, parallel_tol) -""" - CoordinateGaugeTransverseBasis() - -An always-defined computational gauge for 3D: choose the coordinate axis least -aligned with `r̂`, project it into the perpendicular plane, and complete a -right-handed basis. This is useful for deterministic component diagnostics, -but the chosen direction can jump discontinuously as `r̂` changes. -""" -struct CoordinateGaugeTransverseBasis <: AbstractTransverseBasisConvention end - -""" - UserTransverseBasis(f) - -Use `f(r̂)` as the transverse basis provider. The function must return either -a single unit vector or a tuple of unit vectors perpendicular to `r̂`. -""" -struct UserTransverseBasis{F} <: AbstractTransverseBasisConvention - basis_function::F -end - @inline function _sum_abs2(x) out = zero(eltype(x)) @inbounds for i in eachindex(x) @@ -630,73 +671,53 @@ end return SA.SVector{length(r_hat), eltype(r_hat)}(ntuple(i -> x[i], length(r_hat))) end -@inline function _project_reference_axis(axis, r_hat, parallel_tol) - a = _as_svector_like(r_hat, axis) - projected = a - LA.dot(a, r_hat) * r_hat - projected_norm2 = _sum_abs2(projected) - tol2 = parallel_tol * parallel_tol - projected_norm2 > tol2 || throw( - ArgumentError( - "reference axis is parallel or nearly parallel to r̂; " * - "choose a different axis or use CoordinateGaugeTransverseBasis()", - ), - ) - return projected / sqrt(projected_norm2) -end - -@inline function transverse_basis(::CanonicalTransverseBasis, r_hat::SA.SVector{2}) - return (n̂(r_hat),) +@inline function _axis_transverse(axis, r_hat::SA.SVector{3}, parallel_tol) + c = LA.cross(_as_svector_like(r_hat, axis), r_hat) + c2 = _sum_abs2(c) + c2 > parallel_tol * parallel_tol || throw(ArgumentError( + "the reference axis is parallel to r̂ for this pair, which leaves no transverse direction; choose an axis no separation is parallel to, or CanonicalTransverseBasis()", + )) + return c / sqrt(c2) end -@inline function transverse_basis(::CanonicalTransverseBasis, r_hat) - length(r_hat) == 2 || throw(ArgumentError("CanonicalTransverseBasis is only defined in 2D")) - return (n̂(r_hat),) -end +""" + transverse_basis(rule::AbstractTransverseBasisConvention, r̂) -> NTuple of unit vectors -@inline function transverse_basis(basis::ReferenceAxisTransverseBasis, r_hat::SA.SVector{2}) - e1 = _project_reference_axis(basis.axis, r_hat, basis.parallel_tol) - return (e1,) -end +The transverse basis of a pair with unit separation `r̂` under `rule`: one vector in two dimensions, +two in three, each perpendicular to `r̂` and to the others, the first odd under `r̂ ↦ −r̂`. +""" +@inline transverse_basis(::CanonicalTransverseBasis, r_hat::SA.SVector{2}) = (n̂(r_hat),) -@inline function transverse_basis(basis::ReferenceAxisTransverseBasis, r_hat::SA.SVector{3}) - e1 = _project_reference_axis(basis.axis, r_hat, basis.parallel_tol) - e2 = LA.cross(r_hat, e1) - return (e1, e2) +@inline function transverse_basis(::CanonicalTransverseBasis, r_hat::SA.SVector{3}) + n = n̂(r_hat) + return (n, LA.cross(r_hat, n)) end -@inline function transverse_basis(basis::ReferenceAxisTransverseBasis, r_hat) +@inline function transverse_basis(basis::CanonicalTransverseBasis, r_hat) D = length(r_hat) D == 2 && return transverse_basis(basis, SA.SVector{2, eltype(r_hat)}(r_hat)) D == 3 && return transverse_basis(basis, SA.SVector{3, eltype(r_hat)}(r_hat)) - throw(ArgumentError("ReferenceAxisTransverseBasis currently supports D=2 or D=3")) + throw(ArgumentError("CanonicalTransverseBasis is defined for D = 2 and D = 3")) end -@inline function transverse_basis(::CoordinateGaugeTransverseBasis, r_hat::SA.SVector{3, T}) where {T} - ax = abs(r_hat[1]) - ay = abs(r_hat[2]) - az = abs(r_hat[3]) - axis = ax <= ay && ax <= az ? SA.SVector{3, T}(1, 0, 0) : - ay <= az ? SA.SVector{3, T}(0, 1, 0) : - SA.SVector{3, T}(0, 0, 1) - e1 = axis - LA.dot(axis, r_hat) * r_hat - e1 = e1 / sqrt(_sum_abs2(e1)) - e2 = LA.cross(r_hat, e1) - return (e1, e2) -end - -@inline function transverse_basis(::CoordinateGaugeTransverseBasis, r_hat::SA.SVector{2}) - return (n̂(r_hat),) +@inline function transverse_basis(basis::ReferenceAxisTransverseBasis, r_hat::SA.SVector{3}) + e1 = _axis_transverse(basis.axis, r_hat, basis.parallel_tol) + return (e1, LA.cross(r_hat, e1)) end -@inline function transverse_basis(basis::CoordinateGaugeTransverseBasis, r_hat) - D = length(r_hat) - D == 2 && return transverse_basis(basis, SA.SVector{2, eltype(r_hat)}(r_hat)) - D == 3 && return transverse_basis(basis, SA.SVector{3, eltype(r_hat)}(r_hat)) - throw(ArgumentError("CoordinateGaugeTransverseBasis currently supports D=2 or D=3")) +@inline function transverse_basis(basis::ReferenceAxisTransverseBasis, r_hat) + length(r_hat) == 3 || throw(ArgumentError( + "ReferenceAxisTransverseBasis is defined in 3-D; in 2-D the transverse direction is n̂, CanonicalTransverseBasis()", + )) + return transverse_basis(basis, SA.SVector{3, eltype(r_hat)}(r_hat)) end -@inline transverse_basis(basis::UserTransverseBasis, r_hat) = basis.basis_function(r_hat) +""" + transverse_basis_vector(r̂, rule, index = 1) +The `index`-th vector of [`transverse_basis`](@ref)`(rule, r̂)`; the first is the signed transverse +direction an odd transverse operator reads. +""" @inline function transverse_basis_vector(r_hat, basis::AbstractTransverseBasisConvention, basis_index::Integer = 1) basis_vectors = transverse_basis(basis, r_hat) 1 <= basis_index <= length(basis_vectors) || @@ -726,7 +747,7 @@ Return the transverse magnitude of `δu`, signed relative to the normal vector ` caller must ensure `r_hat` is a unit vector. """ @inline function magnitude_δu_transverse(δu, r_hat) - # Signed relative to n̂, unlike LA.norm(δu .- δu_longitudinal(δu, r_hat)). + # Signed relative to n̂; the norm of the rejected component is the unsigned magnitude. return LA.dot(δu, n̂(r_hat)) end diff --git a/src/MultiFields.jl b/src/MultiFields.jl new file mode 100644 index 0000000..bd80418 --- /dev/null +++ b/src/MultiFields.jl @@ -0,0 +1,124 @@ +""" +Several fields at one set of points, differenced together. + +A structure function is a statement about one pair and any number of quantities carried at its two +ends. Velocity is a **vector** field, parallel-transported by the geometry before differencing; a +tracer, a vorticity, a temperature is a **scalar** field, differenced as it stands. Both are the +same pair sweep, so they travel together in one [`Fields`](@ref). +""" +module MultiFields + +using StaticArrays: StaticArrays as SA + +export Fields, FieldIncrement, n_vector_fields, n_scalar_fields, field_dimension + +""" + Fields(; vectors = (), scalars = ()) + +Several quantities sampled at one set of points: `vectors` are parallel-transported before being +differenced, `scalars` are differenced as they stand. + +```julia +Fields(vectors = (u,)) # a velocity — what a bare `u` already means +Fields(vectors = (u,), scalars = (θ,)) # velocity and a tracer, for the mixed laws +Fields(vectors = (u, 𝓐u)) # velocity and its advection +Fields(scalars = (ω, 𝓐ω)) # a scalar and its advection +``` + +Each vector is `(D, N)` and each scalar is `(N,)` or `(1, N)`; on a grid, each vector is +`(D, cells...)` and each scalar `(cells...)`, the cells flattened in the order the array stores them. +They are packed once, at construction, into the single `(V·D + K, N)` array the kernels already load — +so a pair costs one contiguous read whatever it carries, and the field counts are type parameters, +so the kernel specialises on them. + +Which is transported and which is not follows from the name and from nothing else: a vector field +carries a direction the geometry must rotate, a scalar field does not. +""" +struct Fields{D, V, K, A <: AbstractMatrix} + data::A +end + +"""Velocity-like fields, each parallel-transported.""" +@inline n_vector_fields(::Fields{D, V, K}) where {D, V, K} = V + +"""Tracer-like fields, each differenced without transport.""" +@inline n_scalar_fields(::Fields{D, V, K}) where {D, V, K} = K + +"""Components in each vector field.""" +@inline field_dimension(::Fields{D}) where {D} = D + +@inline packed(f::Fields) = f.data + +@inline Base.size(f::Fields) = size(f.data) +@inline Base.eltype(::Fields{D, V, K, A}) where {D, V, K, A} = eltype(A) + +function Fields(; vectors = (), scalars = ()) + V = length(vectors) + K = length(scalars) + V * K >= 0 || throw(ArgumentError("field counts cannot be negative")) + V + K > 0 || throw(ArgumentError( + "a field needs at least one field; got no vectors and no scalars", + )) + D = V == 0 ? 0 : size(first(vectors), 1) + for (i, v) in enumerate(vectors) + ndims(v) >= 2 || throw(ArgumentError( + "vector field $i must be (D, N) or (D, cells...); got an array of $(ndims(v)) dimensions", + )) + size(v, 1) == D || throw(DimensionMismatch( + "vector field $i has $(size(v, 1)) components, field 1 has $D; every vector " * + "field is transported by the same geometry and so must have the same dimension", + )) + end + cells = V > 0 ? size(first(vectors))[2:end] : size(first(scalars)) + N = prod(cells) + for (i, v) in enumerate(vectors) + size(v)[2:end] == cells || throw(DimensionMismatch( + "vector field $i covers cells $(size(v)[2:end]), expected $cells", + )) + end + for (i, s) in enumerate(scalars) + (size(s) == cells || length(s) == N) || throw(DimensionMismatch( + "scalar field $i covers $(size(s)), expected $cells or $N points", + )) + end + + T = promote_type((eltype(v) for v in vectors)..., (eltype(s) for s in scalars)...) + data = Matrix{T}(undef, V * D + K, N) + @inbounds for (i, v) in enumerate(vectors) + vf = reshape(v, D, N) + for n in 1:N, d in 1:D + data[(i - 1) * D + d, n] = vf[d, n] + end + end + @inbounds for (i, s) in enumerate(scalars), n in 1:N + data[V * D + i, n] = s[n] + end + return Fields{D, V, K, typeof(data)}(data) +end + +""" + FieldIncrement(vectors, scalars) + +One pair's increment across every field: each vector field already transported into the pair's +common frame, each scalar field already differenced. + +An operator reads the fields it names. A field of one vector field and no scalars does **not** +produce one of these — its increment is the plain `SVector` every existing operator already takes, so +the single-field path is unchanged down to the instruction. +""" +struct FieldIncrement{D, V, K, T} + vectors::NTuple{V, SA.SVector{D, T}} + scalars::NTuple{K, T} +end + +"""The `i`-th transported vector increment.""" +@inline vector_field(c::FieldIncrement, i::Integer) = @inbounds c.vectors[i] + +"""The `i`-th scalar increment.""" +@inline scalar_field(c::FieldIncrement, i::Integer) = @inbounds c.scalars[i] + +@inline n_vector_fields(::FieldIncrement{D, V, K}) where {D, V, K} = V +@inline n_scalar_fields(::FieldIncrement{D, V, K}) where {D, V, K} = K +@inline field_dimension(::FieldIncrement{D}) where {D} = D + +end # module MultiFields diff --git a/src/StructureFunctionObjects.jl b/src/StructureFunctionObjects.jl index c59e670..c47bd02 100644 --- a/src/StructureFunctionObjects.jl +++ b/src/StructureFunctionObjects.jl @@ -1,6 +1,11 @@ module StructureFunctionObjects using ..StructureFunctionTypes: StructureFunctionTypes as SFT +using ..StructureFunctions: HarmonicNodes + +# Values a result on this distance object carries: one per bin between flat edges, one per node. +@inline _value_slots(distance) = length(distance) - 1 +@inline _value_slots(distance::HarmonicNodes) = length(distance) export AbstractStructureFunction, StructureFunction, @@ -8,6 +13,7 @@ export AbstractStructureFunction, StructureFunction2DSumsAndCounts, StructureFunctionTensor, StructureFunctionTensorSumsAndCounts, + StructureFunctionTensor2DSumsAndCounts, HelmholtzDecomposition2D, marginalize @@ -35,7 +41,7 @@ struct StructureFunction{FT, OT <: SFT.AbstractStructureFunctionType, BT, VT} <: function StructureFunction(operator::OT, distance::BT, values::VT) where {OT, BT, VT} n_values = values isa AbstractArray && ndims(values) > 1 ? size(values, 1) : length(values) - (length(distance) == n_values + 1) || throw(DimensionMismatch("Flat distance edges must have length one greater than the leading value-bin axis (got edges=$(length(distance)), value bins=$n_values)")) + (_value_slots(distance) == n_values) || throw(DimensionMismatch("Flat distance edges must have length one greater than the leading value-bin axis (got edges=$(length(distance)), value bins=$n_values)")) FT = eltype(VT) return new{FT, OT, BT, VT}(operator, distance, values) end @@ -67,7 +73,7 @@ struct StructureFunctionSumsAndCounts{ ) where {OT, BT, VT, CT} n_sums = sums isa AbstractArray && ndims(sums) > 1 ? size(sums, 1) : length(sums) n_counts = counts isa AbstractArray && ndims(counts) > 1 ? size(counts, 1) : length(counts) - ((length(distance) == n_sums + 1) && (n_sums == n_counts) && (size(sums) == size(counts))) || throw(DimensionMismatch("Flat distance edges must satisfy length(distance) == size(sums,1) + 1 and sums/counts must match shape (got edges=$(length(distance)), sums=$(size(sums)), counts=$(size(counts)))")) + ((_value_slots(distance) == n_sums) && (n_sums == n_counts) && (size(sums) == size(counts))) || throw(DimensionMismatch("Flat distance edges must satisfy length(distance) == size(sums,1) + 1 and sums/counts must match shape (got edges=$(length(distance)), sums=$(size(sums)), counts=$(size(counts)))")) FT = eltype(sums) return new{FT, OT, BT, VT, CT}(operator, distance, sums, counts) end @@ -148,6 +154,38 @@ struct StructureFunctionTensorSumsAndCounts{P, FT, BT, VT, CT} <: AbstractStruct end end +""" + StructureFunctionTensor2DSumsAndCounts(order, distance_bins, axis_bins, sums, counts) + +Raw tensor structure function joint in separation and a second axis: `sums` has shape +`(D, …, D, n_bins, n_axis)` with `P` component axes, `counts` `(n_bins, n_axis)`, `axis_bins` the +edges of the second axis. +""" +struct StructureFunctionTensor2DSumsAndCounts{P, FT, BT, AT, VT, CT} <: AbstractStructureFunction + order::Val{P} + distance_bins::BT + axis_bins::AT + sums::VT + counts::CT + + function StructureFunctionTensor2DSumsAndCounts( + order::Val{P}, distance_bins::BT, axis_bins::AT, sums::VT, counts::CT, + ) where {P, BT, AT, VT, CT} + P >= 1 || throw(ArgumentError("tensor order must be positive")) + ndims(sums) == P + 2 || throw(DimensionMismatch( + "joint tensor sums must have $P component axes, a distance-bin axis and a second-axis axis", + )) + n_bins, n_axis = size(sums, P + 1), size(sums, P + 2) + length(distance_bins) == n_bins + 1 || + throw(DimensionMismatch("distance_bins must have length size(sums, $(P + 1)) + 1")) + length(axis_bins) == n_axis + 1 || + throw(DimensionMismatch("axis_bins must have length size(sums, $(P + 2)) + 1")) + size(counts) == (n_bins, n_axis) || + throw(DimensionMismatch("counts must be ($n_bins, $n_axis); got $(size(counts))")) + return new{P, eltype(sums), BT, AT, VT, CT}(order, distance_bins, axis_bins, sums, counts) + end +end + """ StructureFunctionTensor(order, distance_bins, values) @@ -284,10 +322,6 @@ Base.firstindex(sf::StructureFunction) = firstindex(sf.values) Base.lastindex(sf::StructureFunction) = lastindex(sf.values) Base.iterate(sf::StructureFunction, args...) = iterate(sf.values, args...) -# For SumsAndCounts, we don't necessarily want to treat it as a single array, -# but getindex could perhaps return (sum, count) tuple? No, let's keep it explicit for now. -# Or better, just update the tests. - function Base.show(io::IO, sf::StructureFunction{FT, OT}) where {FT, OT} print(io, "StructureFunction{", FT, "}") print(io, "(operator=", sf.operator, ", points=", length(sf), ")") diff --git a/src/StructureFunctionTypes.jl b/src/StructureFunctionTypes.jl index 3be25ee..1a4735a 100644 --- a/src/StructureFunctionTypes.jl +++ b/src/StructureFunctionTypes.jl @@ -1,11 +1,30 @@ module StructureFunctionTypes using LinearAlgebra: LinearAlgebra as LA +using StaticArrays: StaticArrays as SA using ..HelperFunctions: HelperFunctions as SFH -using ..Channels: Channels as CH +using ..MultiFields: MultiFields as MF +""" + AbstractStructureFunctionType + +The operator of a structure function: which statistic of a pair's increment is accumulated. +""" abstract type AbstractStructureFunctionType end + +""" + AbstractPairwiseStructureFunctionType + +An operator with a value on one pair, `sf(δu, r̂)`, that the pair loops, the gridded sweeps and the +transforms accumulate. +""" abstract type AbstractPairwiseStructureFunctionType <: AbstractStructureFunctionType end + +""" + AbstractDerivedStructureFunctionType + +A quantity derived from binned structure functions, with no value on one pair. +""" abstract type AbstractDerivedStructureFunctionType <: AbstractStructureFunctionType end # Identity call: allows `SFType()` for singleton operator instances. @@ -36,17 +55,36 @@ end # --------------------------------------------------------------------------- """ - ProjectedStructureFunctionType{NL,NT} + ProjectedStructureFunctionType{NL, NT}(basis = CanonicalTransverseBasis()) -Parametric type representing structure function operators -with **longitudinal (`NL`)** and **transverse (`NT`)** contributions. +Operator `δu_L^NL · δu_T^NT`: `NL` powers of the longitudinal increment `δu·r̂` and `NT` of the +transverse one. `NT = 2` is the invariant transverse energy `‖δu‖² − δu_L²`; every other `NT` is the +signed component along the first vector of `transverse_basis(basis, r̂)`, so the sign of an odd `NT` +is the convention's. [`SFH.CanonicalTransverseBasis`](@ref) is `n̂`, the turn about `ẑ`. The basis travels +with the operator into every result. + +The two readings differ only for `D ≥ 3`, where the transverse plane has more than one direction; in +2-D `‖δu_T‖² = (δu·n̂)²`. They cannot be unified: `‖δu_T‖^NT` is a polynomial in `δu` only for even +`NT`, since `‖δu_T‖² = ‖δu‖² − δu_L²` and an odd power needs the square root, so odd `NT` admits the +component reading alone. `NT = 2` is the energy because that is the quantity the second-order +relations are written in — the Helmholtz split and the `D_LL`/`D_TT` isotropy relations all take it. +[`TransverseComponentSecondOrderStructureFunctionType`](@ref) is the per-component form, +`‖δu_T‖²/(D−1)`. """ -struct ProjectedStructureFunctionType{NL, NT} <: AbstractPairwiseStructureFunctionType end +struct ProjectedStructureFunctionType{NL, NT, B <: SFH.AbstractTransverseBasisConvention} <: + AbstractPairwiseStructureFunctionType + basis::B +end + +"""Alias of [`ProjectedStructureFunctionType`](@ref).""" +const ProjectedStructureFunction = ProjectedStructureFunctionType -const ProjectedStructureFunction = ProjectedStructureFunctionType # Longhand alias for the type +ProjectedStructureFunctionType{NL, NT}( + basis::B = SFH.CanonicalTransverseBasis(), +) where {NL, NT, B <: SFH.AbstractTransverseBasisConvention} = ProjectedStructureFunctionType{NL, NT, B}(basis) -ProjectedStructureFunctionType(NL::Integer, NT::Integer) = - ProjectedStructureFunctionType{NL, NT}() +ProjectedStructureFunctionType(NL::Integer, NT::Integer, basis = SFH.CanonicalTransverseBasis()) = + ProjectedStructureFunctionType{NL, NT}(basis) """ (sf::ProjectedStructureFunctionType{NL,NT})(δu, r̂) @@ -70,24 +108,20 @@ Compute the structure function kernel for longitudinal/transverse components. end end - # Transverse contribution + # Transverse contribution: NT = 2 is the invariant energy; any other NT is the signed component + # along the operator's basis. if !iszero(NT) if NT == 2 - # fast path: invariant transverse energy, no basis and no sqrt ex = :($ex * SFH.transverse_norm2(δu, r̂)) - elseif NT == 3 - # standard magnitude cubed (precomputed scalar), avoids fractional exponent - ex = :($ex * (SFH.mδu_t(δu, r̂)^3)) elseif NT == 1 - ex = :($ex * SFH.mδu_t(δu, r̂)) + ex = :($ex * SFH.mδu_t(δu, r̂, sf.basis)) else - # generic path: use scalar magnitude raised to NT (for uncommon powers) - ex = :($ex * (SFH.mδu_t(δu, r̂)^$NT)) + ex = :($ex * (SFH.mδu_t(δu, r̂, sf.basis)^$NT)) end end return quote - δu = SFC_channel_vector(δu_in, 1) + δu = SFC_field_vector(δu_in, 1) $ex end end @@ -112,25 +146,42 @@ struct ThirdOrderStructureFunctionType <: AbstractPairwiseStructureFunctionType """ FullVectorStructureFunctionType{NF} -Generic full-vector norm-power operator, ``||δu||^NF``. This is not used for -`S3SF`, whose conventional definition is [`ThirdOrderStructureFunctionType`](@ref). +Generic full-vector norm-power operator, ``||δu||^NF``. `S3SF`'s conventional definition is +[`ThirdOrderStructureFunctionType`](@ref). """ struct FullVectorStructureFunctionType{NF} <: AbstractPairwiseStructureFunctionType end +""" + MomentTensorOperator{P}() + +The transform engine's request for the whole rank-`P` increment moment tensor +`M[i₁, …, i_P] = Σ_pairs Π_k δu[i_k]` of a field's vector field, in place of one scalar contraction +of it. It has no value on a single pair. In a fixed Cartesian frame an odd rank changes sign when a +pair is read from its other end, exactly as an odd scalar increment does, so it takes the same +canonical pair reading; in a pair's own geodesic frame the components are read the same from either +end and no reading enters. +""" +struct MomentTensorOperator{P} <: AbstractPairwiseStructureFunctionType end + +(::MomentTensorOperator)(δu, r̂) = throw(ArgumentError( + "the moment tensor operator has no value on one pair; it names the whole increment moment tensor for the transform engine", +)) + +"""Alias of [`FullVectorStructureFunctionType`](@ref).""" const FullVectorStructureFunction = FullVectorStructureFunctionType FullVectorStructureFunctionType(NF::Integer) = FullVectorStructureFunctionType{NF}() -@inline (::SecondOrderStructureFunctionType)(δu, r̂) = norm2(SFC_channel_vector(δu, 1)) +@inline (::SecondOrderStructureFunctionType)(δu, r̂) = norm2(SFC_field_vector(δu, 1)) @inline function (::ThirdOrderStructureFunctionType)(δu, r̂) - v = SFC_channel_vector(δu, 1) + v = SFC_field_vector(δu, 1) return SFH.mδu_l(v, r̂) * norm2(v) end @generated function (::FullVectorStructureFunctionType{NF})(δu, r̂) where {NF} - NF == 2 && return :(norm2(SFC_channel_vector(δu, 1))) - return :(LA.norm(SFC_channel_vector(δu, 1))^$NF) + NF == 2 && return :(norm2(SFC_field_vector(δu, 1))) + return :(LA.norm(SFC_field_vector(δu, 1))^$NF) end """ @@ -151,72 +202,100 @@ Per-component variant of `L1T2SF`, struct LongitudinalTransverseComponentThirdOrderStructureFunctionType <: AbstractPairwiseStructureFunctionType end @inline (::TransverseComponentSecondOrderStructureFunctionType)(δu, r̂) = - SFH.transverse_component_norm2(SFC_channel_vector(δu, 1), r̂) + SFH.transverse_component_norm2(SFC_field_vector(δu, 1), r̂) @inline function (::LongitudinalTransverseComponentThirdOrderStructureFunctionType)(δu, r̂) - v = SFC_channel_vector(δu, 1) + v = SFC_field_vector(δu, 1) return SFH.mδu_l(v, r̂) * SFH.transverse_component_norm2(v, r̂) end # --------------------------------------------------------------------------- # Named Constants: Type Aliases (longhand and shorthands) -# 2nd order Type Aliases +"""`ProjectedStructureFunctionType{2, 0}`: the longitudinal second-order structure function ``⟨δu_L²⟩``.""" const LongitudinalSecondOrderStructureFunctionType = ProjectedStructureFunctionType{2, 0} +"""`ProjectedStructureFunctionType{0, 2}`: the transverse second-order structure function ``⟨‖δu_T‖²⟩ = ⟨‖δu‖² − δu_L²⟩``.""" const TransverseSecondOrderStructureFunctionType = ProjectedStructureFunctionType{0, 2} +"""Shorthand for [`TransverseComponentSecondOrderStructureFunctionType`](@ref).""" const T2ComponentSFType = TransverseComponentSecondOrderStructureFunctionType -# 3rd order Type Aliases +"""`ProjectedStructureFunctionType{3, 0}`: the longitudinal third-order structure function ``⟨δu_L³⟩``.""" const DiagonalConsistentThirdOrderStructureFunctionType = ProjectedStructureFunctionType{3, 0} +"""`ProjectedStructureFunctionType{2, 1}`: ``⟨δu_L² δu_T⟩`` with the signed transverse component of the operator's basis.""" const DiagonalInconsistentThirdOrderStructureFunctionType = ProjectedStructureFunctionType{2, 1} +"""`ProjectedStructureFunctionType{1, 2}`: ``⟨δu_L ‖δu_T‖²⟩``.""" const OffDiagonalInconsistentThirdOrderStructureFunctionType = ProjectedStructureFunctionType{1, 2} +"""`ProjectedStructureFunctionType{0, 3}`: ``⟨δu_T³⟩`` with the signed transverse component of the operator's basis.""" const OffDiagonalConsistentThirdOrderStructureFunctionType = ProjectedStructureFunctionType{0, 3} -# Shorthand Type Aliases +"""Shorthand for [`SecondOrderStructureFunctionType`](@ref), ``⟨‖δu‖²⟩``.""" const S2SFType = SecondOrderStructureFunctionType +"""Shorthand for [`LongitudinalSecondOrderStructureFunctionType`](@ref), ``⟨δu_L²⟩``.""" const L2SFType = LongitudinalSecondOrderStructureFunctionType +"""Shorthand for [`TransverseSecondOrderStructureFunctionType`](@ref), ``⟨‖δu_T‖²⟩``.""" const T2SFType = TransverseSecondOrderStructureFunctionType +"""Shorthand for [`ThirdOrderStructureFunctionType`](@ref), ``⟨δu_L ‖δu‖²⟩``.""" const S3SFType = ThirdOrderStructureFunctionType +"""Shorthand for [`DiagonalConsistentThirdOrderStructureFunctionType`](@ref), ``⟨δu_L³⟩``.""" const L3SFType = DiagonalConsistentThirdOrderStructureFunctionType +"""Shorthand for [`OffDiagonalConsistentThirdOrderStructureFunctionType`](@ref), ``⟨δu_T³⟩``.""" const T3SFType = OffDiagonalConsistentThirdOrderStructureFunctionType +"""Shorthand for [`DiagonalInconsistentThirdOrderStructureFunctionType`](@ref), ``⟨δu_L² δu_T⟩``.""" const L2T1SFType = DiagonalInconsistentThirdOrderStructureFunctionType +"""Shorthand for [`OffDiagonalInconsistentThirdOrderStructureFunctionType`](@ref), ``⟨δu_L ‖δu_T‖²⟩``.""" const L1T2SFType = OffDiagonalInconsistentThirdOrderStructureFunctionType +"""Shorthand for [`LongitudinalTransverseComponentThirdOrderStructureFunctionType`](@ref).""" const L1T2ComponentSFType = LongitudinalTransverseComponentThirdOrderStructureFunctionType # --------------------------------------------------------------------------- # Named Constants: Singleton Functors (The "Longhand" names now point to instances) -# 2nd order Singleton Functors +"""The instance `SecondOrderStructureFunctionType()`.""" const SecondOrderStructureFunction = SecondOrderStructureFunctionType() +"""The instance `LongitudinalSecondOrderStructureFunctionType()`.""" const LongitudinalSecondOrderStructureFunction = LongitudinalSecondOrderStructureFunctionType() +"""The instance `TransverseSecondOrderStructureFunctionType()`.""" const TransverseSecondOrderStructureFunction = TransverseSecondOrderStructureFunctionType() +"""The instance `TransverseComponentSecondOrderStructureFunctionType()`.""" const T2ComponentSF = TransverseComponentSecondOrderStructureFunctionType() -# 3rd order Singleton Functors +"""The instance `ThirdOrderStructureFunctionType()`.""" const ThirdOrderStructureFunction = ThirdOrderStructureFunctionType() +"""The instance `DiagonalConsistentThirdOrderStructureFunctionType()`.""" const DiagonalConsistentThirdOrderStructureFunction = DiagonalConsistentThirdOrderStructureFunctionType() +"""The instance `DiagonalInconsistentThirdOrderStructureFunctionType()`.""" const DiagonalInconsistentThirdOrderStructureFunction = DiagonalInconsistentThirdOrderStructureFunctionType() +"""The instance `OffDiagonalInconsistentThirdOrderStructureFunctionType()`.""" const OffDiagonalInconsistentThirdOrderStructureFunction = OffDiagonalInconsistentThirdOrderStructureFunctionType() +"""The instance `OffDiagonalConsistentThirdOrderStructureFunctionType()`.""" const OffDiagonalConsistentThirdOrderStructureFunction = OffDiagonalConsistentThirdOrderStructureFunctionType() +"""The instance `LongitudinalTransverseComponentThirdOrderStructureFunctionType()`.""" const L1T2ComponentSF = LongitudinalTransverseComponentThirdOrderStructureFunctionType() -# Shorthand Singleton Functors +"""The instance `S2SFType()`.""" const S2SF = SecondOrderStructureFunction +"""The instance `L2SFType()`.""" const L2SF = LongitudinalSecondOrderStructureFunction +"""The instance `T2SFType()`.""" const T2SF = TransverseSecondOrderStructureFunction +"""The instance `S3SFType()`.""" const S3SF = ThirdOrderStructureFunction +"""The instance `L3SFType()`.""" const L3SF = DiagonalConsistentThirdOrderStructureFunction +"""The instance `T3SFType()`.""" const T3SF = OffDiagonalConsistentThirdOrderStructureFunction +"""The instance `L2T1SFType()`.""" const L2T1SF = DiagonalInconsistentThirdOrderStructureFunction +"""The instance `L1T2SFType()`.""" const L1T2SF = OffDiagonalInconsistentThirdOrderStructureFunction # --------------------------------------------------------------------------- @@ -256,42 +335,44 @@ end end """ - ScalarStructureFunctionType{P}(channel = 1) + ScalarStructureFunctionType{P}(field = 1) -``⟨(δθ)^P⟩`` on scalar `channel` — the scalar structure function. `P = 2` is the Obukhov–Corrsin +``⟨(δθ)^P⟩`` on scalar `field` — the scalar structure function. `P = 2` is the Obukhov–Corrsin quantity; odd `P` measures the skewness of the tracer increment. """ struct ScalarStructureFunctionType{P} <: AbstractPairwiseStructureFunctionType - channel::Int + field::Int end ScalarStructureFunctionType{P}() where {P} = ScalarStructureFunctionType{P}(1) +"""Shorthand for [`ScalarStructureFunctionType`](@ref).""" const ScalarSFType = ScalarStructureFunctionType @inline (sf::ScalarStructureFunctionType{P})(δu, r̂) where {P} = - SFC_channel_scalar(δu, sf.channel)^P + SFC_field_scalar(δu, sf.field)^P """ - MixedStructureFunctionType{NL, NT, P}(vector_channel = 1, scalar_channel = 1) + MixedStructureFunctionType{NL, NT, P}(vector_field = 1, scalar_field = 1) ``⟨δu_L^{NL} ‖δu_T‖^{NT} (δθ)^P⟩`` — a velocity–scalar mixed moment. `{1, 0, 2}` is Yaglom's law, ``⟨δu_L (δθ)²⟩ = −(4/3) ε_θ r``; `{1, 0, 1}` is the flux of the tracer -itself. The velocity part is read from a transported vector channel and the scalar part from a -differenced scalar channel, so the two never mix frames. +itself. The velocity part is read from a transported vector field and the scalar part from a +differenced scalar field, so the two never mix frames. """ struct MixedStructureFunctionType{NL, NT, P} <: AbstractPairwiseStructureFunctionType - vector_channel::Int - scalar_channel::Int + vector_field::Int + scalar_field::Int end MixedStructureFunctionType{NL, NT, P}() where {NL, NT, P} = MixedStructureFunctionType{NL, NT, P}(1, 1) +"""Shorthand for [`MixedStructureFunctionType`](@ref).""" const MixedSFType = MixedStructureFunctionType @inline function (sf::MixedStructureFunctionType{NL, NT, P})(δu, r̂) where {NL, NT, P} - v = SFC_channel_vector(δu, sf.vector_channel) - θ = SFC_channel_scalar(δu, sf.scalar_channel) + v = SFC_field_vector(δu, sf.vector_field) + θ = SFC_field_scalar(δu, sf.scalar_field) l = SFH.mδu_l(v, r̂) t2 = SFH.transverse_norm2(v, r̂) return l^NL * sqrt(t2)^NT * θ^P @@ -300,10 +381,10 @@ end """ ScalarDotStructureFunctionType(a, b) -``⟨δθ^{(a)} δθ^{(b)}⟩`` — a second-order **cross-channel** scalar moment. +``⟨δθ^{(a)} δθ^{(b)}⟩`` — a second-order **cross-field** scalar moment. `(1, 1)` is the scalar structure function. `(a, b)` with `a ≠ b` is what an advective structure -function is: `⟨δω δ𝓐_ω⟩` is this with `ω` and its advection as the two channels. +function is: `⟨δω δ𝓐_ω⟩` is this with `ω` and its advection as the two fields. """ struct ScalarDotStructureFunctionType <: AbstractPairwiseStructureFunctionType a::Int @@ -313,12 +394,12 @@ end const ScalarDotSFType = ScalarDotStructureFunctionType @inline (sf::ScalarDotStructureFunctionType)(δu, r̂) = - SFC_channel_scalar(δu, sf.a) * SFC_channel_scalar(δu, sf.b) + SFC_field_scalar(δu, sf.a) * SFC_field_scalar(δu, sf.b) """ VectorDotStructureFunctionType(a, b) -``⟨δu^{(a)} · δu^{(b)}⟩`` — a second-order **cross-channel** vector moment. +``⟨δu^{(a)} · δu^{(b)}⟩`` — a second-order **cross-field** vector moment. `(1, 1)` **is** `S2SF`: the existing second-order operator is this one's diagonal, not a separate thing. `(a, b)` with `a ≠ b` is `⟨δu · δ𝓐_u⟩`, the advective structure function, which holds without @@ -332,47 +413,45 @@ end const VectorDotSFType = VectorDotStructureFunctionType @inline (sf::VectorDotStructureFunctionType)(δu, r̂) = - LA.dot(SFC_channel_vector(δu, sf.a), SFC_channel_vector(δu, sf.b)) + LA.dot(SFC_field_vector(δu, sf.a), SFC_field_vector(δu, sf.b)) -# How an operator reaches a channel of an increment. A single-channel field's increment is the plain -# vector every existing operator takes, so naming channel 1 of it is the vector itself — that is what +# How an operator reaches a field of an increment. A single-field increment is the plain +# vector every existing operator takes, so naming field 1 of it is the vector itself — that is what # keeps `Fields(vectors = (u,))` identical to a bare `u`. -@inline SFC_channel_vector(δu::CH.ChannelIncrement{D, 0, K}, i::Integer) where {D, K} = +@inline SFC_field_vector(δu::MF.FieldIncrement{D, 0, K}, i::Integer) where {D, K} = throw(ArgumentError( - "this field carries no vector channels, so a velocity operator has nothing to read. Build " * + "this field carries no vector fields, so a velocity operator has nothing to read. Build " * "it with Fields(vectors = (...), ...), or use a scalar operator.", )) -@inline SFC_channel_vector(δu::CH.ChannelIncrement, i::Integer) = CH.vector_channel(δu, i) -@inline function SFC_channel_vector(δu, i::Integer) +@inline SFC_field_vector(δu::MF.FieldIncrement, i::Integer) = MF.vector_field(δu, i) +@inline function SFC_field_vector(δu, i::Integer) i == 1 || throw(ArgumentError( - "this field has one vector channel; asked for channel $i. Build the field with " * + "this field has one vector field; asked for field $i. Build the field with " * "Fields(vectors = (...), ...) to carry more.", )) return δu end -@inline SFC_channel_scalar(δu::CH.ChannelIncrement, i::Integer) = CH.scalar_channel(δu, i) -@inline SFC_channel_scalar(δu, i::Integer) = throw(ArgumentError( - "this field carries no scalar channels; asked for scalar channel $i. Build the field with " * +@inline SFC_field_scalar(δu::MF.FieldIncrement, i::Integer) = MF.scalar_field(δu, i) +@inline SFC_field_scalar(δu, i::Integer) = throw(ArgumentError( + "this field carries no scalar fields; asked for scalar field $i. Build the field with " * "Fields(scalars = (...), ...) to carry one.", )) """ RotationalSecondOrderStructureFunctionType() -Helmholtz-derived 2D rotational second-order component. This is not a -pairwise operator; compute it from binned `L2SF`/`T2SF` with -`helmholtz_decompose_2d`. +Helmholtz-derived 2D rotational second-order component. A derived quantity, computed from binned +`L2SF`/`T2SF` with `helmholtz_decompose_2d`. """ struct RotationalSecondOrderStructureFunctionType <: AbstractDerivedStructureFunctionType end """ DivergentSecondOrderStructureFunctionType() -Helmholtz-derived 2D divergent second-order component. This is not a -pairwise operator; compute it from binned `L2SF`/`T2SF` with -`helmholtz_decompose_2d`. +Helmholtz-derived 2D divergent second-order component. A derived quantity, computed from binned +`L2SF`/`T2SF` with `helmholtz_decompose_2d`. """ struct DivergentSecondOrderStructureFunctionType <: AbstractDerivedStructureFunctionType end @@ -384,8 +463,11 @@ rotational and divergent second-order components. """ struct HelmholtzDecomposition2DType <: AbstractDerivedStructureFunctionType end +"""The instance `RotationalSecondOrderStructureFunctionType()`.""" const RotationalSecondOrderStructureFunction = RotationalSecondOrderStructureFunctionType() +"""The instance `DivergentSecondOrderStructureFunctionType()`.""" const DivergentSecondOrderStructureFunction = DivergentSecondOrderStructureFunctionType() +"""The instance `HelmholtzDecomposition2DType()`.""" const HelmholtzDecomposition2DOperator = HelmholtzDecomposition2DType() # --------------------------------------------------------------------------- @@ -443,7 +525,6 @@ export AbstractStructureFunctionType, SecondOrderStructureFunction, LongitudinalSecondOrderStructureFunction, TransverseSecondOrderStructureFunction, - T2ComponentSF, RotationalSecondOrderStructureFunction, DivergentSecondOrderStructureFunction, HelmholtzDecomposition2DOperator, @@ -452,10 +533,12 @@ export AbstractStructureFunctionType, DiagonalInconsistentThirdOrderStructureFunction, OffDiagonalInconsistentThirdOrderStructureFunction, OffDiagonalConsistentThirdOrderStructureFunction, - L1T2ComponentSF, S2SF, L2SF, T2SF, S3SF, L3SF, T3SF, L2T1SF, L1T2SF, T2ComponentSF, L1T2ComponentSF, ProjectedStructureFunctionType, - FullVectorStructureFunctionType, + FullVectorStructureFunctionType, MomentTensorOperator, + ScalarStructureFunctionType, MixedStructureFunctionType, + ScalarDotStructureFunctionType, VectorDotStructureFunctionType, + ScalarSFType, MixedSFType, ScalarDotSFType, VectorDotSFType, ProjectedStructureFunction, FullVectorStructureFunction, get_structure_function_type @@ -537,5 +620,348 @@ order(::LongitudinalTransverseComponentThirdOrderStructureFunctionType) = 3 order(::RotationalSecondOrderStructureFunctionType) = 2 order(::DivergentSecondOrderStructureFunctionType) = 2 order(::HelmholtzDecomposition2DType) = 2 +order(::ScalarStructureFunctionType{P}) where {P} = P +order(::MixedStructureFunctionType{NL, NT, P}) where {NL, NT, P} = NL + NT + P +order(::MomentTensorOperator{P}) where {P} = P +order(::ScalarDotStructureFunctionType) = 2 +order(::VectorDotStructureFunctionType) = 2 + +""" + scalar_order(sf) -> Int + +The total power of scalar-field increments in `sf`. + +Reading a pair from its other end leaves every vector quantity unchanged — `δu`, `r̂` and `n̂` all +flip together — and negates each scalar increment, so `sf` changes sign under that reading exactly +when this is odd. Such an operator is evaluated with the pair read from the lower to the upper end +along the first coordinate that separates its two points (on a sphere: from south to north, and along +one parallel from west to east); where neither end comes first, the two readings are averaged and the +moment is zero. +""" +scalar_order(::AbstractStructureFunctionType) = 0 +scalar_order(::ScalarStructureFunctionType{P}) where {P} = P +scalar_order(::MixedStructureFunctionType{NL, NT, P}) where {NL, NT, P} = P +scalar_order(::ScalarDotStructureFunctionType) = 2 + +"""Whether `sf` changes sign when a pair is read from its other end.""" +@inline is_odd_in_scalars(sf::AbstractStructureFunctionType) = isodd(scalar_order(sf)) +@inline is_odd_in_scalars(::MomentTensorOperator{P}) where {P} = isodd(P) + +# --------------------------------------------------------------------------- +# Polynomial contract: an operator as a contraction of the increment moment tensor +# --------------------------------------------------------------------------- + +""" + is_polynomial_operator(sf) -> Bool + +Whether `sf(δu, r̂)` is a homogeneous polynomial in the packed increment `δu` with coefficients that +depend only on `r̂`, so that `Σ_pairs sf(δu, r̂)` is [`moment_contract`](@ref) of the increment moment +tensor. +""" +@inline is_polynomial_operator(::AbstractStructureFunctionType) = false +@inline is_polynomial_operator(::SecondOrderStructureFunctionType) = true +@inline is_polynomial_operator(::ProjectedStructureFunctionType{NL, NT}) where {NL, NT} = NL + NT >= 1 +@inline is_polynomial_operator(::ThirdOrderStructureFunctionType) = true +@inline is_polynomial_operator(::FullVectorStructureFunctionType{NF}) where {NF} = NF >= 2 && iseven(NF) +@inline is_polynomial_operator(::TransverseComponentSecondOrderStructureFunctionType) = true +@inline is_polynomial_operator(::LongitudinalTransverseComponentThirdOrderStructureFunctionType) = true +@inline is_polynomial_operator(::ScalarStructureFunctionType{P}) where {P} = P >= 1 +@inline is_polynomial_operator(::MixedStructureFunctionType{NL, NT, P}) where {NL, NT, P} = + iseven(NT) && NL + NT + P >= 1 +@inline is_polynomial_operator(::ScalarDotStructureFunctionType) = true +@inline is_polynomial_operator(::VectorDotStructureFunctionType) = true +@inline is_polynomial_operator(::MomentTensorOperator) = true + +""" + SymmetricMoments{W, P}(data::SVector) + +The rank-`P` symmetric increment moment tensor over `W` packed components, stored as its +`binomial(W + P - 1, P)` independent entries `M[j₁ ≤ … ≤ j_P]` in the order of +[`symmetric_indices`](@ref). +""" +struct SymmetricMoments{W, P, N, T} + data::SA.SVector{N, T} + function SymmetricMoments{W, P}(data::SA.SVector{N, T}) where {W, P, N, T} + N == binomial(W + P - 1, P) || throw(DimensionMismatch( + "a rank-$P symmetric tensor over $W components has $(binomial(W + P - 1, P)) " * + "independent entries; got $N", + )) + return new{W, P, N, T}(data) + end +end + +Base.eltype(::SymmetricMoments{W, P, N, T}) where {W, P, N, T} = T + +""" + symmetric_indices(Val(W), Val(P)) -> NTuple{N, NTuple{P, Int}} + +The sorted multi-indices `j₁ ≤ … ≤ j_P` over `1:W` in storage order: entry `n` has +`n - 1 = Σ_k binomial(j_k + k - 2, k)`. +""" +@generated function symmetric_indices(::Val{W}, ::Val{P}) where {W, P} + combos = [c for c in Iterators.product(ntuple(_ -> 1:W, P)...) if issorted(c)] + sort!(combos; by = c -> sum(binomial(c[k] + k - 2, k) for k in 1:P)) + return Meta.quot(Tuple(combos)) +end + +# Storage position of a multi-index in any order: sort it, then rank the sorted tuple. +@generated function symmetric_rank(::Val{W}, ::Val{P}, idx::NTuple{P, Int}) where {W, P} + vars = [Symbol(:j, k) for k in 1:P] + ex = Expr[] + for k in 1:P + push!(ex, :($(vars[k]) = idx[$k])) + end + for k in 2:P, m in k:-1:2 + a, b = vars[m - 1], vars[m] + push!(ex, :(if $a > $b; $a, $b = $b, $a; end)) + end + terms = Expr[] + for k in 1:P + lut = ntuple(n -> binomial(n - 1, k), W + P) + push!(terms, :($(lut)[$(vars[k]) + $(k - 1)])) + end + push!(ex, :(return 1 + $(Expr(:call, :+, terms...)))) + return Expr(:block, ex...) +end + +""" + moment_contract(sf, M::SymmetricMoments, r̂, ::Val{V}, ::Val{K}) + +`Σ_pairs sf(δu, r̂)` from the increment moment tensor `M[i₁, …, i_p] = Σ_pairs Π_k δu[i_k]` of the +pairs sharing the unit separation `r̂`. `δu` is packed as `V` vector fields of width `D = length(r̂)` +followed by `K` scalar fields, so `M` has `W = V * D + K` components. Operators that are not +polynomials in `δu` have no method. +""" +function moment_contract(sf::AbstractStructureFunctionType, M, r̂, ::Val, ::Val) + throw(ArgumentError( + "$(typeof(sf)) is not a polynomial in the increment, so its pair average is not a " * + "contraction of an increment moment tensor. Omit the spectral backend for the lag sweep, " * + "which evaluates any pairwise operator exactly.", + )) +end + +@inline function _check_packed_width(::SymmetricMoments{W}, ::Val{D}, ::Val{V}, ::Val{K}) where {W, D, V, K} + W == V * D + K || throw(DimensionMismatch( + "the moment tensor has $W components but the field packs $V vector field(s) of width $D " * + "and $K scalar field(s), $(V * D + K) components", + )) + return nothing +end + +@inline _unit(::Val{W}, i::Integer, ::Type{T}) where {W, T} = + SA.SVector{W, T}(ntuple(j -> T(j == i), Val(W))) + +# `r̂` placed in vector field `a` of the packed layout, zero elsewhere. +@inline function _embed(::Val{W}, r̂::SA.SVector{D, T}, a::Integer) where {W, D, T} + off = (a - 1) * D + return SA.SVector{W, T}(ntuple(j -> off < j <= off + D ? r̂[j - off] : zero(T), Val(W))) +end + +# One literal each: a device kernel compiles a throw of a constant, never a formatted or joined string. +# The entry points name the field and the field's layout before any moment is contracted. +@inline function _require_vector_field(a::Integer, ::Val{V}) where {V} + 1 <= a <= V || throw(ArgumentError( + "the operator reads a vector field the field does not carry; build the field with Fields(vectors = (...), ...) or use a scalar operator", + )) + return nothing +end + +@inline function _require_scalar_field(k::Integer, ::Val{K}) where {K} + 1 <= k <= K || throw(ArgumentError( + "the operator reads a scalar field the field does not carry; build the field with Fields(scalars = (...), ...) to carry one", + )) + return nothing +end + +# Σ over every index tuple of M[i₁, …, i_p] · Π_k vs[k][i_k]. +@generated function _contract( + M::SymmetricMoments{W, P, N, TM}, vs::NTuple{P, SA.SVector{W}}, +) where {W, P, N, TM} + T = P == 0 ? TM : promote_type(TM, eltype(vs.parameters[1])) + idx = [Symbol(:i, k) for k in 1:P] + coeff = Expr(:call, :*, (:(vs[$k][$(idx[k])]) for k in 1:P)...) + body = :(acc += M.data[symmetric_rank(Val($W), Val($P), ($(idx...),))] * $coeff) + for k in P:-1:1 + body = :(for $(idx[k]) in 1:$W; $body; end) + end + return quote + acc = zero($T) + @inbounds $body + return acc + end +end + +@inline function _vector_dot(M::SymmetricMoments{W, 2}, a::Integer, b::Integer, ::Val{D}) where {W, D} + acc = zero(eltype(M)) + @inbounds for d in 1:D + acc += M.data[symmetric_rank(Val(W), Val(2), ((a - 1) * D + d, (b - 1) * D + d))] + end + return acc +end + +# `n` trailing slot pairs, each Σ_c e_c ⊗ e_c over the components of vector field `a`: ‖δu‖² per pair. +@inline _norm2_pairs(M, prefix::Tuple, ::Val{0}, a, ::Val{D}, ::Val{W}, ::Type{T}) where {D, W, T} = + _contract(M, prefix) +@inline function _norm2_pairs( + M, prefix::Tuple, ::Val{n}, a, ::Val{D}, ::Val{W}, ::Type{T}, +) where {n, D, W, T} + acc = zero(T) + for c in 1:D + e = _unit(Val(W), (a - 1) * D + c, T) + acc += _norm2_pairs(M, (prefix..., e, e), Val(n - 1), a, Val(D), Val(W), T) + end + return acc +end + +# `n` trailing slot pairs, each Σ_c e_c ⊗ e_c − rp ⊗ rp: ‖δu_T‖² per pair. +@inline _transverse_pairs( + M, prefix::Tuple, ::Val{0}, rp, a, ::Val{D}, ::Val{W}, ::Type{T}, +) where {D, W, T} = _contract(M, prefix) +@inline function _transverse_pairs( + M, prefix::Tuple, ::Val{n}, rp, a, ::Val{D}, ::Val{W}, ::Type{T}, +) where {n, D, W, T} + acc = zero(T) + for c in 1:D + e = _unit(Val(W), (a - 1) * D + c, T) + acc += _transverse_pairs(M, (prefix..., e, e), Val(n - 1), rp, a, Val(D), Val(W), T) + end + return acc - _transverse_pairs(M, (prefix..., rp, rp), Val(n - 1), rp, a, Val(D), Val(W), T) +end + +@inline function moment_contract( + ::SecondOrderStructureFunctionType, M::SymmetricMoments{W, 2}, r̂::SA.SVector{D}, ::Val{V}, ::Val{K}, +) where {W, D, V, K} + _check_packed_width(M, Val(D), Val(V), Val(K)) + _require_vector_field(1, Val(V)) + return _vector_dot(M, 1, 1, Val(D)) +end + +@generated function moment_contract( + sf::ProjectedStructureFunctionType{NL, NT}, M::SymmetricMoments{W, P, N, TM}, r̂::SA.SVector{D, TR}, + ::Val{V}, ::Val{K}, +) where {NL, NT, W, P, N, TM, D, TR, V, K} + NL + NT >= 1 || return :(throw(ArgumentError( + "ProjectedStructureFunctionType{0, 0} is the constant 1 and has no moment tensor", + ))) + T = promote_type(TM, TR) + rps = fill(:rp, NL) + if NT == 0 + core = :(_contract(M, ($(rps...),))) + frame = :(rp = _embed(Val($W), r̂, 1)) + elseif NT == 2 + core = :(_transverse_pairs(M, ($(rps...),), Val(1), rp, 1, Val($D), Val($W), $T)) + frame = :(rp = _embed(Val($W), r̂, 1)) + else + core = :(_contract(M, ($(rps...), $(fill(:np, NT)...)))) + frame = quote + rp = _embed(Val($W), r̂, 1) + np = _embed(Val($W), SFH.transverse_basis_vector(r̂, sf.basis), 1) + end + end + return quote + _check_packed_width(M, Val($D), Val($V), Val($K)) + _require_vector_field(1, Val($V)) + $frame + return $core + end +end + +@inline function moment_contract( + ::ThirdOrderStructureFunctionType, M::SymmetricMoments{W, 3}, r̂::SA.SVector{D, TR}, ::Val{V}, ::Val{K}, +) where {W, D, TR, V, K} + _check_packed_width(M, Val(D), Val(V), Val(K)) + _require_vector_field(1, Val(V)) + T = promote_type(eltype(M), TR) + rp = _embed(Val(W), r̂, 1) + return _norm2_pairs(M, (rp,), Val(1), 1, Val(D), Val(W), T) +end + +@generated function moment_contract( + ::FullVectorStructureFunctionType{NF}, M::SymmetricMoments{W, P, N, TM}, r̂::SA.SVector{D, TR}, + ::Val{V}, ::Val{K}, +) where {NF, W, P, N, TM, D, TR, V, K} + (NF >= 2 && iseven(NF)) || return :(throw(ArgumentError( + "FullVectorStructureFunctionType{$($NF)} is ‖δu‖^$($NF), an odd power of a norm and not a " * + "polynomial in the increment; the lag sweep evaluates it exactly.", + ))) + T = promote_type(TM, TR) + return quote + _check_packed_width(M, Val($D), Val($V), Val($K)) + _require_vector_field(1, Val($V)) + return _norm2_pairs(M, (), Val($(NF ÷ 2)), 1, Val($D), Val($W), $T) + end +end + +@inline function moment_contract( + ::TransverseComponentSecondOrderStructureFunctionType, M::SymmetricMoments, r̂::SA.SVector{D}, + ::Val{V}, ::Val{K}, +) where {D, V, K} + D > 1 || throw(ArgumentError( + "T2ComponentSF averages over the transverse directions, of which there are none at D = 1", + )) + return moment_contract(ProjectedStructureFunctionType{0, 2}(), M, r̂, Val(V), Val(K)) / (D - 1) +end + +@inline function moment_contract( + ::LongitudinalTransverseComponentThirdOrderStructureFunctionType, M::SymmetricMoments, + r̂::SA.SVector{D}, ::Val{V}, ::Val{K}, +) where {D, V, K} + D > 1 || throw(ArgumentError( + "L1T2ComponentSF averages over the transverse directions, of which there are none at D = 1", + )) + return moment_contract(ProjectedStructureFunctionType{1, 2}(), M, r̂, Val(V), Val(K)) / (D - 1) +end + +@inline function moment_contract( + sf::ScalarStructureFunctionType{P}, M::SymmetricMoments{W, P}, r̂::SA.SVector{D}, ::Val{V}, ::Val{K}, +) where {P, W, D, V, K} + _check_packed_width(M, Val(D), Val(V), Val(K)) + _require_scalar_field(sf.field, Val(K)) + s = V * D + sf.field + return @inbounds M.data[symmetric_rank(Val(W), Val(P), ntuple(_ -> s, Val(P)))] +end + +@generated function moment_contract( + sf::MixedStructureFunctionType{NL, NT, P}, M::SymmetricMoments{W, PM, N, TM}, r̂::SA.SVector{D, TR}, + ::Val{V}, ::Val{K}, +) where {NL, NT, P, W, PM, N, TM, D, TR, V, K} + iseven(NT) || return :(throw(ArgumentError( + "MixedStructureFunctionType{$($NL), $($NT), $($P)} raises ‖δu_T‖ to an odd power, which is " * + "not a polynomial in the increment; the lag sweep evaluates it exactly.", + ))) + NL + NT + P >= 1 || return :(throw(ArgumentError( + "MixedStructureFunctionType{0, 0, 0} is the constant 1 and has no moment tensor", + ))) + T = promote_type(TM, TR) + slots = vcat(fill(:rp, NL), fill(:es, P)) + return quote + _check_packed_width(M, Val($D), Val($V), Val($K)) + _require_vector_field(sf.vector_field, Val($V)) + _require_scalar_field(sf.scalar_field, Val($K)) + rp = _embed(Val($W), r̂, sf.vector_field) + es = _unit(Val($W), $V * $D + sf.scalar_field, $T) + return _transverse_pairs( + M, ($(slots...),), Val($(NT ÷ 2)), rp, sf.vector_field, Val($D), Val($W), $T, + ) + end +end + +@inline function moment_contract( + sf::ScalarDotStructureFunctionType, M::SymmetricMoments{W, 2}, r̂::SA.SVector{D}, ::Val{V}, ::Val{K}, +) where {W, D, V, K} + _check_packed_width(M, Val(D), Val(V), Val(K)) + _require_scalar_field(sf.a, Val(K)) + _require_scalar_field(sf.b, Val(K)) + return @inbounds M.data[symmetric_rank(Val(W), Val(2), (V * D + sf.a, V * D + sf.b))] +end + +@inline function moment_contract( + sf::VectorDotStructureFunctionType, M::SymmetricMoments{W, 2}, r̂::SA.SVector{D}, ::Val{V}, ::Val{K}, +) where {W, D, V, K} + _check_packed_width(M, Val(D), Val(V), Val(K)) + _require_vector_field(sf.a, Val(V)) + _require_vector_field(sf.b, Val(V)) + return _vector_dot(M, sf.a, sf.b, Val(D)) +end end # module diff --git a/src/StructureFunctions.jl b/src/StructureFunctions.jl index eea8957..d5a0a87 100644 --- a/src/StructureFunctions.jl +++ b/src/StructureFunctions.jl @@ -1,11 +1,10 @@ -module StructureFunctions # `using StructureFunctions`` should work `@everywhere` automatically... hopefully the methods and extensinos below follow... +module StructureFunctions using StaticArrays: StaticArrays as SA using PrecompileTools: PrecompileTools +using SpectralBackends: SpectralBackends -# using Distributed -# @everywhere include("ParallelCalculations.jl") # this works w/ include("src/StructureFunctions.jl") but not w/ using StructureFunctions, and the former dumps directly into Main... -include("Channels.jl") +include("MultiFields.jl") include("BinEdges.jl") include("HelperFunctions.jl") include("AuxiliaryAxes.jl") @@ -23,69 +22,23 @@ import .StructureFunctionObjects: StructureFunctionTensorSumsAndCounts, HelmholtzDecomposition2D -using .Channels -using .HelperFunctions -using .StructureFunctionTypes -using .StructureFunctionObjects -using .Calculations -using .KHM +using .MultiFields: MultiFields # what is a field +using .HelperFunctions: HelperFunctions +using .StructureFunctionTypes: StructureFunctionTypes +using .StructureFunctionObjects: StructureFunctionObjects +using .Calculations: Calculations +using .KHM: KHM -# Re-export key APIs -export Fields +# The package's own names. Everything else is reached through the submodule that owns it — +# `Calculations` for the entries, `StructureFunctionTypes` for the operators, `HelperFunctions` for +# the geometry, `MultiFields` for `Fields`. export AbstractBinEdges, BinEdges, LinearBinEdges, LogBinEdges, LogBinEdges_from_log_edges, - InfPaddedBinEdges, physical_edges_vector, n_histogram_bins -export calculate_structure_function, calculate_structure_function!, calculate_structure_functions_single_pass, - calculate_structure_functions_single_pass!, calculate_structure_functions_single_pass_2d, - calculate_structure_functions_single_pass_2d!, helmholtz_decompose_2d, - append_helmholtz_rotational_divergent_rows, - marginalize_sp2d_then_append_helmholtz_rows, - calculate_structure_function_tensor, calculate_structure_function_tensor!, - calculate_structure_function_batch!, calculate_structure_function_2d_batch!, - calculate_structure_functions_single_pass_batch!, calculate_structure_functions_single_pass_2d_batch!, - GPUSFWorkspace, CPUSFWorkspace, reset_histogram!, release!, - joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256 -export isotropic_spectrum, shell_spectrum, gridded_spectrum, shell_average, - helmholtz_spectra, spectral_flux, covariance, covariance_matrix -export marginalize -export AbstractStructureFunction, StructureFunction, StructureFunctionSumsAndCounts, StructureFunction2DSumsAndCounts -export StructureFunctionTensor, StructureFunctionTensorSumsAndCounts, HelmholtzDecomposition2D -export LongitudinalSecondOrderStructureFunctionType, - TransverseSecondOrderStructureFunctionType -export AbstractPairwiseStructureFunctionType, AbstractDerivedStructureFunctionType -export SecondOrderStructureFunctionType, ThirdOrderStructureFunctionType -export DiagonalConsistentThirdOrderStructureFunctionType, - DiagonalInconsistentThirdOrderStructureFunctionType -export OffDiagonalConsistentThirdOrderStructureFunctionType, - OffDiagonalInconsistentThirdOrderStructureFunctionType -export RotationalSecondOrderStructureFunctionType, DivergentSecondOrderStructureFunctionType, - HelmholtzDecomposition2DType -export L2SFType, T2SFType, L3SFType, S2SFType, S3SFType, T3SFType, L2T1SFType, L1T2SFType -export T2ComponentSFType, L1T2ComponentSFType - -export LongitudinalSecondOrderStructureFunction, TransverseSecondOrderStructureFunction -export SecondOrderStructureFunction, ThirdOrderStructureFunction -export DiagonalConsistentThirdOrderStructureFunction, - DiagonalInconsistentThirdOrderStructureFunction -export OffDiagonalConsistentThirdOrderStructureFunction, - OffDiagonalInconsistentThirdOrderStructureFunction -export L2SF, T2SF, L3SF, S2SF, S3SF, T3SF, L2T1SF, L1T2SF -export RotationalSecondOrderStructureFunction, DivergentSecondOrderStructureFunction, - HelmholtzDecomposition2DOperator -export T2ComponentSF, L1T2ComponentSF -export get_structure_function_type + InfPaddedBinEdges, ModeBinEdges, physical_edges_vector, n_histogram_bins, midpoints +export AbstractTaper, NoTaper, Bartlett, GaussianTaper, HarmonicNodes, gauss_legendre +export AbstractStructureFunction, StructureFunction, StructureFunctionSumsAndCounts, + StructureFunction2DSumsAndCounts, StructureFunctionTensor, StructureFunctionTensorSumsAndCounts, + HelmholtzDecomposition2D export KHM -export transverse_norm2, - transverse_component_norm2, - transverse_component, - transverse_basis, - transverse_basis_vector, - AbstractTransverseBasisConvention, - CanonicalTransverseBasis, - ReferenceAxisTransverseBasis, - CoordinateGaugeTransverseBasis, - UserTransverseBasis, - midpoints - # --------------------------------------------------------------------------- # Initialization & Precompilation diff --git a/src/precompile.jl b/src/precompile.jl index 0027838..4ebd683 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -6,16 +6,16 @@ PrecompileTools.@compile_workload begin for FT in FTs bins = [FT(0), FT(1), FT(2)] sfs = [ - LongitudinalSecondOrderStructureFunction, - TransverseSecondOrderStructureFunction, - DiagonalConsistentThirdOrderStructureFunction, + StructureFunctionTypes.LongitudinalSecondOrderStructureFunction, + StructureFunctionTypes.TransverseSecondOrderStructureFunction, + StructureFunctionTypes.DiagonalConsistentThirdOrderStructureFunction, ] for N in dims x_mat = zeros(FT, N, 3) u_mat = zeros(FT, N, 3) for sf in sfs - calculate_structure_function( + Calculations.calculate_structure_function( sf, x_mat, u_mat, diff --git a/test/Project.toml b/test/Project.toml index 4413e63..6af05a4 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,20 +1,24 @@ [deps] -Bessels = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" -FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" AbstractFFTs = "621f4979-c628-5d54-868e-fcf4e3e8185c" -ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" +Bessels = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" +FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" +FINUFFT = "d8beea63-0952-562e-9c6a-8e8ef7364055" FlowGeometries = "0ccd6995-f618-4175-b01e-f437d0cb4974" JET = "c3a54625-cd67-489e-a8e7-0a5a0ff4e31b" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +LsqFit = "2fda8390-95c7-5789-9bda-21331edee243" MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" +NUFSHT = "e99b67a3-9706-455a-90e2-85b195a33206" +NonuniformFFTs = "cd96f58b-6017-4a02-bb9e-f4d81626177f" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca" @@ -27,5 +31,6 @@ StructureFunctions = "e93fee26-4d5e-49c1-899d-490508cfd19b" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [sources] -FlowGeometries = { url = "https://github.com/jbphyswx/FlowGeometries.jl" } -SpectralBackends = { url = "https://github.com/jbphyswx/SpectralBackends.jl" } +FlowGeometries = {url = "https://github.com/jbphyswx/FlowGeometries.jl"} +NUFSHT = {url = "https://github.com/jbphyswx/NUFSHT.jl"} +SpectralBackends = {url = "https://github.com/jbphyswx/SpectralBackends.jl"} diff --git a/test/runtests.jl b/test/runtests.jl index ea452b7..841dbab 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -32,14 +32,37 @@ Test.@testset "StructureFunctions.jl" begin println("--- Running Gridded Masked Test ---") include("test_gridded_masked.jl") + println("--- Running Gridded Moments Test ---") + include("test_gridded_moments.jl") + println("--- Running Gridded Lat-Lon Test ---") include("test_gridded_zonal.jl") + println("--- Running Gridded Separable Schedules Test ---") + include("test_gridded_separable.jl") + println("--- Running Gridded Device Engine Test ---") + include("test_gridded_device.jl") + println("--- Running Pair Weights Test ---") + include("test_gridded_weights.jl") + println("--- Running Scattered Modes (NUFFT) Test ---") + include("test_scattered_modes.jl") + println("--- Running Sorted Line Route Test ---") + include("test_sorted_line.jl") + + println("--- Running Lag-Space Spectra Test ---") + include("test_spectra_lagspace.jl") + + println("--- Running Spherical Harmonic Route Test ---") + include("test_harmonic_sphere.jl") + println("--- Running Directional Test ---") include("test_directional.jl") - println("--- Running Multi-Channel Fields Test ---") - include("test_channels.jl") + println("--- Running Multi-Field Fields Test ---") + include("test_multifields.jl") + + println("--- Running Operator Polynomial Contract Test ---") + include("test_operator_contract.jl") println("--- Running Single-Pass & Helmholtz Test ---") include("test_single_pass.jl") @@ -77,6 +100,9 @@ Test.@testset "StructureFunctions.jl" begin println("--- Running Transforms Test ---") include("test_transforms.jl") + println("--- Running Regularised Fits Test ---") + include("test_fits.jl") + println("--- Running Triangle Outer Chunks Test ---") include("test_triangle_outer_chunks.jl") @@ -84,9 +110,6 @@ Test.@testset "StructureFunctions.jl" begin include("test_cpu_workspace.jl") - # println("--- Running Performance Benchmark Test ---") # This need not run all the time, but it's here for reference - # include("benchmark_performance.jl") - # Enable Parallel/Distributed Test println("--- Running Parallel Equivalence Test ---") include("test_parallel_equivalence.jl") diff --git a/test/test_batch_matrix.jl b/test/test_batch_matrix.jl index 81ba34f..6cf77f2 100644 --- a/test/test_batch_matrix.jl +++ b/test/test_batch_matrix.jl @@ -90,6 +90,33 @@ Test.@testset "batch matrix parity (KA.CPU)" begin @test batch_histograms_equal(gpu_s, gpu_c, cpu_s, cpu_c; atol = 1f-4) end + @testset "row2b signed transverse operators on the batch kernels" begin + for sft in (SFT.T3SFType(), SFT.L2T1SFType()) + x, u, lbe = _rand_batch_fixed(N, B) + NB = length(lbe.edges) - 1 + cpu_s = zeros(Float32, NB, B) + cpu_c = zeros(UInt32, NB, B) + auxiliary_shared_positions!(cpu_s, cpu_c, x, u, sft, lbe) + gpu_out = SFC.calculate_structure_function( + sft, x, u, lbe; + backend = GPU_BE, output_type = SF.StructureFunctionSumsAndCounts, verbose = false, + ) + @test batch_histograms_equal(gpu_out.sums, gpu_out.counts, cpu_s, cpu_c; atol = 1f-4) + @test any(!iszero, cpu_s) + + xv, uv, lbev = _rand_batch_varying(N, B) + NBv = length(lbev.edges) - 1 + cpu_sv = zeros(Float32, NBv, B) + cpu_cv = zeros(UInt32, NBv, B) + auxiliary_varying_positions!(cpu_sv, cpu_cv, xv, uv, sft, lbev) + gpu_sv = zeros(Float32, NBv, B) + gpu_cv = zeros(UInt32, NBv, B) + SFC.calculate_structure_function_batch!(gpu_sv, gpu_cv, sft, xv, uv, lbev; backend = GPU_BE) + @test batch_histograms_equal(gpu_sv, gpu_cv, cpu_sv, cpu_cv; atol = 1f-4) + @test any(!iszero, cpu_sv) + end + end + @testset "row3 SP1D fixed-x" begin x, u, lbe = _rand_batch_fixed(N, B) n_bins = length(lbe.edges) - 1 diff --git a/test/test_channels.jl b/test/test_channels.jl deleted file mode 100644 index fc889fd..0000000 --- a/test/test_channels.jl +++ /dev/null @@ -1,241 +0,0 @@ -using ComputationalBackends: ComputationalBackends as CB -using Test: Test -using StructureFunctions: StructureFunctions as SF, Calculations as SFC, - StructureFunctionTypes as SFT, Channels as CH -using StaticArrays: StaticArrays as SA -using LinearAlgebra: dot -using OhMyThreads: OhMyThreads -using Random: Random - -# Every pair, evaluated straight from the inputs. Independent of the packing and of the sweep. -function _brute(op, x, vectors, scalars, bins) - N = size(x, 2) - D = isempty(vectors) ? 0 : size(first(vectors), 1) - nb = length(bins) - 1 - sums = zeros(Float64, nb) - counts = zeros(Int, nb) - for i in 1:(N - 1), j in (i + 1):N - dx = SA.SVector{size(x, 1)}(x[:, j] - x[:, i]) - r = sqrt(dot(dx, dx)) - b = searchsortedfirst(bins, r) - 1 - 1 <= b <= nb || continue - rh = dx / r - dv = [SA.SVector{D}(v[:, j] - v[:, i]) for v in vectors] - ds = [s[j] - s[i] for s in scalars] - sums[b] += op(dv, ds, rh) - counts[b] += 1 - end - return sums, counts -end - -_run(op, x, f, bins) = SFC.calculate_structure_function( - op, x, f, bins, UInt32; output_type = SF.StructureFunctionSumsAndCounts, - verbose = false, show_progress = false) - -Test.@testset "a field of one vector channel is the array path" begin - # The adapter must be a no-op for what callers already pass: same kernel, same answer, bit for bit. - Random.seed!(1200) - x = rand(2, 80) - u = randn(2, 80) - bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal - for op in (SFT.L2SFType(), SFT.T2SFType(), SFT.S2SFType(), SFT.L3SFType()) - bare = SFC.calculate_structure_function(op, x, u, bins, UInt32; - output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) - bundled = _run(op, x, SF.Fields(vectors = (u,)), bins) - Test.@test bundled.counts == bare.counts - Test.@test bundled.sums == bare.sums # identical, not merely close - end - # and the packing itself copies nothing it need not - Test.@test CH.packed(SF.Fields(vectors = (u,))) == u -end - -Test.@testset "packing lays channels out as declared" begin - Random.seed!(1300) - u = randn(3, 6) - a = randn(3, 6) - th = randn(6) - ph = randn(6) - f = SF.Fields(vectors = (u, a), scalars = (th, ph)) - Test.@test CH.channel_dimension(f) == 3 - Test.@test CH.n_vector_channels(f) == 2 - Test.@test CH.n_scalar_channels(f) == 2 - d = CH.packed(f) - Test.@test size(d) == (3 * 2 + 2, 6) - Test.@test d[1:3, :] == u - Test.@test d[4:6, :] == a - Test.@test d[7, :] == th - Test.@test d[8, :] == ph -end - -Test.@testset "the bundle refuses what it cannot mean" begin - Test.@test_throws ArgumentError SF.Fields() - Test.@test_throws DimensionMismatch SF.Fields(vectors = (randn(2, 5), randn(3, 5))) - Test.@test_throws DimensionMismatch SF.Fields(vectors = (randn(2, 5),), scalars = (randn(4),)) - Test.@test_throws ArgumentError SF.Fields(vectors = (randn(2, 5, 2),)) -end - -Test.@testset "the scalar structure function matches brute force" begin - Random.seed!(1400) - N = 70 - x = rand(2, N) - th = randn(N) - bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal - f = SF.Fields(vectors = (randn(2, N),), scalars = (th,)) - for P in (2, 3) - got = _run(SFT.ScalarSFType{P}(), x, f, bins) - ref_s, ref_c = _brute((dv, ds, rh) -> ds[1]^P, x, (), (th,), bins) - Test.@test got.counts == ref_c - Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) - Test.@test sum(got.counts) == N * (N - 1) ÷ 2 - end -end - -Test.@testset "Yaglom's mixed moment matches brute force" begin - # ⟨δu_L (δθ)²⟩ — the velocity part read from a transported channel, the scalar part from a - # differenced one, so the two never share a frame by accident. - Random.seed!(1500) - N = 70 - x = rand(2, N) - u = randn(2, N) - th = randn(N) - bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal - f = SF.Fields(vectors = (u,), scalars = (th,)) - got = _run(SFT.MixedSFType{1, 0, 2}(), x, f, bins) - ref_s, ref_c = _brute((dv, ds, rh) -> dot(dv[1], rh) * ds[1]^2, x, (u,), (th,), bins) - Test.@test got.counts == ref_c - Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) - - # and the first-order flux of the tracer itself - got1 = _run(SFT.MixedSFType{1, 0, 1}(), x, f, bins) - ref1_s, _ = _brute((dv, ds, rh) -> dot(dv[1], rh) * ds[1], x, (u,), (th,), bins) - Test.@test isapprox(got1.sums, ref1_s; rtol = 1e-10, atol = 1e-12) -end - -Test.@testset "cross-channel moments are what an advective structure function is" begin - # ⟨δu · δ𝓐⟩ and ⟨δω δ𝓐_ω⟩ — second-order moments between two different channels. - Random.seed!(1600) - N = 60 - x = rand(2, N) - u = randn(2, N) - adv = randn(2, N) - w = randn(N) - advw = randn(N) - bins = collect(range(0.0, 1.3; length = 6)) - - fv = SF.Fields(vectors = (u, adv)) - got = _run(SFT.VectorDotSFType(1, 2), x, fv, bins) - ref_s, ref_c = _brute((dv, ds, rh) -> dot(dv[1], dv[2]), x, (u, adv), (), bins) - Test.@test got.counts == ref_c - Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) - - fs = SF.Fields(vectors = (u,), scalars = (w, advw)) - gots = _run(SFT.ScalarDotSFType(1, 2), x, fs, bins) - refs_s, _ = _brute((dv, ds, rh) -> ds[1] * ds[2], x, (u,), (w, advw), bins) - Test.@test isapprox(gots.sums, refs_s; rtol = 1e-10, atol = 1e-12) - - # the diagonal of the vector cross-moment IS the second-order structure function - diag = _run(SFT.VectorDotSFType(1, 1), x, fv, bins) - s2 = _run(SFT.S2SFType(), x, SF.Fields(vectors = (u,)), bins) - Test.@test diag.counts == s2.counts - Test.@test isapprox(diag.sums, s2.sums; rtol = 1e-12) -end - -Test.@testset "asking for a channel a field does not carry says so" begin - Random.seed!(1700) - x = rand(2, 20) - u = randn(2, 20) - bins = collect(range(0.0, 1.0; length = 4)) - # a plain velocity has no scalar channel - Test.@test_throws ArgumentError _run(SFT.ScalarSFType{2}(), x, SF.Fields(vectors = (u,)), bins) - # and only one vector channel - Test.@test_throws ArgumentError _run(SFT.VectorDotSFType(1, 2), x, SF.Fields(vectors = (u,)), bins) -end - -Test.@testset "channels are transported on a sphere, scalars are not" begin - # A vector channel is carried as an ambient 3-vector on a sphere, so a bundle must widen every - # vector channel exactly as the array path widens the one it has. A scalar has nothing to - # transport and passes through untouched. - Random.seed!(1800) - N = 50 - x = vcat(reshape(2π .* rand(N), 1, N), reshape((rand(N) .- 0.5) .* 1.4, 1, N)) - u = randn(2, N) - th = randn(N) - bins = collect(range(0.0, 2.4; length = 6)) - metric = SFC.DI.SphericalAngle() - - # one vector channel: the same kernel as the array path, so identical to the last bit - # Both pinned to the same backend: the claim is that the bundle takes the *same kernel*, and a - # different backend would differ in summation order alone, which would not test that. - bare_s = zeros(5); bare_c = zeros(UInt32, 5) - SF.calculate_structure_function!(bare_s, bare_c, SFT.L2SFType(), x, u, bins; - distance_metric = metric, backend = CB.SerialBackend()) - bundled = SFC.calculate_structure_function( - SFT.L2SFType(), x, SF.Fields(vectors = (u,)), bins, UInt32; distance_metric = metric, - backend = CB.SerialBackend(), - output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) - Test.@test bundled.counts == bare_c - Test.@test bundled.sums == bare_s - - # a scalar rides along without disturbing the velocity part: L2SF on the bundle must still equal - # L2SF on the velocity alone - with_tracer = SFC.calculate_structure_function( - SFT.L2SFType(), x, SF.Fields(vectors = (u,), scalars = (th,)), bins, UInt32; - distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, - verbose = false, show_progress = false) - Test.@test with_tracer.counts == bare_c - Test.@test isapprox(with_tracer.sums, bare_s; rtol = 1e-12) - - # the scalar structure function on a sphere: transport-free, so it is the plain difference - scalar_only = SFC.calculate_structure_function( - SFT.ScalarSFType{2}(), x, SF.Fields(scalars = (th,)), bins, UInt32; - distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, - verbose = false, show_progress = false) - ref_s = zeros(5); ref_c = zeros(Int, 5) - for i in 1:(N - 1), j in (i + 1):N - r = SFC.DI.SphericalAngle()(view(x, :, i), view(x, :, j)) - b = searchsortedfirst(bins, r) - 1 - 1 <= b <= 5 || continue - ref_s[b] += (th[j] - th[i])^2 - ref_c[b] += 1 - end - Test.@test scalar_only.counts == UInt32.(ref_c) - Test.@test isapprox(scalar_only.sums, ref_s; rtol = 1e-10, atol = 1e-12) - Test.@test sum(scalar_only.counts) > 0 - - # Yaglom on a sphere runs and stays finite; its velocity half is transported, so it is not the - # flat answer - yag = SFC.calculate_structure_function( - SFT.MixedSFType{1, 0, 2}(), x, SF.Fields(vectors = (u,), scalars = (th,)), bins, UInt32; - distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, - verbose = false, show_progress = false) - Test.@test all(isfinite, yag.sums) - Test.@test yag.counts == bare_c -end - -Test.@testset "the threaded backend gives the serial answer" begin - # Multi-channel across threads: the setup happens once above the task loop and each task sweeps - # its own outer indices, so the only thing that may differ from serial is summation order. - Random.seed!(1900) - N = 400 - x = rand(2, N) - u = randn(2, N) - adv = randn(2, N) - th = randn(N) - bins = collect(range(0.0, 1.5; length = 8)) # spans the unit square diagonal - nb = length(bins) - 1 - - for (f, op) in ((SF.Fields(vectors = (u,), scalars = (th,)), SFT.MixedSFType{1, 0, 2}()), - (SF.Fields(vectors = (u, adv)), SFT.VectorDotSFType(1, 2)), - (SF.Fields(vectors = (u,), scalars = (th,)), SFT.ScalarSFType{2}()), - (SF.Fields(vectors = (u,)), SFT.L2SFType())) - ser_s = zeros(nb); ser_c = zeros(Int, nb) - SFC.serial_calculate_structure_function!(ser_s, ser_c, op, x, f, bins; - verbose = false, show_progress = false) - thr_s = zeros(nb); thr_c = zeros(Int, nb) - SFC.threaded_calculate_structure_function!(thr_s, thr_c, op, x, f, bins; - verbose = false, show_progress = false) - Test.@test thr_c == ser_c - Test.@test isapprox(thr_s, ser_s; rtol = 1e-10, atol = 1e-12) - Test.@test sum(thr_c) == N * (N - 1) ÷ 2 - end -end diff --git a/test/test_core_correctness.jl b/test/test_core_correctness.jl index f0daba7..794fa5a 100644 --- a/test/test_core_correctness.jl +++ b/test/test_core_correctness.jl @@ -1,8 +1,11 @@ using StructureFunctions: - StructureFunctions as SF, StructureFunctionTypes as SFT, Calculations as SFC + StructureFunctions as SF, StructureFunctionTypes as SFT, Calculations as SFC, HelperFunctions as SFH using Test: Test using Random: Random using StaticArrays: StaticArrays as SA +using LinearAlgebra: LinearAlgebra as LA +using ComputationalBackends: ComputationalBackends as CB +using OhMyThreads: OhMyThreads Test.@testset "Core Correctness - Block A" begin Test.@testset "Blocked path regression" begin @@ -177,6 +180,42 @@ Test.@testset "Core Correctness - Block A" begin end end +Test.@testset "a projected operator's convention decides its signed transverse component through the entry" begin + Random.seed!(1103) + N = 60 + x = randn(3, N) + u = randn(3, N) + bins = [0.0, 100.0] + conventions = (SFH.CanonicalTransverseBasis(), + SFH.ReferenceAxisTransverseBasis(LA.normalize(SA.SVector(1.0, sqrt(2.0), sqrt(3.0))))) + for (NL, NT) in ((0, 3), (2, 1)) + by_basis = Float64[] + for basis in conventions + sf = SFT.ProjectedStructureFunctionType{NL, NT}(basis) + expected = 0.0 + for i in 1:(N - 1), j in (i + 1):N + dx = SA.SVector{3}(x[1, j] - x[1, i], x[2, j] - x[2, i], x[3, j] - x[3, i]) + r̂ = dx / LA.norm(dx) + δu = SA.SVector{3}(u[1, j] - u[1, i], u[2, j] - u[2, i], u[3, j] - u[3, i]) + e = SFH.transverse_basis(basis, r̂)[1] + expected += LA.dot(δu, r̂)^NL * LA.dot(δu, e)^NT + end + for backend in (CB.SerialBackend(), CB.ThreadedBackend()) + res = SFC.calculate_structure_function( + sf, x, u, bins; + backend, verbose = false, show_progress = false, + output_type = SF.StructureFunctionSumsAndCounts, + ) + Test.@test res.counts == [N * (N - 1) ÷ 2] + Test.@test res.sums[1] ≈ expected rtol = 1e-12 + Test.@test res.operator.basis === basis + end + push!(by_basis, expected) + end + Test.@test !(by_basis[1] ≈ by_basis[2]) + end +end + Test.@testset "Type Stability and Performance - Block C" begin x = [0.0 1.0 2.0; 0.0 0.0 0.0] u = [1.0 2.0 3.0; 0.0 0.0 0.0] diff --git a/test/test_cpu_pair_blocking.jl b/test/test_cpu_pair_blocking.jl index d26512d..67c05e4 100644 --- a/test/test_cpu_pair_blocking.jl +++ b/test/test_cpu_pair_blocking.jl @@ -12,7 +12,7 @@ function _run_blocks(sf, xc, uc, bins, ::Val{D}, blocks, N, ::Type{FT}) where {D nb = SFC.n_histogram_bins(plan) s = zeros(FT, nb); c = zeros(UInt32, nb) SFC._pf_simd_pairs!(s, c, sf, xc, uc, plan, Val(D), - Vector{FT}(undef, N), Vector{FT}(undef, N), Vector{Int32}(undef, N), blocks) + Vector{FT}(undef, N), Vector{FT}(undef, N), Vector{Int32}(undef, N), blocks, SFC.NoWeights()) return s, c end @@ -126,7 +126,7 @@ Test.@testset "culling policy" begin Test.@test SFC.cull_grid_for(xc, g, tight, SFC.NoCulling()) === nothing Test.@test SFC.cull_grid_for(xc, g, tight, SFC.AutoCulling()) !== nothing - # a cutoff spanning the grid removes no pairs, so :auto declines rather than pay for the sort + # a cutoff spanning the grid removes no pairs, so :auto declines and pays for no sort Test.@test SFC.cull_grid_for(xc, g, wide, SFC.AutoCulling()) === nothing Test.@test SFC.cull_grid_for(xc, g, wide, SFC.AlwaysCulling()) !== nothing @@ -242,7 +242,7 @@ Test.@testset "2D kernels are invariant to the block schedule" begin # single-pass 2D vb = ntuple(_ -> val, SFC.SINGLE_PASS_N) # h is (sum/count, invariant, value bin, distance bin) — the kernel scatters with - # @inbounds, so a wrong shape here corrupts the heap instead of erroring. + # @inbounds, so a wrong shape here corrupts the heap and never errors. sp2d(pol) = begin h = zeros(FT, 2, SFC.SINGLE_PASS_N, n_val, n_dist) SFC._sp2d_simd_partial!(h, x, u, dist, vb, Val(D), n_val, 1:(N - 1), pol) diff --git a/test/test_cpu_workspace.jl b/test/test_cpu_workspace.jl index 3fc2a0d..fca6079 100644 --- a/test/test_cpu_workspace.jl +++ b/test/test_cpu_workspace.jl @@ -1,7 +1,7 @@ using Test using Random: Random -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, - LinearBinEdges, CPUSFWorkspace, reset_histogram! +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, LinearBinEdges +using StructureFunctions.Calculations: CPUSFWorkspace, reset_histogram! using ComputationalBackends: ComputationalBackends as CB using OhMyThreads: OhMyThreads diff --git a/test/test_directional.jl b/test/test_directional.jl index 79e9668..e4167b3 100644 --- a/test/test_directional.jl +++ b/test/test_directional.jl @@ -62,7 +62,7 @@ Test.@testset "marginalizing the angle recovers the plain structure function" be nb = length(dist_bins) - 1 ref_s = zeros(Float64, nb) ref_c = zeros(UInt32, nb) - SF.calculate_structure_function!(ref_s, ref_c, SF2, x, u, dist_bins; + SFC.calculate_structure_function!(ref_s, ref_c, SF2, x, u, dist_bins; backend = CB.SerialBackend()) Test.@test vec(sum(joint.counts; dims = 2)) == ref_c Test.@test isapprox(vec(sum(joint.sums; dims = 2)), ref_s; rtol = 1e-10, atol = 1e-12) @@ -119,7 +119,7 @@ end Test.@testset "an angle axis is refused where the direction is not shared" begin # On a sphere each pair's direction lives in its own frame, so an angle to one fixed reference - # axis is not a property of the pair. Refused by name rather than approximated. + # axis is not a property of the pair, so it is refused by name. Random.seed!(7500) x = [0.1 0.2 0.35; -0.2 0.05 0.3] u = randn(2, 3) diff --git a/test/test_fits.jl b/test/test_fits.jl new file mode 100644 index 0000000..b47a4af --- /dev/null +++ b/test/test_fits.jl @@ -0,0 +1,310 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT +using ComputationalBackends: ComputationalBackends as CB +using Bessels: Bessels +using LsqFit: LsqFit +using LinearAlgebra: LinearAlgebra as LA +using Random: Random + +J0(x) = Bessels.besselj0(x) +J1(x) = Bessels.besselj1(x) +J2(x) = Bessels.besselj(2, x) + +# ∫ f dk over [a, b] by the trapezoid rule on a fine grid. +function _trapz(f, a, b; n = 200_001) + k = range(a, b; length = n) + v = f.(k) + return sum((v[1:(end - 1)] .+ v[2:end]) ./ 2 .* step(k)) +end + +# ∫ f dk over [a, b] by Simpson's rule on a fine grid. +function _simpson(f, a, b; n = 200_001) + n = isodd(n) ? n : n + 1 + k = range(a, b; length = n) + v = f.(k) + return step(k) / 3 * (v[1] + v[end] + 4 * sum(v[2:2:(end - 1)]) + 2 * sum(v[3:2:(end - 2)])) +end + +_centres(edges) = [(edges[j] + edges[j + 1]) / 2 for j in 1:(length(edges) - 1)] +_widths(edges) = diff(edges) +_logedges(a, b, n) = exp.(range(log(a), log(b); length = n + 1)) + +Test.@testset "the forward models are the relations they name" begin + r = collect(range(0.05, 15.0; length = 120)) + k_edges = _logedges(0.2, 20.0, 12) + # one dimension: ∫ (1 − cos kr) dk is elementary + m1 = SFC.SpectrumForwardModel(Val(1), r, k_edges) + H1 = [2 * ((k_edges[j + 1] - k_edges[j]) - (sin(k_edges[j + 1] * ri) - sin(k_edges[j] * ri)) / ri) + for ri in r, j in 1:(length(k_edges) - 1)] + Test.@test SFC.forward_matrix(m1) ≈ H1 rtol = 1e-12 + # two dimensions against a fine quadrature of the J₀ kernel + m2 = SFC.SpectrumForwardModel(Val(2), r[1:20:end], k_edges) + for (i, ri) in enumerate(r[1:20:end]), j in 1:3 + Test.@test m2.H[i, j] ≈ _trapz(k -> 2 * (1 - J0(k * ri)), k_edges[j], k_edges[j + 1]) rtol = 1e-8 + end + # the flux model is exact for a piecewise-constant flux: eq. 8 written out, and eq. 6 integrated + Random.seed!(4310) + mf = SFC.FluxForwardModel(r, k_edges) + kc, dk = _centres(k_edges), _widths(k_edges) + ε = 0.3 + ξ = rand(length(kc)) + x = vcat(ε, ξ) + S3 = SFC.forward_matrix(mf) * x + Test.@test S3 ≈ [2ε * ri - sum(4 * ξ[j] * dk[j] / kc[j] * J1(kc[j] * ri) for j in eachindex(kc)) for ri in r] rtol = 1e-12 + F(k) = -ε + sum(ξ[j] * dk[j] for j in eachindex(kc) if kc[j] <= k; init = 0.0) + Kmax = 60.0 + pieces = vcat(1e-6, kc, Kmax) # F is constant between its jumps at the bin centres + for ri in r[1:30:end] + integral = sum(F(pieces[p]) * _simpson(k -> J2(k * ri) / k, pieces[p], pieces[p + 1]; n = 200_001) + for p in 1:(length(pieces) - 1)) + integral += F(Kmax) * J1(Kmax * ri) / (Kmax * ri) # ∫_K^∞ J₂(kr)/k dk = J₁(Kr)/(Kr) + Test.@test -4 * ri * integral ≈ S3[findfirst(==(ri), r)] rtol = 1e-8 + end + Fc = SFC.flux_matrix(mf) * x + Test.@test Fc ≈ F.(kc) + # the Helmholtz model's sum and difference lines + mh = SFC.HelmholtzForwardModel(r[1:20:end], k_edges) + nr, nk = length(r[1:20:end]), length(kc) + for (i, ri) in enumerate(r[1:20:end]), j in 1:2 + plus = _trapz(k -> 1 - J0(k * ri), k_edges[j], k_edges[j + 1]) + minus = _trapz(k -> J2(k * ri), k_edges[j], k_edges[j + 1]) + Test.@test mh.H[i, j] + mh.H[nr + i, j] ≈ 2plus rtol = 1e-8 + Test.@test mh.H[i, j] - mh.H[nr + i, j] ≈ 2minus rtol = 1e-8 + Test.@test mh.H[i, nk + j] - mh.H[nr + i, nk + j] ≈ -2minus rtol = 1e-8 + end +end + +Test.@testset "round trips through the inversions" begin + Random.seed!(4320) + r = collect(range(0.05, 15.0; length = 150)) + k_edges = _logedges(0.2, 20.0, 12) + mf = SFC.FluxForwardModel(r, k_edges) + x = vcat(0.4, rand(length(k_edges) - 1)) + y = SFC.forward_matrix(mf) * x + W = fill(1e-20, length(y)) + xr, C = SFC.solve(SFC.RegularizedLeastSquares(nothing), mf.H, y, W) + Test.@test xr ≈ x rtol = 1e-8 + Test.@test size(C) == (length(x), length(x)) + xn, Cn = SFC.solve(SFC.NonNegativeLeastSquares(), mf.H, y, nothing) + Test.@test all(>=(0), xn) + Test.@test xn ≈ x rtol = 1e-8 + Test.@test Cn === nothing + # a flux with a sink cannot be represented by the monotone model: the constrained fit stays non-negative + xs = copy(x) + xs[5] = -0.5 + xneg, _ = SFC.solve(SFC.NonNegativeLeastSquares(), mf.H, mf.H * xs, nothing) + Test.@test all(>=(0), xneg) + Test.@test xneg[5] == 0 + # through the result objects + edges = collect(range(0.0, 15.0; length = 151)) + mids = SF.midpoints(edges) + S3 = SFC.forward_matrix(SFC.FluxForwardModel(collect(mids), k_edges)) * x + res = SF.StructureFunction(SFT.S3SFType(), edges, S3) + fit = SFC.fit_flux(res, k_edges, SFC.RegularizedLeastSquares(nothing); W = fill(1e-20, length(S3))) + Test.@test fit.ε ≈ x[1] rtol = 1e-8 + Test.@test fit.ξ ≈ x[2:end] rtol = 1e-8 + Test.@test fit.F ≈ SFC.flux_matrix(SFC.FluxForwardModel(collect(mids), k_edges)) * x rtol = 1e-8 + Test.@test fit.k == _centres(k_edges) + Test.@test size(fit.flux_covariance) == (length(k_edges) - 1, length(k_edges) - 1) + # a spectrum on bins, in one dimension: exact data on the model's own bins come back + E = 0.5 .+ rand(12) + m1 = SFC.SpectrumForwardModel(Val(1), r, k_edges) + y1 = m1.H * E + res1 = SF.StructureFunction(SFT.S2SFType(), edges, SFC.SpectrumForwardModel(Val(1), collect(mids), k_edges).H * E) + f1 = SFC.fit_spectrum(res1, k_edges, SFC.RegularizedLeastSquares(nothing), Val(1); W = fill(1e-20, 150)) + Test.@test f1.E ≈ E rtol = 1e-7 + f1n = SFC.fit_spectrum(res1, k_edges, SFC.NonNegativeLeastSquares(), Val(1)) + Test.@test f1n.E ≈ E rtol = 1e-7 + # sums-and-counts input with an empty bin dropped + counts = fill(UInt32(5), 150) + counts[40] = 0 + sums = 5 .* res1.values .* (counts .> 0) + raw = SF.StructureFunctionSumsAndCounts(SFT.S2SFType(), edges, sums, counts) + f1r = SFC.fit_spectrum(raw, k_edges, SFC.RegularizedLeastSquares(nothing), Val(1); W = fill(1e-20, 149)) + Test.@test f1r.E ≈ E rtol = 1e-7 +end + +Test.@testset "the Helmholtz fit separates gradient from curl" begin + ℓ = 1.0 + r = collect(range(0.05, 6.0; length = 80)) + C_LL(r) = (1 / ℓ^2 - r^2 / ℓ^4) * exp(-r^2 / (2ℓ^2)) + C_TT(r) = exp(-r^2 / (2ℓ^2)) / ℓ^2 + DLL = 2 .* (C_LL(0.0) .- C_LL.(r)) + DTT = 2 .* (C_TT(0.0) .- C_TT.(r)) + E_E(k) = k^3 * ℓ^2 * exp(-k^2 * ℓ^2 / 2) + k_edges = collect(range(0.02, 8.0; length = 41)) + nk = length(k_edges) - 1 + Ebar = [_trapz(E_E, k_edges[j], k_edges[j + 1]; n = 2001) / (k_edges[j + 1] - k_edges[j]) for j in 1:nk] + m = SFC.HelmholtzForwardModel(r, k_edges) + # the model on the bin-averaged gradient spectrum reproduces the closed forms to the binning error + pred = m.H * vcat(Ebar, zeros(nk)) + Test.@test pred[1:80] ≈ DLL rtol = 2e-2 + Test.@test pred[81:end] ≈ DTT rtol = 2e-2 + # and the inversion of the model's own data returns the spectra, with no curl, on bins the separations + # can resolve (a bin narrower than ~π/r_max is not) + kr_edges = collect(range(0.5, 8.0; length = 9)) + Er = [_trapz(E_E, kr_edges[j], kr_edges[j + 1]; n = 2001) / (kr_edges[j + 1] - kr_edges[j]) for j in 1:8] + edges = collect(range(0.0, 6.0; length = 81)) + mids = collect(SF.midpoints(edges)) + mm = SFC.HelmholtzForwardModel(mids, kr_edges) + y = mm.H * vcat(Er, zeros(8)) + L2 = SF.StructureFunction(SFT.L2SFType(), edges, y[1:80]) + T2 = SF.StructureFunction(SFT.T2SFType(), edges, y[81:end]) + fit = SFC.fit_helmholtz_spectra(L2, T2, kr_edges, SFC.RegularizedLeastSquares(nothing); W = fill(1e-20, 160)) + Test.@test fit.E ≈ Er rtol = 1e-6 + Test.@test maximum(abs, fit.B) < 1e-6 * maximum(Er) + Test.@test fit.k == _centres(kr_edges) + fitn = SFC.fit_helmholtz_spectra(L2, T2, kr_edges, SFC.NonNegativeLeastSquares()) + Test.@test fitn.E ≈ Er rtol = 1e-6 + Test.@test all(>=(0), fitn.B) + Test.@test_throws ArgumentError SFC.fit_helmholtz_spectra(T2, L2, kr_edges, SFC.NonNegativeLeastSquares()) +end + +Test.@testset "the segmented power law recovers slopes and breaks" begin + k_lo, k_hi = 0.3, 30.0 + r = collect(range(0.05, 12.0; length = 100)) + edges = collect(range(0.0, 12.0; length = 101)) + mids = collect(SF.midpoints(edges)) + for D in (1, 2) + # one segment: a power law comes back + e1 = SFC._segment_edges(k_lo, k_hi, 1) + kq, _, K = SFC._segmented_design(Val(D), mids, e1) + p_true = [0.7, -5 / 3] + y = K * SFC.segmented_spectrum(p_true, kq, e1) + res = SF.StructureFunction(SFT.S2SFType(), edges, y) + f = SFC.fit_spectrum(res, [k_lo, k_hi], SFC.SegmentedPowerLaw(1), Val(D)) + Test.@test f.converged + Test.@test f.parameters ≈ p_true rtol = 1e-6 + Test.@test f.E ≈ SFC.segmented_spectrum(p_true, f.k, e1) rtol = 1e-6 + Test.@test size(f.covariance) == (2, 2) + # two segments with the break at the log-uniform midpoint + e2 = SFC._segment_edges(k_lo, k_hi, 2) + kq2, _, K2 = SFC._segmented_design(Val(D), mids, e2) + p2 = [0.7, -1.0, -3.0] + y2 = K2 * SFC.segmented_spectrum(p2, kq2, e2) + res2 = SF.StructureFunction(SFT.S2SFType(), edges, y2) + f2 = SFC.fit_spectrum(res2, [k_lo, k_hi], SFC.SegmentedPowerLaw(2), Val(D)) + Test.@test f2.converged + Test.@test f2.parameters ≈ p2 rtol = 1e-5 + Test.@test f2.breakpoints ≈ e2 + sel = SFC.select_segments(res2, [k_lo, k_hi], 1:3, Val(D)) + Test.@test sel.segments == 2 + Test.@test sel.misfits[2] < 1e-6 + Test.@test sel.misfits[1] > 1e-2 + Test.@test issorted(sel.misfits[1:2]; rev = true) + # a data covariance weighs the residual, where the default weighs the relative misfit + fw = SFC.fit_spectrum(res2, [k_lo, k_hi], SFC.SegmentedPowerLaw(2), Val(D); W = fill(1e-6, 100)) + Test.@test fw.parameters ≈ p2 rtol = 1e-5 + end + # continuity at the breakpoints + e3 = SFC._segment_edges(k_lo, k_hi, 3) + p3 = [1.0, -1.0, -2.0, -3.5] + for b in e3[2:3] + Test.@test SFC.segmented_spectrum(p3, [prevfloat(b)], e3) ≈ SFC.segmented_spectrum(p3, [nextfloat(b)], e3) rtol = 1e-10 + end +end + +Test.@testset "the fitted flux is the flux the transform recovers" begin + Random.seed!(4340) + R = 200.0 + r = collect(range(0.02, R; length = 20_000)) + k_edges = _logedges(0.2, 20.0, 12) + kc = _centres(k_edges) + x = vcat(0.2, 0.1 .+ rand(12)) + m = SFC.FluxForwardModel(r, k_edges) + S3 = SFC.forward_matrix(m) * x + F = SFC.flux_matrix(m) * x + # between the jumps at the bin centres the flux is F[j]; at a jump the transform gives the midpoint value + K = k_edges[5:11] + Π = SFC.spectral_flux(SFT.S3SFType(), r, S3, K) + Test.@test Π ≈ F[4:10] rtol = 5e-2 + # and at twice the truncation radius, where the truncation error has moved through its oscillation + r2 = collect(range(0.02, 2R; length = 40_000)) + S3b = SFC.forward_matrix(SFC.FluxForwardModel(r2, k_edges)) * x + Π2 = SFC.spectral_flux(SFT.S3SFType(), r2, S3b, K) + Test.@test Π2 ≈ F[4:10] rtol = 5e-2 +end + +Test.@testset "posterior covariance and the trade-off curve" begin + Random.seed!(4350) + r = collect(range(0.05, 15.0; length = 150)) + k_edges = _logedges(0.2, 20.0, 12) + m = SFC.FluxForwardModel(r, k_edges) + H = SFC.forward_matrix(m) + x = vcat(0.4, rand(12)) + σ2 = 0.03 + y = H * x .+ sqrt(σ2) .* randn(length(r)) + xhat, C = SFC.solve(SFC.RegularizedLeastSquares(nothing), H, y, fill(σ2, length(y))) + Test.@test Matrix(C) ≈ σ2 .* inv(H' * H) rtol = 1e-10 + Test.@test xhat ≈ (H' * H) \ (H' * y) rtol = 1e-10 + edges = collect(range(0.0, 15.0; length = 151)) + fit = SFC.fit_flux(SF.StructureFunction(SFT.S3SFType(), edges, H * x), k_edges, + SFC.RegularizedLeastSquares(fill(1e-2, 13)); W = fill(σ2, 150)) + Test.@test Matrix(fit.flux_covariance) ≈ SFC.flux_matrix(m) * Matrix(fit.covariance) * SFC.flux_matrix(m)' rtol = 1e-12 + # a full data covariance equals its diagonal form + xd, Cd = SFC.solve(SFC.RegularizedLeastSquares(fill(1e-2, 13)), H, y, fill(σ2, length(y))) + xm, Cm = SFC.solve(SFC.RegularizedLeastSquares(fill(1e-2, 13)), H, y, LA.Diagonal(fill(σ2, length(y))) |> Matrix) + Test.@test xd ≈ xm rtol = 1e-10 + Test.@test Matrix(Cd) ≈ Matrix(Cm) rtol = 1e-10 + xp, _ = SFC.solve(SFC.RegularizedLeastSquares(1e-2 .* LA.I(13) |> Matrix), H, y, fill(σ2, length(y))) + Test.@test xp ≈ xd rtol = 1e-10 + # the trade-off curve: a weaker prior lowers the misfit and raises the norm + priors = 10.0 .^ range(-6, 2; length = 17) + curve = SFC.tradeoff_curve(m, y, fill(σ2, length(y)), priors) + Test.@test issorted(curve.misfit; rev = true) + Test.@test issorted(curve.norm) + Test.@test length(curve.misfit) == 17 +end + +Test.@testset "the data covariance from a value-binned joint histogram" begin + Random.seed!(4360) + N = 200 + x = rand(2, N) .* 10.0 + u = randn(2, N) + bins = [0.0, 2.0, 4.0, 7.0] + nb = length(bins) - 1 + vals = [Float64[] for _ in 1:nb] + for i in 1:(N - 1), j in (i + 1):N + dx = x[:, j] .- x[:, i] + rr = LA.norm(dx) + b = searchsortedfirst(bins, rr) - 1 + 1 <= b <= nb || continue + push!(vals[b], SFT.L2SFType()(u[:, j] .- u[:, i], dx ./ rr)) + end + truth = [sum(abs2, v .- sum(v) / length(v)) / length(v) / length(v) for v in vals] + vmax = maximum(maximum, vals) + fine = collect(range(-1e-9, vmax * (1 + 1e-9); length = 4001)) + joint = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, fine; backend = CB.SerialBackend(), + verbose = false, show_progress = false) + est = SFC.independent_pair_variance(joint) + Test.@test est ≈ truth rtol = 2e-3 + coarse = collect(range(-1e-9, vmax * (1 + 1e-9); length = 6)) + jc = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, coarse; backend = CB.SerialBackend(), + verbose = false, show_progress = false) + estc = SFC.independent_pair_variance(jc) + Test.@test all(estc .<= truth .* (1 + 1e-12)) + Test.@test all(estc .> 0) +end + +Test.@testset "the fits refuse what they cannot mean" begin + r = collect(range(0.05, 15.0; length = 60)) + edges = collect(range(0.0, 15.0; length = 61)) + k_edges = _logedges(0.2, 20.0, 8) + y = rand(60) + L2 = SF.StructureFunction(SFT.L2SFType(), edges, y) + S2 = SF.StructureFunction(SFT.S2SFType(), edges, y) + S3 = SF.StructureFunction(SFT.S3SFType(), edges, y) + Test.@test_throws ArgumentError SFC.fit_flux(L2, k_edges, SFC.NonNegativeLeastSquares()) + Test.@test_throws ArgumentError SFC.fit_spectrum(L2, k_edges, SFC.NonNegativeLeastSquares(), Val(2)) + Test.@test_throws ArgumentError SFC.fit_spectrum(S2, k_edges, SFC.RegularizedLeastSquares(nothing), Val(2)) + Test.@test_throws ArgumentError SFC.fit_flux(S3, reverse(k_edges), SFC.NonNegativeLeastSquares()) + Test.@test_throws ArgumentError SFC.fit_flux(S3, vcat(0.0, k_edges), SFC.NonNegativeLeastSquares()) + Test.@test_throws ArgumentError SFC.SegmentedPowerLaw(0) + Test.@test_throws ArgumentError SFC.SegmentedPowerLaw(2; slope_bounds = (1.0, -1.0)) + Test.@test_throws ArgumentError SFC.RegularizedLeastSquares([1.0, -1.0]) + Test.@test_throws DimensionMismatch SFC.solve(SFC.RegularizedLeastSquares(fill(1.0, 3)), rand(60, 9), y, fill(1.0, 60)) + Test.@test_throws DimensionMismatch SFC.fit_flux(S3, k_edges, SFC.RegularizedLeastSquares(nothing); W = fill(1.0, 7)) + Test.@test_throws ArgumentError SFC.fit_flux(S3, k_edges, SFC.RegularizedLeastSquares(nothing); W = fill(-1.0, 60)) + Test.@test_throws ArgumentError SFC.SpectrumForwardModel(Val(1), reverse(r), k_edges) + Test.@test_throws DimensionMismatch SFC.segmented_spectrum([1.0, 2.0], [1.0], [0.1, 1.0, 10.0]) +end diff --git a/test/test_gpu_joint2d_smem.jl b/test/test_gpu_joint2d_smem.jl index 3e8e61b..36ecac6 100644 --- a/test/test_gpu_joint2d_smem.jl +++ b/test/test_gpu_joint2d_smem.jl @@ -3,8 +3,8 @@ using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, - InfPaddedBinEdges, LinearBinEdges, LogBinEdges, - joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256 + InfPaddedBinEdges, LinearBinEdges, LogBinEdges +using StructureFunctions.Calculations: joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256 using Random: Random const GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) diff --git a/test/test_gpu_shape_contract.jl b/test/test_gpu_shape_contract.jl index 6d8ca49..22044e6 100644 --- a/test/test_gpu_shape_contract.jl +++ b/test/test_gpu_shape_contract.jl @@ -210,13 +210,13 @@ Test.@testset "GPU point-field families honour a spherical metric" begin ) Test.@test raw(DI.Euclidean()).counts != raw(m).counts - # And a metric with NO geometry is refused outright on every backend rather than being assumed - # flat — a distance function does not define a separation direction or a transport rule. + # And a metric with NO geometry is refused outright on every backend: a distance function + # defines neither a separation direction nor a transport rule. Test.@test_throws ArgumentError raw(DI.Cityblock()) end # The auxiliary-axis (batch) families carry the geometry into their kernels, so they honour a -# spherical metric and must reproduce the CPU's transported answer rather than a flat one. +# spherical metric and must reproduce the CPU's transported answer. Test.@testset "GPU batch families honour a spherical metric" begin FT = Float64 N, B = 40, 3 @@ -254,7 +254,7 @@ Test.@testset "GPU batch families honour a spherical metric" begin end # The point-field single-pass 2D family carries the geometry into its kernels, so it honors a -# non-Euclidean metric rather than refusing it, and must produce the CPU's transported answer. +# non-Euclidean metric and must produce the CPU's transported answer. Test.@testset "GPU single-pass 2D honors a spherical metric" begin FT = Float64 N = 96 @@ -284,8 +284,8 @@ Test.@testset "GPU single-pass 2D honors a spherical metric" begin Test.@test flat.L2.counts != got.L2.counts end -# The single-pass 2D GPU boundary used to splat display-only kwargs into a core with no `kwargs...` -# sink, so the package's own standard `verbose`/`show_progress` pair was a MethodError. +# The single-pass 2D GPU boundary accepts the package's standard `verbose`/`show_progress` pair, +# which its core takes no `kwargs...` sink for. Test.@testset "GPU single-pass 2D accepts the standard display kwargs" begin FT = Float64 N = 16 diff --git a/test/test_gpu_single_pass_tiled.jl b/test/test_gpu_single_pass_tiled.jl index 2fbbfa9..57780da 100644 --- a/test/test_gpu_single_pass_tiled.jl +++ b/test/test_gpu_single_pass_tiled.jl @@ -152,8 +152,8 @@ Test.@testset "GPU single-pass 2D global fallback parity" begin sp_cpu = SFC.calculate_structure_functions_single_pass_2d( x, u, bins, value_bins; backend = CB.SerialBackend(), ) - # `force_global_atomic` is a GPU routing override, so it goes to the GPU entry rather - # than the backend-generic one, which would have to ignore it on a CPU backend. + # `force_global_atomic` is a GPU routing override, so it goes to the GPU entry; the + # backend-generic entry has no meaning for it on a CPU backend. gs, gc = SFC.gpu_calculate_structure_functions_single_pass_2d( backend.backend, x, u, bins, value_bins; force_global_atomic = true, ) diff --git a/test/test_gpu_sp2d_3d.jl b/test/test_gpu_sp2d_3d.jl index 0f8c9d5..e2430aa 100644 --- a/test/test_gpu_sp2d_3d.jl +++ b/test/test_gpu_sp2d_3d.jl @@ -27,7 +27,7 @@ Test.@testset "GPU single-pass 2D, D = 3" begin # Total counts are conserved exactly — no pair may be dropped or double-counted. Individual # cells may differ by one where a pair sits within an ulp of a bin edge and GPU FMA rounds - # the other way; a systematic difference would be a real bug, a few boundary pairs are not. + # the other way, so the bound is one pair per cell and the total is exact. gcm, ccm = Array(gc), cc @test sum(Int.(gcm)) == sum(Int.(ccm)) @test maximum(abs.(Int.(gcm) .- Int.(ccm))) <= 1 diff --git a/test/test_gpu_sp2d_partitioned.jl b/test/test_gpu_sp2d_partitioned.jl index b184da3..a2537d6 100644 --- a/test/test_gpu_sp2d_partitioned.jl +++ b/test/test_gpu_sp2d_partitioned.jl @@ -453,9 +453,9 @@ end # which is why two defects lived here unnoticed: SP2D threw outright for any `n_dist > 128` (the # naive global-atomic route demanded a value-edge workspace that nothing supplies by default), and # the `:direct` strategy was chosen over plain global atomics well past the point where it loses -# 2–4× (see `gpu/SPEED_OF_LIGHT.md`). Float64 because Float32 carries only ~7 digits and a histogram -# this sparse (few pairs per cell, cancelling odd moments) disagrees with a Float64 reference by -# percent even on the CPU — a Float32 assertion here would be testing arithmetic, not the kernel. +# 2–4×. Float64 because Float32 carries only ~7 digits and a histogram this sparse (few pairs per +# cell, cancelling odd moments) disagrees with a Float64 reference by percent even on the CPU, so a +# Float32 assertion would be testing arithmetic and not the kernel. Test.@testset "GPU sp2d large bin counts (KA.CPU)" begin backend = KA.CPU() FT = Float64 @@ -472,7 +472,7 @@ Test.@testset "GPU sp2d large bin counts (KA.CPU)" begin ) sums_gpu = zeros(FT, 6, nd, nv) cnts_gpu = zeros(UInt32, 6, nd, nv) - # No workspace: the path that used to raise `ArgumentError` here. + # No workspace, which this path must accept. SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, cnts_gpu, x, u, dist, val; backend = CB.GPUBackend(backend), ) diff --git a/test/test_gpu_tiled_parity.jl b/test/test_gpu_tiled_parity.jl index 1b43a24..966b13f 100644 --- a/test/test_gpu_tiled_parity.jl +++ b/test/test_gpu_tiled_parity.jl @@ -2,7 +2,7 @@ using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: - StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, HelperFunctions as SFH, LinearBinEdges, LogBinEdges using Random: Random using LinearAlgebra: LinearAlgebra as LA @@ -173,6 +173,24 @@ Test.@testset "GPU joint 2D parity — L3SF log distance bins" begin Test.@test gpu.sums ≈ ref.sums atol = 1e-10 end +Test.@testset "GPU tiled parity — signed transverse operators keep the operator's convention" begin + for (D, N) in ((2, 50), (3, 40)) + x = rand(Float64, D, N) + u = randn(Float64, D, N) + bin_edges = collect(range(0.0, 1.4; length = 8)) + ops = (SFT.T3SFType(), SFT.L2T1SFType()) + D == 3 && (ops = (ops..., SFT.ProjectedStructureFunctionType{0, 3}( + SFH.ReferenceAxisTransverseBasis(LA.normalize(SA.SVector(1.0, sqrt(2.0), sqrt(3.0))))))) + for sft in ops + ref = _cpu_ref(sft, x, u, bin_edges) + gpu = _gpu_tiled(sft, x, u, bin_edges) + Test.@test gpu.counts == ref.counts + Test.@test gpu.sums ≈ ref.sums atol = 1e-10 + Test.@test any(!iszero, ref.sums) + end + end +end + Test.@testset "GPU tiled parity — NB > SF_GPU_MAX_BINS errors" begin N = 20 FT = Float64 diff --git a/test/test_gpu_workspace.jl b/test/test_gpu_workspace.jl index 8f25bae..6d91843 100644 --- a/test/test_gpu_workspace.jl +++ b/test/test_gpu_workspace.jl @@ -248,3 +248,52 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin SFC.release!(ws_sp) SFC.release!(ws_sp2d) end + +Test.@testset "three-dimensional slice batches (KA.CPU)" begin + # The slice-batch drivers dispatch their launchers on a runtime `D`, and those launchers + # specialize on `Val(2)` and `Val(3)`, so a `(3, N, T)` batch is a supported shape and must + # equal the same slices computed one at a time. A width the launchers do not specialize for + # is refused by name. + N, T, FT = 40, 4, Float64 + backend = KA.CPU() + sft = SFT.L2SFType() + bins = collect(FT, range(0.0, 1.5, length = 11)) + NB = length(bins) - 1 + Random.seed!(8801) + x_batch = rand(FT, 3, N, T) + u_batch = rand(FT, 3, N, T) + + ref_s = zeros(FT, NB, T) + ref_c = zeros(UInt32, NB, T) + for t in 1:T + r = SFC.gpu_calculate_structure_function(sft, backend, x_batch[:, :, t], u_batch[:, :, t], bins) + ref_s[:, t] .= r.sums + ref_c[:, t] .= r.counts + end + + got_s = zeros(FT, NB, T) + got_c = zeros(UInt32, NB, T) + SFC.gpu_calculate_structure_function_batch!(got_s, got_c, sft, backend, x_batch, u_batch, bins) + Test.@test got_c == ref_c + Test.@test isapprox(got_s, ref_s; atol = 1e-12) + Test.@test sum(Int.(got_c)) == T * N * (N - 1) ÷ 2 + + # the six single-pass invariants over the same batch + sp_s = zeros(FT, SFC.SINGLE_PASS_N, NB, T) + sp_c = zeros(UInt32, SFC.SINGLE_PASS_N, NB, T) + SFC.gpu_calculate_structure_functions_single_pass_batch!(sp_s, sp_c, backend, x_batch, u_batch, bins) + for t in 1:T + one_s = zeros(FT, SFC.SINGLE_PASS_N, NB) + one_c = zeros(UInt32, SFC.SINGLE_PASS_N, NB) + SFC.calculate_structure_functions_single_pass!(one_s, one_c, x_batch[:, :, t], u_batch[:, :, t], + bins; backend = CB.SerialBackend()) + Test.@test isapprox(sp_s[:, :, t], one_s; rtol = 1e-10, atol = 1e-12) + Test.@test sp_c[1, :, t] == one_c[1, :] + end + + # a width the launchers do not specialize for is refused, and says so + x4 = rand(FT, 4, N, T) + u4 = rand(FT, 4, N, T) + Test.@test_throws ErrorException SFC.gpu_calculate_structure_function_batch!( + got_s, got_c, sft, backend, x4, u4, bins) +end diff --git a/test/test_gridded.jl b/test/test_gridded.jl index 3511fd2..70a6e2d 100644 --- a/test/test_gridded.jl +++ b/test/test_gridded.jl @@ -109,7 +109,7 @@ Test.@testset "lag sweep on a bounded grid equals the unstructured path" begin got_s, got_c = _sweep(sf, u, dims, spacing, periodic, bins, Dg) ref_s = zeros(Float64, nb) ref_c = zeros(Int, nb) - SF.calculate_structure_function!(ref_s, ref_c, sf, x, reshape(u, Dg, N), bins) + SFC.calculate_structure_function!(ref_s, ref_c, sf, x, reshape(u, Dg, N), bins) Test.@test got_c == ref_c Test.@test isapprox(got_s, ref_s; rtol = 1e-10, atol = 1e-12) Test.@test sum(got_c) > 0 diff --git a/test/test_gridded_device.jl b/test/test_gridded_device.jl new file mode 100644 index 0000000..440e529 --- /dev/null +++ b/test/test_gridded_device.jl @@ -0,0 +1,144 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using SpectralBackends: SpectralBackends as SB +using KernelAbstractions: KernelAbstractions as KA +using StaticArrays: StaticArrays as SA +using FFTW: FFTW +using Random: Random + +const DEV = CB.GPUBackend(KA.CPU()) +const FFT = SB.FastFourierTransformSpectralBackend() + +# The device engine against the CPU engine on the same schedule; counts exact, sums to round-off. +function _device_matches(sf, u, s, edges, D; valid = SFC.AllValid(), count_type = Int, tag = FFT) + nb = length(edges) - 1 + a, ca = zeros(nb), zeros(count_type, nb) + b, cb = zeros(nb), zeros(count_type, nb) + SFC.gridded_sweep!(a, ca, sf, u, s, edges, Val(D), FFT; valid) + SFC.gridded_sweep!(b, cb, sf, u, s, edges, Val(D), tag; valid, backend = DEV) + scale = max(maximum(abs, a), 1e-12) + Test.@test ca == cb + Test.@test maximum(abs.(a .- b)) <= 1e-11 * scale + return nothing +end + +# A copy of the packed field with a fraction of its cells set to NaN, and their validity. +function _masked(u::AbstractMatrix, frac; seed = 3) + Random.seed!(seed) + v = copy(u) + v[:, rand(size(v, 2)) .< frac] .= NaN + return v, SFC.field_validity(v) +end + +Test.@testset "the device engine equals the CPU engine on a uniform grid" begin + Random.seed!(11) + dims = (24, 20) + edges = collect(range(0.0, 7.0; length = 15)) + for periodic in ((true, true), (false, false), (true, false)) + s = SFC.UniformLagSchedule(dims, (0.5, 0.7), periodic) + u = randn(2, dims...) + for sf in (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType()) + _device_matches(sf, u, s, edges, 2) + end + um, valid = _masked(reshape(u, 2, :), 0.25) + for sf in (SFT.L2SFType(), SFT.L3SFType()) + _device_matches(sf, reshape(um, 2, dims...), s, edges, 2; valid) + end + end + # three directions, floating-point counts, log bins + s3 = SFC.UniformLagSchedule((8, 9, 7), (1.0, 1.1, 0.9), (true, false, true)) + u3 = randn(3, 8, 9, 7) + _device_matches(SFT.L2SFType(), u3, s3, collect(range(0.0, 6.0; length = 9)), 3; count_type = Float64) + _device_matches(SFT.S3SFType(), u3, s3, SF.LogBinEdges(exp.(range(log(0.8), log(6.0); length = 8))), 3) +end + +Test.@testset "multi-fields and higher moments ride the device engine" begin + Random.seed!(12) + dims = (18, 16) + s = SFC.UniformLagSchedule(dims, (1.0, 1.0), (true, true)) + u = randn(2, dims...) + θ = randn(dims...) + f = Fields(vectors = (u,), scalars = (θ,)) + edges = collect(range(0.0, 8.0; length = 12)) + nb = length(edges) - 1 + for sf in (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{2}(), SFT.ProjectedStructureFunctionType{4, 0}()) + a, ca = zeros(nb), zeros(Int, nb) + b, cb = zeros(nb), zeros(Int, nb) + SFC.gridded_sweep!(a, ca, sf, f, s, edges, FFT) + SFC.gridded_sweep!(b, cb, sf, f, s, edges, FFT; backend = DEV) + Test.@test ca == cb + Test.@test maximum(abs.(a .- b)) <= 1e-11 * maximum(abs, a) + end +end + +Test.@testset "rectilinear and zonal schedules run on the device" begin + Random.seed!(13) + coords = cumsum(0.4 .+ 0.6 .* rand(9)) + sr = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((16,), (0.5,), (true,)), (coords,), (1, 2)) + ur = randn(2, 16, 9) + edges = collect(range(0.0, 5.0; length = 11)) + for sf in (SFT.L2SFType(), SFT.L3SFType()) + _device_matches(sf, ur, sr, edges, 2) + end + um, valid = _masked(reshape(ur, 2, :), 0.2) + _device_matches(SFT.S3SFType(), reshape(um, 2, 16, 9), sr, edges, 2; valid) + # the stretched axis first in the field + sr2 = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((16,), (0.5,), (true,)), (coords,), (2, 1)) + _device_matches(SFT.L2SFType(), randn(2, 9, 16), sr2, edges, 2) + + lats = collect(range(-1.2, 1.3; length = 11)) + n_lon = 20 + sz = SFC.ZonalLagSchedule(lats, n_lon, 2π / n_lon, 1.0, true) + uz = randn(2, n_lon, 11) + zedges = collect(range(0.0, π; length = 13)) + for sf in (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType()) + _device_matches(sf, uz, sz, zedges, 2) + end + um, valid = _masked(reshape(uz, 2, :), 0.3) + _device_matches(SFT.L2SFType(), reshape(um, 2, n_lon, 11), sz, zedges, 2; valid) + fz = Fields(vectors = (uz,), scalars = (randn(n_lon, 11),)) + nb = length(zedges) - 1 + a, ca = zeros(nb), zeros(Int, nb) + b, cb = zeros(nb), zeros(Int, nb) + SFC.gridded_sweep!(a, ca, SFT.MixedSFType{1, 0, 2}(), fz, sz, zedges, FFT) + SFC.gridded_sweep!(b, cb, SFT.MixedSFType{1, 0, 2}(), fz, sz, zedges, FFT; backend = DEV) + Test.@test ca == cb + Test.@test maximum(abs.(a .- b)) <= 1e-11 * maximum(abs, a) +end + +Test.@testset "the joint histogram and the wide histogram take the global-atomic path" begin + Random.seed!(14) + dims = (20, 18) + s = SFC.UniformLagSchedule(dims, (1.0, 1.0), (true, true)) + u = randn(2, dims...) + edges = collect(range(0.0, 12.0; length = 9)) # reaches the half-turn lags + aedges = collect(range(prevfloat(0.0), π; length = 7)) + nb, na = length(edges) - 1, length(aedges) - 1 + axis = SFC.SeparationAngleAxis([1.0, 0.0]) + a, ca = zeros(nb, na), zeros(nb, na) + b, cb = zeros(nb, na), zeros(nb, na) + SFC.gridded_sweep!(a, ca, SFT.L2SFType(), u, s, edges, aedges, Val(2), FFT; second_axis = axis) + SFC.gridded_sweep!(b, cb, SFT.L2SFType(), u, s, edges, aedges, Val(2), FFT; second_axis = axis, backend = DEV) + Test.@test ca == cb + Test.@test maximum(abs.(a .- b)) <= 1e-11 * maximum(abs, a) + Test.@test_throws ArgumentError SFC.gridded_sweep!(zeros(nb, na), zeros(Int, nb, na), SFT.L2SFType(), u, s, + edges, aedges, Val(2), FFT; second_axis = axis, backend = DEV) + # more bins than shared memory holds + wide = collect(range(0.0, 12.0; length = 4001)) + _device_matches(SFT.L2SFType(), u, s, wide, 2) +end + +Test.@testset "the device answers Auto with the transform and refuses what it cannot express" begin + dims = (12, 10) + s = SFC.UniformLagSchedule(dims, (1.0, 1.0), (true, true)) + u = randn(2, dims...) + edges = collect(range(0.0, 5.0; length = 8)) + _device_matches(SFT.L2SFType(), u, s, edges, 2; tag = SB.AutoSpectralBackend()) + nb = length(edges) - 1 + Test.@test_throws ArgumentError SFC.gridded_sweep!(zeros(nb), zeros(Int, nb), SFT.FullVectorStructureFunctionType{3}(), + u, s, edges, Val(2), SB.AutoSpectralBackend(); backend = DEV) + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!(zeros(nb), zeros(Int, nb), SFT.L2SFType(), u, s, edges, + Val(2); backend = DEV) +end diff --git a/test/test_gridded_fft.jl b/test/test_gridded_fft.jl index 7abc20a..a0d7038 100644 --- a/test/test_gridded_fft.jl +++ b/test/test_gridded_fft.jl @@ -70,13 +70,19 @@ Test.@testset "the transform refuses what it cannot express" begin periodic = (false, false) u = randn(T, 2, dims...) bins = collect(range(0.0, 1.0; length = 5)) - # a third-order operator is not a contraction of the second-order tensor - for sf in (SFT.L3SFType(), SFT.S3SFType()) - Test.@test_throws ArgumentError _run(sf, u, dims, spacing, periodic, bins, 2, - SB.FastFourierTransformSpectralBackend()) - # ...and the lag sweep still does it - _, c = _run(sf, u, dims, spacing, periodic, bins, 2, nothing) - Test.@test sum(c) > 0 + # an odd power of a norm is not a polynomial in the increment, so no moment tensor produces it + sf = SFT.FullVectorStructureFunctionType{3}() + Test.@test_throws ArgumentError _run(sf, u, dims, spacing, periodic, bins, 2, + SB.FastFourierTransformSpectralBackend()) + # ...and the lag sweep still does it + _, c = _run(sf, u, dims, spacing, periodic, bins, 2, nothing) + Test.@test sum(c) > 0 + # the third-order operators are polynomials and the transform computes them + for sf3 in (SFT.L3SFType(), SFT.S3SFType()) + ref_s, ref_c = _run(sf3, u, dims, spacing, periodic, bins, 2, nothing) + got_s, got_c = _run(sf3, u, dims, spacing, periodic, bins, 2, SB.FastFourierTransformSpectralBackend()) + Test.@test got_c == ref_c + Test.@test isapprox(got_s, ref_s; rtol = 1e-9, atol = 1e-10) end end @@ -101,11 +107,18 @@ Test.@testset "the algorithm tags select as documented" begin Test.@test au_c == ref_c Test.@test isapprox(au_s, ref_s; rtol = 1e-8, atol = 1e-10) - # auto on an operator no transform expresses still works, by sweeping - l3_s, l3_c = _run(SFT.L3SFType(), u, dims, spacing, periodic, bins, 2, SB.AutoSpectralBackend()) - ref3_s, ref3_c = _run(SFT.L3SFType(), u, dims, spacing, periodic, bins, 2, nothing) + # auto on an operator no transform expresses still works, by sweeping — bit-identically + l3_s, l3_c = _run(SFT.FullVectorStructureFunctionType{3}(), u, dims, spacing, periodic, bins, 2, + SB.AutoSpectralBackend()) + ref3_s, ref3_c = _run(SFT.FullVectorStructureFunctionType{3}(), u, dims, spacing, periodic, bins, + 2, nothing) Test.@test l3_c == ref3_c Test.@test l3_s == ref3_s + # auto on a third-order polynomial picks one of two exact algorithms + a3_s, a3_c = _run(SFT.L3SFType(), u, dims, spacing, periodic, bins, 2, SB.AutoSpectralBackend()) + r3_s, r3_c = _run(SFT.L3SFType(), u, dims, spacing, periodic, bins, 2, nothing) + Test.@test a3_c == r3_c + Test.@test isapprox(a3_s, r3_s; rtol = 1e-9, atol = 1e-10) end Test.@testset "the grid entry takes the tag positionally" begin diff --git a/test/test_gridded_flowgeometries.jl b/test/test_gridded_flowgeometries.jl index dd4e270..745c082 100644 --- a/test/test_gridded_flowgeometries.jl +++ b/test/test_gridded_flowgeometries.jl @@ -49,7 +49,7 @@ Test.@testset "a uniform Cartesian grid gives the unstructured answer" begin ) ref_s = zeros(Float64, nb) ref_c = zeros(UInt32, nb) - SF.calculate_structure_function!(ref_s, ref_c, SF1D, _points(grid), + SFC.calculate_structure_function!(ref_s, ref_c, SF1D, _points(grid), reshape(u, 2, nx * ny), bins) Test.@test got.counts == ref_c Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) @@ -107,46 +107,64 @@ Test.@testset "the adapter refuses only what is genuinely ill-posed" begin SF1D, uniform, randn(2, 4, 4), bins; nonsense = 1, verbose = false, show_progress = false) end -Test.@testset "grids with no structure to exploit are enumerated, not refused" begin - # A stretched axis, a curvilinear mesh and a pixelized sphere share no separation between pairs. - # Each is still a valid question, so the adapter routes it to the pair loop rather than erroring. - Random.seed!(5300) +# Bin edges between the separations a point set can produce, for grids whose separations are not +# `i·h`: near-equal separations are merged first, so no edge lands inside one shell. +function _separated_bins_points(x, n_bins) + N = size(x, 2) + seps = sort!([sqrt(sum(abs2, x[:, j] .- x[:, i])) for i in 1:(N - 1) for j in (i + 1):N]) + distinct = [seps[1]] + for s in seps + s - distinct[end] > 1e-9 && push!(distinct, s) + end + idx = unique(round.(Int, range(1, length(distinct) - 1; length = n_bins))) + return [0.0; [(distinct[i] + distinct[i + 1]) / 2 for i in idx]] +end - # a stretched Cartesian axis: the answer must equal the unstructured path on the same points +Test.@testset "a stretched axis keeps the lags of the uniform one beside it; no structure is enumerated" begin + # A stretched axis beside a uniform one shares a separation along the uniform one between every pair + # of stretched positions; two stretched axes share nothing. Both are valid questions, both are exact, + # and both must equal the unstructured path on the same points. + Random.seed!(5300) geo = FG.Geometry.CartesianGeometry() xs = [0.0, 0.1, 0.35, 0.8, 0.85] ys = range(0.0, step = 0.2, length = 4) - stretched = FG.Grids.StructuredGrid(geo, xs, ys) - u = randn(2, length(xs), length(ys)) - bins = collect(range(0.0, 1.5; length = 7)) - got = SFC.calculate_structure_function( - SF1D, stretched, u, bins, UInt32; output_type = SF.StructureFunctionSumsAndCounts, - verbose = false, show_progress = false) + sched_of(grid) = Base.invokelatest( + getfield(Base.get_extension(SF, :StructureFunctionsFlowGeometriesExt), :_lag_schedule), grid) N = length(xs) * length(ys) x = Matrix{Float64}(undef, 2, N) for (k, I) in enumerate(CartesianIndices((length(xs), length(ys)))) x[1, k] = xs[I[1]] x[2, k] = ys[I[2]] end - ref_s = zeros(6); ref_c = zeros(UInt32, 6) - SF.calculate_structure_function!(ref_s, ref_c, SF1D, x, reshape(u, 2, N), bins) + bins = _separated_bins_points(x, 6) + nb = length(bins) - 1 + u = randn(2, length(xs), length(ys)) + + stretched = FG.Grids.StructuredGrid(geo, xs, ys) + Test.@test sched_of(stretched) isa SFC.RectilinearLagSchedule + Test.@test SFC.n_cells(sched_of(stretched)) == N + got = SFC.calculate_structure_function( + SF1D, stretched, u, bins, UInt32; output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + ref_s = zeros(nb); ref_c = zeros(UInt32, nb) + SFC.calculate_structure_function!(ref_s, ref_c, SF1D, x, reshape(u, 2, N), bins) Test.@test got.counts == ref_c Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) Test.@test sum(got.counts) > 0 - # the schedule chosen really is the structureless one, not a lag sweep - sched = Base.invokelatest( - getfield(Base.get_extension(SF, :StructureFunctionsFlowGeometriesExt), :_lag_schedule), - stretched) - Test.@test sched isa SFC.ScatteredPairs - Test.@test SFC.n_scattered_cells(sched) == N + # the same points with both axes as coordinate lists share no lag, and are enumerated + structureless = FG.Grids.StructuredGrid(geo, xs, collect(ys)) + Test.@test sched_of(structureless) isa SFC.ScatteredPairs + Test.@test SFC.n_scattered_cells(sched_of(structureless)) == N + got2 = SFC.calculate_structure_function( + SF1D, structureless, u, bins, UInt32; output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + Test.@test got2.counts == ref_c + Test.@test isapprox(got2.sums, ref_s; rtol = 1e-10, atol = 1e-12) # while a uniform grid still gets the lag sweep uniform = FG.Grids.StructuredGrid(geo, range(0.0, step = 0.2, length = 5), ys) - sched_u = Base.invokelatest( - getfield(Base.get_extension(SF, :StructureFunctionsFlowGeometriesExt), :_lag_schedule), - uniform) - Test.@test sched_u isa SFC.UniformLagSchedule + Test.@test sched_of(uniform) isa SFC.UniformLagSchedule end Test.@testset "a pixelized sphere is enumerated too" begin @@ -178,7 +196,7 @@ Test.@testset "a pixelized sphere is enumerated too" begin coords = FG.Grids.materialize(grid) x = permutedims(hcat(coords...)) ref_s = zeros(5); ref_c = zeros(UInt32, 5) - SF.calculate_structure_function!(ref_s, ref_c, SF1D, x, u, bins; + SFC.calculate_structure_function!(ref_s, ref_c, SF1D, x, u, bins; distance_metric = SFC.DI.SphericalAngle()) Test.@test got.counts == ref_c Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) diff --git a/test/test_gridded_masked.jl b/test/test_gridded_masked.jl index ad0939d..de50e66 100644 --- a/test/test_gridded_masked.jl +++ b/test/test_gridded_masked.jl @@ -47,18 +47,18 @@ end Test.@testset "field_validity reports what is usable" begin u = randn(2, 4, 3) - Test.@test SFC.field_validity(u, Val(2)) isa SFC.AllValid + Test.@test SFC.field_validity(u) isa SFC.AllValid u[1, 2, 2] = NaN - v = SFC.field_validity(u, Val(2)) + v = SFC.field_validity(u) Test.@test !(v isa SFC.AllValid) Test.@test count(v) == 11 # one cell of twelve lost Test.@test !v[2 + (2 - 1) * 4] # an infinite component is no more usable than a missing one u2 = randn(2, 3, 3); u2[2, 1, 1] = Inf - Test.@test count(SFC.field_validity(u2, Val(2))) == 8 + Test.@test count(SFC.field_validity(u2)) == 8 # a cell the grid says does not exist is excluded even where the field is finite cm = trues(12); cm[5] = false - Test.@test count(SFC.field_validity(randn(2, 4, 3), Val(2), cm)) == 11 + Test.@test count(SFC.field_validity(randn(2, 4, 3), cm)) == 11 # AllValid answers for any index, so a complete field needs no array Test.@test SFC.AllValid()[1] && SFC.AllValid()[10^9] end @@ -76,7 +76,7 @@ Test.@testset "a masked sweep matches brute force" begin for k in 1:N rand() < frac && (uf[1, k] = NaN) end - valid = SFC.field_validity(u, Val(Dg)) + valid = SFC.field_validity(u) Test.@test !(valid isa SFC.AllValid) bins = collect(range(0.0, 0.7 * maximum(d -> spacing[d] * dims[d], 1:Dg); length = 7)) for sf in (SFT.L2SFType(), SFT.L3SFType()) @@ -104,7 +104,7 @@ Test.@testset "the masked transform matches the masked sweep" begin for k in 1:N rand() < 0.2 && (uf[2, k] = NaN) end - valid = SFC.field_validity(u, Val(Dg)) + valid = SFC.field_validity(u) bins = collect(range(0.0, 1.2; length = 8)) for sf in (SFT.S2SFType(), SFT.L2SFType(), SFT.T2SFType()) ref_s, ref_c = _run(sf, u, dims, spacing, periodic, bins, Dg, valid, nothing) diff --git a/test/test_gridded_moments.jl b/test/test_gridded_moments.jl new file mode 100644 index 0000000..b73ef8c --- /dev/null +++ b/test/test_gridded_moments.jl @@ -0,0 +1,309 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO, HelperFunctions as SFH +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using StaticArrays: StaticArrays as SA +using FFTW: FFTW +using SpectralBackends: SpectralBackends as SB +using FlowGeometries: FlowGeometries as FG +using Random: Random + +const FFT_TAG = SB.FastFourierTransformSpectralBackend() + +# One call for either route, on a bare array or a multi-field. +function _moments_run(sf, field, dims, spacing, periodic, bins; valid = SFC.AllValid(), backend = nothing) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + s = zeros(Float64, nb) + c = zeros(Int, nb) + sched = SFC.UniformLagSchedule(dims, spacing, periodic) + if field isa Fields + backend === nothing ? SFC.gridded_lag_sweep!(s, c, sf, field, sched, bins; valid) : + SFC.gridded_sweep!(s, c, sf, field, sched, bins, backend; valid) + else + D = size(field, 1) + backend === nothing ? SFC.gridded_lag_sweep!(s, c, sf, field, sched, bins, Val(D); valid) : + SFC.gridded_sweep!(s, c, sf, field, sched, bins, Val(D), backend; valid) + end + return s, c +end + +# An odd operator on a self-reverse lag is exactly zero in the sweep and round-off in the transform, so +# the comparison carries an absolute floor set by the field scale. +_moments_close(got, ref) = isapprox(got, ref; rtol = 1e-9, atol = 1e-10 * max(1.0, maximum(abs, ref))) + +const MOMENT_GRIDS = ( + ((9, 6), (0.1, 0.2), (false, false)), + ((8, 8), (0.25, 0.25), (true, true)), + ((10, 7), (0.15, 0.15), (true, false)), + ((12,), (0.3,), (false,)), + ((6, 5, 4), (0.2, 0.2, 0.3), (false, false, false)), + ((6, 6, 4), (0.2, 0.2, 0.3), (true, false, true)), +) + +const VECTOR_OPS = ( + SFT.S2SFType(), SFT.L2SFType(), SFT.T2SFType(), SFT.T2ComponentSFType(), + SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType(), SFT.L1T2ComponentSFType(), + SFT.ProjectedStructureFunctionType{4, 0}(), SFT.ProjectedStructureFunctionType{2, 2}(), + SFT.FullVectorStructureFunctionType{4}(), SFT.VectorDotSFType(1, 1), +) +# Operators reading one signed transverse component; at D = 3 the lags along ẑ take the x̂ rule. +const ODD_TRANSVERSE_OPS = (SFT.L2T1SFType(), SFT.T3SFType(), SFT.ProjectedStructureFunctionType{0, 4}()) +# The canonical rule about an axis no lattice lag is parallel to: a non-canonical basis through moment_contract. +const AXIS_OPS = (SFT.ProjectedStructureFunctionType{0, 3}( + SFH.ReferenceAxisTransverseBasis(SA.SVector(1.0, sqrt(2.0), sqrt(3.0)))),) + +Test.@testset "the transform equals the lag sweep for every polynomial operator" begin + for (dims, spacing, periodic) in MOMENT_GRIDS + Dg = length(dims) + Random.seed!(9100 + prod(dims) + Dg) + u = randn(Dg, dims...) + r_max = 0.7 * sum(d -> spacing[d] * dims[d], 1:Dg) + bins = collect(range(0.0, r_max; length = 9)) + ops = Dg == 1 ? VECTOR_OPS : + Dg == 2 ? (VECTOR_OPS..., ODD_TRANSVERSE_OPS...) : (VECTOR_OPS..., ODD_TRANSVERSE_OPS..., AXIS_OPS...) + for sf in ops + Dg == 1 && sf isa Union{SFT.T2ComponentSFType, SFT.L1T2ComponentSFType} && continue + ref_s, ref_c = _moments_run(sf, u, dims, spacing, periodic, bins) + got_s, got_c = _moments_run(sf, u, dims, spacing, periodic, bins; backend = FFT_TAG) + Test.@test got_c == ref_c + Test.@test _moments_close(got_s, ref_s) + Test.@test sum(got_c) > 0 + end + end +end + +Test.@testset "the masked transform equals the masked lag sweep at every order" begin + for (dims, spacing, periodic) in MOMENT_GRIDS[1:3] + N = prod(dims) + Random.seed!(9200 + N) + u = randn(2, dims...) + uf = reshape(u, 2, N) + for k in 1:N + rand() < 0.3 && (uf[1, k] = NaN) + end + valid = SFC.field_validity(u) + Test.@test !(valid isa SFC.AllValid) + bins = collect(range(0.0, 1.3; length = 8)) + for sf in (SFT.S2SFType(), SFT.L2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType(), + SFT.ProjectedStructureFunctionType{4, 0}(), SFT.T3SFType()) + ref_s, ref_c = _moments_run(sf, u, dims, spacing, periodic, bins; valid) + got_s, got_c = _moments_run(sf, u, dims, spacing, periodic, bins; valid, backend = FFT_TAG) + Test.@test got_c == ref_c + Test.@test _moments_close(got_s, ref_s) + Test.@test all(isfinite, got_s) + Test.@test sum(got_c) > 0 + end + end +end + +# Grid coordinates as a point list, for the unstructured oracle. +function _grid_points(dims, spacing) + Dg = length(dims) + N = prod(dims) + x = zeros(Float64, Dg, N) + for (k, I) in enumerate(CartesianIndices(dims)), d in 1:Dg + x[d, k] = (I[d] - 1) * spacing[d] + end + return x +end + +Test.@testset "multi-fields on a grid: scalar, mixed and cross-field moments" begin + dims = (9, 7) + spacing = (0.1, 0.15) + Random.seed!(9300) + u = randn(2, dims...) + θ = randn(dims...) + a = randn(2, dims...) + # edges between the separations the lattice can produce, so a whole shell never sits on one + bins = [0.0; collect(range(0.1137, 0.93; length = 7))] + f_vs = Fields(vectors = (u,), scalars = (θ,)) + f_s = Fields(scalars = (θ, a[1, :, :])) + f_vv = Fields(vectors = (u, a)) + cases = ( + (f_vs, (SFT.ScalarSFType{2}(), SFT.ScalarSFType{3}(), SFT.MixedSFType{1, 0, 2}(), + SFT.MixedSFType{1, 0, 1}(), SFT.MixedSFType{0, 2, 1}(), SFT.L2SFType(), SFT.S3SFType())), + (f_s, (SFT.ScalarSFType{2}(), SFT.ScalarSFType{3}(2), SFT.ScalarDotSFType(1, 2))), + (f_vv, (SFT.VectorDotSFType(1, 2), SFT.VectorDotSFType(2, 2), SFT.L2SFType())), + ) + for periodic in ((true, false), (false, false)), (f, ops) in cases, sf in ops + ref_s, ref_c = _moments_run(sf, f, dims, spacing, periodic, bins) + got_s, got_c = _moments_run(sf, f, dims, spacing, periodic, bins; backend = FFT_TAG) + Test.@test got_c == ref_c + Test.@test _moments_close(got_s, ref_s) + Test.@test sum(got_c) > 0 + end + + # The lag sweep on a multi-field against the unstructured field path over the same points, which is + # checked against brute force in test_multifields.jl and shares no code with the lag enumeration. + x = _grid_points(dims, spacing) + for (f, ops) in cases, sf in ops + ref = SFC.calculate_structure_function(sf, x, f, bins; backend = CB.SerialBackend(), + output_type = SFO.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + got_s, got_c = _moments_run(sf, f, dims, spacing, (false, false), bins) + Test.@test got_c == Int.(ref.counts) + Test.@test isapprox(got_s, ref.sums; rtol = 1e-10, atol = 1e-12) + end + + # a field the multi-field does not carry is refused, on both routes + Test.@test_throws ArgumentError _moments_run(SFT.VectorDotSFType(1, 2), f_vs, dims, spacing, + (false, false), bins) + Test.@test_throws ArgumentError _moments_run(SFT.VectorDotSFType(1, 2), f_vs, dims, spacing, + (false, false), bins; backend = FFT_TAG) + Test.@test_throws ArgumentError _moments_run(SFT.L2SFType(), f_s, dims, spacing, (false, false), + bins; backend = FFT_TAG) +end + +Test.@testset "directional output on a grid agrees with the unstructured joint path and marginalises" begin + dims = (10, 8) + spacing = (0.1, 0.1) + Random.seed!(9400) + u = randn(2, dims...) + # edges placed between the separations and angles a lattice can produce + bins = [0.0; collect(range(0.1137, 0.95; length = 7))] + # angle 0 is exact for lags along the reference axis; bins are (lo, hi], so the first edge sits below it + ax_bins = [prevfloat(0.0); collect(range(0.3011, π - 0.3; length = 5)); π + 1e-9] + src = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0)) + nb = length(bins) - 1 + na = length(ax_bins) - 1 + sched = SFC.UniformLagSchedule(dims, spacing, (false, false)) + + ts = zeros(nb, na); tc = zeros(Float64, nb, na) + SFC.gridded_sweep!(ts, tc, SFT.L2SFType(), u, sched, bins, ax_bins, Val(2), FFT_TAG; second_axis = src) + ss = zeros(nb, na); sc = zeros(Float64, nb, na) + SFC.gridded_lag_sweep!(ss, sc, SFT.L2SFType(), u, sched, bins, ax_bins, Val(2); second_axis = src) + + x = _grid_points(dims, spacing) + ref = SFC.serial_calculate_structure_function(SFT.L2SFType(), x, reshape(u, 2, :), bins, ax_bins; + second_axis = src, verbose = false, show_progress = false) + Test.@test sc == Float64.(ref.counts) + Test.@test tc == Float64.(ref.counts) + Test.@test isapprox(ss, ref.sums; rtol = 1e-10, atol = 1e-12) + Test.@test isapprox(ts, ref.sums; rtol = 1e-9, atol = 1e-10) + Test.@test sum(tc) > 0 + + # summing over the angle gives the 1-D result, bin for bin + s1, c1 = _moments_run(SFT.L2SFType(), u, dims, spacing, (false, false), bins) + Test.@test vec(sum(tc; dims = 2)) == Float64.(c1) + Test.@test isapprox(vec(sum(ts; dims = 2)), s1; rtol = 1e-9, atol = 1e-10) + + # on a periodic grid with an even cell count the half-turn lags split their pairs between two + # directions: integer counts are refused, floating-point ones still marginalise exactly + per = SFC.UniformLagSchedule((8, 8), (0.25, 0.25), (true, true)) + u8 = randn(2, 8, 8) + pbins = [0.0; collect(range(0.2611, 1.5; length = 6))] + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!( + zeros(6, na), zeros(Int, 6, na), SFT.L2SFType(), u8, per, pbins, ax_bins, Val(2); second_axis = src) + ps = zeros(6, na); pc = zeros(Float64, 6, na) + SFC.gridded_sweep!(ps, pc, SFT.L2SFType(), u8, per, pbins, ax_bins, Val(2), FFT_TAG; second_axis = src) + ps1, pc1 = _moments_run(SFT.L2SFType(), u8, (8, 8), (0.25, 0.25), (true, true), pbins) + Test.@test isapprox(vec(sum(pc; dims = 2)), Float64.(pc1); atol = 1e-9) + Test.@test isapprox(vec(sum(ps; dims = 2)), ps1; rtol = 1e-9, atol = 1e-10) +end + +Test.@testset "the forward transforms batch, and the batch size changes nothing" begin + # Every (slab, monomial) is a short transform along the uniform directions, so they go through one + # batched call; the batch is bounded by a byte budget. Driving the budget down to one column at a + # time, and to a size that leaves a short last batch, must not move a single number. + ext = Base.get_extension(SF, :StructureFunctionsAbstractFFTsExt) + Random.seed!(9550) + dims = (24, 9) # 9 slabs of 24, so the stretched axis makes many small transforms + coords = cumsum(0.7 .+ 0.4 .* rand(dims[2])) + s = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((dims[1],), (0.5,), (true,)), (coords,), (1, 2)) + u = randn(2, dims...) + bins = collect(range(0.0, 4.0; length = 9)) + budget = ext.FORWARD_BATCH_BYTES[] + try + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + run() = (a = zeros(Float64, nb); c = zeros(Int, nb); + SFC.gridded_sweep!(a, c, SFT.L2SFType(), u, s, bins, Val(2), FFT_TAG); (a, c)) + ref_s, ref_c = run() + # a slab costs 24·8 + 13·16 = 400 bytes here, so these give batches of 9 (one), 1, 2 (a short + # last batch of 1) and 4 (a short last batch of 1) + for bytes in (budget, 1, 800, 1600) + ext.FORWARD_BATCH_BYTES[] = bytes + got_s, got_c = run() + Test.@test got_s == ref_s + Test.@test got_c == ref_c + end + Test.@test sum(ref_c) > 0 + finally + ext.FORWARD_BATCH_BYTES[] = budget + end +end + +Test.@testset "gridded_spectrum transforms each monomial once, and a descending axis gives positive dk" begin + ext = Base.get_extension(SF, :StructureFunctionsAbstractFFTsExt) + Test.@test ext !== nothing + dims = (16, 12) + Random.seed!(9500) + u = randn(2, dims...) + s = SFC.UniformLagSchedule(dims, (0.5, 0.5), (true, true)) + mt = ext.MonomialTransforms(reshape(u, 2, :), s, dims, SFC.AllValid()) + ext._trace_lags(mt, Val(2)) + Test.@test mt.misses == 1 + 2 * 2 # the mask, each component, each square + Test.@test mt.hits >= 1 + Test.@test all(k -> k[2] == 0 || k[1] == k[2], keys(mt.cache)) # no off-diagonal monomial + + kax, dens = SFC.gridded_spectrum(u, s, Val(2), FFT_TAG) + sdesc = SFC.UniformLagSchedule(dims, (0.5, -0.5), (true, true)) + kax2, dens2 = SFC.gridded_spectrum(u, sdesc, Val(2), FFT_TAG) + Test.@test dens2 == dens + Test.@test kax2[2] == kax[2] + Test.@test sum(dens) > 0 +end + +Test.@testset "padding to n + h_max reproduces the 2n − 1 result at every lag within r_max" begin + ext = Base.get_extension(SF, :StructureFunctionsAbstractFFTsExt) + dims = (24, 20) + spacing = (0.1, 0.1) + Random.seed!(9600) + u = randn(2, dims...) + s = SFC.UniformLagSchedule(dims, spacing, (false, false)) + tight = collect(range(0.0, 0.35; length = 6)) # h_max = 3 along each direction + P_tight = ext._pad_dims(s, 0.35) + P_full = ext._pad_dims(s, Inf) + Test.@test all(P_tight .< P_full) + Test.@test all(P_tight .>= dims .+ 3) + for sf in (SFT.L2SFType(), SFT.L3SFType()) + ref_s, ref_c = _moments_run(sf, u, dims, spacing, (false, false), tight) + got_s, got_c = _moments_run(sf, u, dims, spacing, (false, false), tight; backend = FFT_TAG) + Test.@test got_c == ref_c + Test.@test _moments_close(got_s, ref_s) + end +end + +Test.@testset "the grid entry takes a multi-field and a joint request" begin + geo = FG.Geometry.CartesianGeometry() + nx, ny = 9, 7 + grid = FG.Grids.StructuredGrid(geo, range(0.0, step = 0.2, length = nx), + range(0.0, step = 0.2, length = ny)) + Random.seed!(9700) + u = randn(2, nx, ny) + θ = randn(nx, ny) + f = Fields(vectors = (u,), scalars = (θ,)) + bins = [0.0; collect(range(0.2137, 1.4; length = 7))] + yag = SFT.MixedSFType{1, 0, 2}() + swept = SFC.calculate_structure_function(yag, grid, f, bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + transformed = SFC.calculate_structure_function(yag, grid, f, bins, UInt32, FFT_TAG; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test transformed.counts == swept.counts + Test.@test _moments_close(transformed.sums, swept.sums) + Test.@test sum(swept.counts) > 0 + + ax_bins = [prevfloat(0.0); collect(range(0.3011, π - 0.3; length = 5)); π + 1e-9] + src = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0)) + joint = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, ax_bins; + second_axis = src, verbose = false, show_progress = false) + joint_t = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, ax_bins, FFT_TAG; + second_axis = src, verbose = false, show_progress = false) + plain = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test joint isa SFO.StructureFunction2DSumsAndCounts + Test.@test vec(sum(joint.counts; dims = 2)) == Float64.(plain.counts) + Test.@test isapprox(vec(sum(joint.sums; dims = 2)), plain.sums; rtol = 1e-10, atol = 1e-12) + Test.@test joint_t.counts == joint.counts + Test.@test _moments_close(joint_t.sums, joint.sums) +end diff --git a/test/test_gridded_separable.jl b/test/test_gridded_separable.jl new file mode 100644 index 0000000..dbbbf4f --- /dev/null +++ b/test/test_gridded_separable.jl @@ -0,0 +1,457 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO, HelperFunctions as SFH +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using OhMyThreads: OhMyThreads +using FFTW: FFTW +using SpectralBackends: SpectralBackends as SB +using FlowGeometries: FlowGeometries as FG +using Distances: Distances as DI +using StaticArrays: StaticArrays as SA +using Random: Random + +const FFT_TAG = SB.FastFourierTransformSpectralBackend() +const RE = 6.371e6 + +# An odd operator on a self-reverse lag is exactly zero in the sweep and round-off in the transform, so +# the comparison carries an absolute floor set by the field scale. +_close(got, ref) = isapprox(got, ref; rtol = 1e-9, atol = 1e-10 * max(1.0, maximum(abs, ref))) + +# The lat-lon grid's cells as the unstructured entry wants them: (λ, φ) in radians and the local +# (east, north) components, flattened in the order the zonal schedule indexes cells. +function _zonal_points(lats, n_lon, dlon, u) + W = size(u, 1) + n_lat = length(lats) + x = Matrix{Float64}(undef, 2, n_lon * n_lat) + uu = Matrix{Float64}(undef, W, n_lon * n_lat) + for j in 1:n_lat, i in 1:n_lon + k = i + (j - 1) * n_lon + x[1, k] = (i - 1) * dlon + x[2, k] = lats[j] + for c in 1:W + uu[c, k] = u[c, i, j] + end + end + return x, uu +end + +# Cell coordinates of a rectilinear grid in the order `reshape(u, W, :)` flattens them. +function _grid_points(axes) + dims = map(length, axes) + x = Matrix{Float64}(undef, length(axes), prod(dims)) + for (k, I) in enumerate(CartesianIndices(dims)), d in eachindex(axes) + x[d, k] = axes[d][I[d]] + end + return x +end + +# Bin edges between the separations a point set can produce. Pairs sharing a lag share one exact +# separation, so an edge through it splits a whole shell by rounding: the sweep bins them by the lag's +# separation and a pair loop by each pair's own coordinate difference, which differ by an ulp. +function _separated_bins(x, n_bins) + N = size(x, 2) + seps = sort!([sqrt(sum(abs2, x[:, j] .- x[:, i])) for i in 1:(N - 1) for j in (i + 1):N]) + distinct = [seps[1]] + for s in seps + s - distinct[end] > 1e-9 && push!(distinct, s) + end + idx = unique(round.(Int, range(1, length(distinct) - 1; length = n_bins))) + return [0.0; [(distinct[i] + distinct[i + 1]) / 2 for i in idx]] +end + +function _run(sf, u, sched, bins; valid = SFC.AllValid(), tag = nothing, backend = CB.SerialBackend()) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + s = zeros(Float64, nb) + c = zeros(Int, nb) + if u isa Fields + tag === nothing ? SFC.gridded_lag_sweep!(s, c, sf, u, sched, bins; valid, backend) : + SFC.gridded_sweep!(s, c, sf, u, sched, bins, tag; valid, backend) + else + D = size(u, 1) + tag === nothing ? SFC.gridded_lag_sweep!(s, c, sf, u, sched, bins, Val(D); valid, backend) : + SFC.gridded_sweep!(s, c, sf, u, sched, bins, Val(D), tag; valid, backend) + end + return s, c +end + +function _reference(sf, x, u, bins; metric = DI.Euclidean()) + nb = length(bins) - 1 + s = zeros(nb) + c = zeros(Int, nb) + if u isa Fields + ref = SFC.calculate_structure_function(sf, x, u, bins; distance_metric = metric, + backend = CB.SerialBackend(), output_type = SFO.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + return ref.sums, Int.(ref.counts) + end + SFC.calculate_structure_function!(s, c, sf, x, u, bins; distance_metric = metric) + return s, c +end + +const ZONAL_OPS = (SFT.L2SFType(), SFT.T2SFType(), SFT.S2SFType(), SFT.L3SFType(), SFT.S3SFType(), + SFT.L1T2SFType()) + +Test.@testset "the zonal transform equals the zonal sweep and the spherical pair loop" begin + # The sweep is checked against the pair loop, which shares no code with the lag enumeration; the + # transform is checked against the sweep, which shares the enumeration but not the algebra. + for (n_lon, dlon, periodic, lats) in ( + (12, 2π / 12, true, [-0.9, -0.5, -0.3, 0.1, 0.35, 0.8]), + (9, 0.07, false, [-1.0, -0.6, -0.55, -0.2]), + (16, 2π / 16, true, collect(range(0.1, 0.9; length = 5))), + ) + Random.seed!(7100 + n_lon) + u = randn(2, n_lon, length(lats)) + bins = collect(range(0.0, 0.45π; length = 8)) + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, 1.0, periodic) + x, uu = _zonal_points(lats, n_lon, dlon, u) + for sf in ZONAL_OPS + ref_s, ref_c = _reference(sf, x, uu, bins; metric = SFH.SphericalDistance(1.0)) + sw_s, sw_c = _run(sf, u, sched, bins) + tr_s, tr_c = _run(sf, u, sched, bins; tag = FFT_TAG) + Test.@test sw_c == ref_c + Test.@test isapprox(sw_s, ref_s; rtol = 1e-9, atol = 1e-10) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test sum(tr_c) > 0 + end + + # missing cells: the mask's own transform carries the counts + um = copy(u) + uf = reshape(um, 2, :) + for k in 1:size(uf, 2) + rand() < 0.25 && (uf[1, k] = NaN) + end + valid = SFC.field_validity(um) + Test.@test !(valid isa SFC.AllValid) + for sf in (SFT.L2SFType(), SFT.L3SFType(), SFT.S3SFType()) + sw_s, sw_c = _run(sf, um, sched, bins; valid) + tr_s, tr_c = _run(sf, um, sched, bins; valid, tag = FFT_TAG) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test all(isfinite, tr_s) + Test.@test sum(tr_c) > 0 + end + end +end + +Test.@testset "a scalar field rides the zonal transform" begin + n_lon, lats = 11, [-0.7, -0.4, 0.0, 0.3, 0.75] + dlon = 2π / n_lon + Random.seed!(7200) + u = randn(2, n_lon, length(lats)) + th = randn(n_lon, length(lats)) + f = Fields(vectors = (u,), scalars = (th,)) + x, uu = _zonal_points(lats, n_lon, dlon, u) + f_pts = Fields(vectors = (uu,), scalars = (vec(th),)) + bins = collect(range(0.0, 0.5π; length = 7)) + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, 1.0, true) + for sf in (SFT.MixedSFType{1, 0, 2}(), SFT.MixedSFType{1, 0, 1}(), SFT.ScalarSFType{3}(), + SFT.ScalarSFType{2}(), SFT.MixedSFType{0, 2, 1}()) + ref_s, ref_c = _reference(sf, x, f_pts, bins; metric = SFH.SphericalDistance(1.0)) + sw_s, sw_c = _run(sf, f, sched, bins) + tr_s, tr_c = _run(sf, f, sched, bins; tag = FFT_TAG) + Test.@test sw_c == ref_c + Test.@test isapprox(sw_s, ref_s; rtol = 1e-9, atol = 1e-10) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test any(!iszero, tr_s) + end +end + +Test.@testset "the rectilinear transform equals the sweep and the pair loop" begin + Random.seed!(7300) + xs = range(0.0, step = 0.1, length = 9) + ys = [0.0, 0.13, 0.31, 0.5, 0.52, 0.9] + zs = [0.0, 0.2, 0.45, 0.6] + ws = range(0.0, step = 0.15, length = 7) + cases = ( + # (field axes in order, schedule) + ((xs, ys), SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), (ys,), (1, 2))), + ((ys, xs), SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), (ys,), (2, 1))), + ((ys, xs, zs), SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), (ys, zs), (2, 1, 3))), + ((xs, zs, ws), SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9, 7), (0.1, 0.15), (false, false)), + (zs,), (1, 3, 2))), + ) + for (axes, sched) in cases + Dg = length(axes) + dims = map(length, axes) + u = randn(Dg, dims...) + x = _grid_points(axes) + bins = _separated_bins(x, 7) + ops = Dg == 2 ? (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.L2T1SFType(), SFT.S3SFType()) : + (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType()) + for sf in ops + ref_s, ref_c = _reference(sf, x, reshape(u, Dg, :), bins) + sw_s, sw_c = _run(sf, u, sched, bins) + tr_s, tr_c = _run(sf, u, sched, bins; tag = FFT_TAG) + Test.@test sw_c == ref_c + Test.@test isapprox(sw_s, ref_s; rtol = 1e-10, atol = 1e-12) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + end + Test.@test sum(_run(SFT.L2SFType(), u, sched, [0.0, 1e3])[2]) == prod(dims) * (prod(dims) - 1) ÷ 2 + end + + # a periodic uniform direction wraps on both routes; the pair loop cannot be the oracle there, but + # the two routes must agree and every pair must be counted once + per = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((8,), (0.25,), (true,)), (zs,), (2, 1)) + u = randn(2, 4, 8) + bins = [0.0; collect(range(0.17, 1.3; length = 7))] + for sf in (SFT.L2SFType(), SFT.L3SFType(), SFT.T3SFType()) + sw_s, sw_c = _run(sf, u, per, bins) + tr_s, tr_c = _run(sf, u, per, bins; tag = FFT_TAG) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + end + Test.@test sum(_run(SFT.L2SFType(), u, per, [0.0, 1e3])[2]) == 32 * 31 ÷ 2 + + # a scalar multi-field on a stretched grid + th = randn(4, 8) + f = Fields(vectors = (u,), scalars = (th,)) + for sf in (SFT.MixedSFType{1, 0, 1}(), SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{3}()) + sw_s, sw_c = _run(sf, f, per, bins) + tr_s, tr_c = _run(sf, f, per, bins; tag = FFT_TAG) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test any(!iszero, sw_s) + end +end + +Test.@testset "culling the slab pairs and the lags changes nothing but the work" begin + n_lon, lats = 12, collect(range(-1.2, 1.2; length = 9)) + dlon = 2π / n_lon + Random.seed!(7400) + u = randn(2, n_lon, length(lats)) + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, 1.0, true) + tight = collect(range(0.0, 0.12π; length = 5)) + x, uu = _zonal_points(lats, n_lon, dlon, u) + ref_s, ref_c = _reference(SFT.L2SFType(), x, uu, tight; metric = SFH.SphericalDistance(1.0)) + sw_s, sw_c = _run(SFT.L2SFType(), u, sched, tight) + tr_s, tr_c = _run(SFT.L2SFType(), u, sched, tight; tag = FFT_TAG) + Test.@test sw_c == ref_c + Test.@test isapprox(sw_s, ref_s; rtol = 1e-9, atol = 1e-10) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test sum(sw_c) > 0 + n_lat = length(lats) + Test.@test length(SFC.sweep_items(sched, 0.12π, 1, false)) < n_lat * (n_lat + 1) ÷ 2 # rows skipped + Test.@test SFC.lag_limits(sched, 1, 1, 0.12π)[1] < n_lon ÷ 2 # lags skipped + # the equator row keeps the fewest offsets, a pole-side row the most + Test.@test SFC.lag_limits(sched, 5, 5, 0.12π)[1] <= SFC.lag_limits(sched, 1, 1, 0.12π)[1] + Test.@test SFC.lag_limits(sched, 0.12π)[1] >= maximum(I -> SFC.lag_limits(sched, I, I, 0.12π)[1], 1:n_lat) + + ys = [0.0, 0.13, 0.31, 0.5, 0.52, 0.9, 1.4, 1.5] + rect = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), (ys,), (1, 2)) + ur = randn(2, 9, length(ys)) + xr = _grid_points((range(0.0, step = 0.1, length = 9), ys)) + tight_r = _separated_bins(xr, 20)[1:5] + ref_s, ref_c = _reference(SFT.L2SFType(), xr, reshape(ur, 2, :), tight_r) + sw_s, sw_c = _run(SFT.L2SFType(), ur, rect, tight_r) + tr_s, tr_c = _run(SFT.L2SFType(), ur, rect, tight_r; tag = FFT_TAG) + Test.@test sw_c == ref_c + Test.@test isapprox(sw_s, ref_s; rtol = 1e-10, atol = 1e-12) + Test.@test tr_c == sw_c + Test.@test _close(tr_s, sw_s) + Test.@test length(SFC.sweep_items(rect, last(tight_r), 1, false)) < 8 * 9 ÷ 2 +end + +Test.@testset "the threaded backend gives the serial answer" begin + n_lon, lats = 12, [-0.9, -0.5, -0.3, 0.1, 0.35, 0.8] + dlon = 2π / n_lon + Random.seed!(7500) + u = randn(2, n_lon, length(lats)) + bins = collect(range(0.0, 0.5π; length = 8)) + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, 1.0, true) + for tag in (nothing, FFT_TAG), backend in (CB.ThreadedBackend(), CB.AutoBackend()) + ser_s, ser_c = _run(SFT.L3SFType(), u, sched, bins; tag) + thr_s, thr_c = _run(SFT.L3SFType(), u, sched, bins; tag, backend) + Test.@test thr_c == ser_c + Test.@test _close(thr_s, ser_s) + end + # a single-slab schedule splits its lags across the tasks instead + uni = SFC.UniformLagSchedule((9, 7), (0.1, 0.15), (false, true)) + uu = randn(2, 9, 7) + ubins = [0.0; collect(range(0.0937, 1.1; length = 7))] + Test.@test length(SFC.sweep_items(uni, 1.1, 4, true)) == 4 + for tag in (nothing, FFT_TAG) + ser_s, ser_c = _run(SFT.L2SFType(), uu, uni, ubins; tag) + thr_s, thr_c = _run(SFT.L2SFType(), uu, uni, ubins; tag, backend = CB.ThreadedBackend()) + Test.@test thr_c == ser_c + Test.@test _close(thr_s, ser_s) + end + # the joint histogram too + src = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0)) + ax_bins = [prevfloat(0.0); collect(range(0.3011, π - 0.3; length = 5)); π + 1e-9] + na = length(ax_bins) - 1 + nb = length(ubins) - 1 + rect = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), ([0.0, 0.13, 0.31, 0.5, 0.52, 0.9, 1.4],), (1, 2)) + ur = randn(2, 9, 7) + ss = zeros(nb, na); sc = zeros(Float64, nb, na) + SFC.gridded_lag_sweep!(ss, sc, SFT.L2SFType(), ur, rect, ubins, ax_bins, Val(2); second_axis = src) + ts = zeros(nb, na); tc = zeros(Float64, nb, na) + SFC.gridded_sweep!(ts, tc, SFT.L2SFType(), ur, rect, ubins, ax_bins, Val(2), FFT_TAG; + second_axis = src, backend = CB.ThreadedBackend()) + hs = zeros(nb, na); hc = zeros(Float64, nb, na) + SFC.gridded_lag_sweep!(hs, hc, SFT.L2SFType(), ur, rect, ubins, ax_bins, Val(2); + second_axis = src, backend = CB.ThreadedBackend()) + Test.@test tc == sc + Test.@test hc == sc + Test.@test _close(ts, ss) + Test.@test _close(hs, ss) + Test.@test sum(sc) > 0 + # a GPU tag has no gridded method, and says so + Test.@test_throws ArgumentError _run(SFT.L2SFType(), u, sched, bins; backend = CB.GPUBackend(nothing)) +end + +Test.@testset "the sphere's radius reaches every route" begin + a = (0.3, -0.2) + b = (1.1, 0.4) + Test.@test SFH.SphericalDistance(RE)(a, b) == RE * DI.SphericalAngle()(a, b) + Test.@test SFH.pair_geometry_for(SFH.SphericalDistance(RE), Val(2)) isa SFH.SphericalGeometry{2} + Test.@test SFH.pair_geometry_for(SFH.SphericalDistance(RE), Val(2)).radius == RE + + # the unstructured entry with the radius in the metric equals the unit sphere with scaled bins + n_lon, lats = 12, collect(range(-0.6, 0.6; length = 5)) + dlon = 2π / n_lon + Random.seed!(7600) + u = randn(2, n_lon, length(lats)) + x, uu = _zonal_points(lats, n_lon, dlon, u) + unit_bins = collect(range(0.0, 2.5; length = 7)) + s1, c1 = _reference(SFT.L2SFType(), x, uu, unit_bins; metric = DI.SphericalAngle()) + s2, c2 = _reference(SFT.L2SFType(), x, uu, RE .* unit_bins; metric = SFH.SphericalDistance(RE)) + Test.@test c1 == c2 + Test.@test isapprox(s1, s2; rtol = 1e-12) + + # through the grid entry: the same field on a range longitude axis (zonal schedule) and on a vector + # one (enumerated pairs) reports the same separations in metres + geo = FG.Geometry.SphericalGeometry(RE) + lam = range(0.0, step = dlon, length = n_lon) + phi = range(-0.6, 0.6; length = length(lats)) + zonal = FG.Grids.StructuredGrid(geo, lam, phi) + scattered = FG.Grids.StructuredGrid(geo, collect(lam), phi) + ext = Base.get_extension(SF, :StructureFunctionsFlowGeometriesExt) + Test.@test Base.invokelatest(ext._lag_schedule, zonal) isa SFC.ZonalLagSchedule + Test.@test Base.invokelatest(ext._lag_schedule, scattered) isa SFC.ScatteredPairs + Test.@test Base.invokelatest(ext._lag_schedule, scattered).metric == SFH.SphericalDistance(RE) + metre_bins = RE .* collect(range(0.0, 1.9; length = 8)) + rz = SFC.calculate_structure_function(SFT.L2SFType(), zonal, u, metre_bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + rs = SFC.calculate_structure_function(SFT.L2SFType(), scattered, u, metre_bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test rz.counts == rs.counts + Test.@test isapprox(rz.sums, rs.sums; rtol = 1e-9, atol = 1e-10) + Test.@test sum(rz.counts) > 0 + Test.@test count(!iszero, rz.counts) > 1 # the bins really are in metres +end + +Test.@testset "axis types decide the route, and the routes agree" begin + ext = Base.get_extension(SF, :StructureFunctionsFlowGeometriesExt) + sched_of(grid) = Base.invokelatest(ext._lag_schedule, grid) + + # a lat-lon sampling built from a recipe stores its axes as vectors, so it enumerates pairs; the + # same nodes given as ranges take the zonal schedule; the answers agree + n_lon, n_lat = 10, 5 + geo = FG.Geometry.SphericalGeometry(1.0) + recipe = FG.Connectivity.structured_grid(FG.SphericalSampling.LatLonSampling(), n_lat; + geometry = geo, nlon = n_lon) + ranged = FG.Grids.StructuredGrid(geo, range(0.0, step = 2π / n_lon, length = n_lon), + range(-π / 2, π / 2; length = n_lat)) + Test.@test sched_of(recipe) isa SFC.ScatteredPairs + Test.@test sched_of(ranged) isa SFC.ZonalLagSchedule + Random.seed!(7700) + u = randn(2, n_lon, n_lat) + bins = collect(range(0.013, 0.9π; length = 7)) + r1 = SFC.calculate_structure_function(SFT.L2SFType(), recipe, u, bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + r2 = SFC.calculate_structure_function(SFT.L2SFType(), ranged, u, bins; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test r1.counts == r2.counts + Test.@test isapprox(r1.sums, r2.sums; rtol = 1e-9, atol = 1e-10) + Test.@test sum(r1.counts) > 0 + + # Cartesian: one uniform axis keeps its lags, none enumerates, and a wrapping coordinate list is refused + cgeo = FG.Geometry.CartesianGeometry() + xs = [0.0, 0.1, 0.35, 0.8, 0.85] + ys = range(0.0, step = 0.2, length = 4) + Test.@test sched_of(FG.Grids.StructuredGrid(cgeo, xs, ys)) isa SFC.RectilinearLagSchedule{1, 1, 2} + Test.@test sched_of(FG.Grids.StructuredGrid(cgeo, ys, xs)) isa SFC.RectilinearLagSchedule{1, 1, 2} + Test.@test sched_of(FG.Grids.StructuredGrid(cgeo, xs, collect(ys))) isa SFC.ScatteredPairs + Test.@test sched_of(FG.Grids.StructuredGrid(cgeo, ys, ys)) isa SFC.UniformLagSchedule + Test.@test_throws ArgumentError sched_of(FG.Grids.StructuredGrid(cgeo, xs, ys; + topology = (FG.Grids.Periodic(), FG.Grids.Bounded()))) + Test.@test_throws ArgumentError sched_of(FG.Grids.StructuredGrid(cgeo, xs, collect(ys); + topology = (FG.Grids.Bounded(), FG.Grids.Periodic()))) + # and the field's axis order is honoured whichever axis is uniform + grid_yx = FG.Grids.StructuredGrid(cgeo, ys, xs) + u_yx = randn(2, length(ys), length(xs)) + x_yx = _grid_points((ys, xs)) + bins_yx = _separated_bins(x_yx, 6) + got = SFC.calculate_structure_function(SFT.L3SFType(), grid_yx, u_yx, bins_yx, UInt32, FFT_TAG; + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + ref_s, ref_c = _reference(SFT.L3SFType(), x_yx, reshape(u_yx, 2, :), bins_yx) + Test.@test got.counts == ref_c + Test.@test _close(got.sums, ref_s) +end + +Test.@testset "the transform tag is served wherever there is a lag, and refused where there is none" begin + Random.seed!(7800) + n_lon, lats = 12, [-0.9, -0.5, -0.3, 0.1, 0.35, 0.8] + sched = SFC.ZonalLagSchedule(lats, n_lon, 2π / n_lon, 1.0, true) + u = randn(2, n_lon, length(lats)) + bins = collect(range(0.0, 0.5π; length = 8)) + au_s, au_c = _run(SFT.L2SFType(), u, sched, bins; tag = SB.AutoSpectralBackend()) + sw_s, sw_c = _run(SFT.L2SFType(), u, sched, bins) + Test.@test au_c == sw_c + Test.@test _close(au_s, sw_s) + ds_s, ds_c = _run(SFT.L2SFType(), u, sched, bins; tag = SB.DirectSumSpectralBackend()) + Test.@test ds_c == sw_c + Test.@test ds_s == sw_s + # a norm is no polynomial, on this schedule as on any + Test.@test_throws ArgumentError _run(SFT.FullVectorStructureFunctionType{3}(), u, sched, bins; tag = FFT_TAG) + # no uniform direction, no transform + pts = randn(2, 20) + scat = SFC.ScatteredPairs(pts, DI.Euclidean()) + err = try + SFC.gridded_sweep!(zeros(3), zeros(Int, 3), SFT.L2SFType(), reshape(randn(2, 20), 2, :), scat, + [0.0, 1.0, 2.0, 3.0], Val(2), Val(1), Val(0), FFT_TAG) + nothing + catch e + e + end + Test.@test err isa ArgumentError + Test.@test occursin("ScatteredPairs", err.msg) + # the angle-resolved histogram has no meaning on a sphere, on either route + src = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0)) + ax = [prevfloat(0.0), 1.0, 2.0, π + 1e-9] + Test.@test_throws ArgumentError SFC.gridded_sweep!(zeros(7, 3), zeros(7, 3), SFT.L2SFType(), u, sched, + bins, ax, Val(2), FFT_TAG; second_axis = src) + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!(zeros(7, 3), zeros(7, 3), SFT.L2SFType(), u, sched, + bins, ax, Val(2); second_axis = src) +end + +Test.@testset "uniform_lag_box agrees with the lag limits it describes" begin + # A device launch indexes its work items by division on one lag box when a schedule answers + # `true`, and through the prefix sum of the pairs' box volumes when it answers `false`. A `true` + # that is not the truth silently drops every lag outside the first pair's box, so the trait is + # checked against `lag_limits` itself, on every schedule and at several radii. + lats = collect(range(-1.2, 1.2; length = 9)) + zonal = SFC.ZonalLagSchedule(lats, 16, 2π / 16, 1.0, true) + uniform = SFC.UniformLagSchedule((12, 10), (0.1, 0.2), (true, false)) + rect = SFC.RectilinearLagSchedule(SFC.UniformLagSchedule((9,), (0.1,), (false,)), + (collect(range(0.0, 1.0; length = 7)),), (2, 1)) + for s in (uniform, rect, zonal), r_max in (0.05, 0.3, 1.0, 3.0) + items = SFC.sweep_items(s, r_max, 1, false) + isempty(items) && continue + limits = unique(SFC.lag_limits(s, it[1], it[2], r_max) for it in items) + # the direction the device depends on: `true` must mean one box for every pair + SFC.uniform_lag_box(s) && Test.@test length(limits) == 1 + end + # and the sphere must answer `false`, because at a radius that saturates nothing a row pair near + # a pole reaches more longitude offsets than one at the equator + zonal_limits = unique(SFC.lag_limits(zonal, it[1], it[2], 0.3) + for it in SFC.sweep_items(zonal, 0.3, 1, false)) + Test.@test length(zonal_limits) > 1 + Test.@test SFC.uniform_lag_box(zonal) == false + Test.@test SFC.uniform_lag_box(uniform) && SFC.uniform_lag_box(rect) +end diff --git a/test/test_gridded_weights.jl b/test/test_gridded_weights.jl new file mode 100644 index 0000000..35b7a74 --- /dev/null +++ b/test/test_gridded_weights.jl @@ -0,0 +1,395 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO, HelperFunctions as SFH, HarmonicNodes +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using StaticArrays: StaticArrays as SA +using LinearAlgebra: LinearAlgebra as LA +using FFTW: FFTW +using SpectralBackends: SpectralBackends as SB +using FlowGeometries: FlowGeometries as FG +using KernelAbstractions: KernelAbstractions as KA +using OhMyThreads: OhMyThreads +using Random: Random + +const FFT_TAG = SB.FastFourierTransformSpectralBackend() +const SERIAL = CB.SerialBackend() +const THREADED = CB.ThreadedBackend() +const DEVICE = CB.GPUBackend(KA.CPU()) +const RAW = SF.StructureFunctionSumsAndCounts + +# One run on either gridded route from a packed field and a schedule, into Float64 counts. +function _weighted_run(sf, data, sched, bins, vD, vV, vK; valid = SFC.AllValid(), weights = nothing, + tag = nothing, backend = SERIAL) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + s = zeros(Float64, nb) + c = zeros(Float64, nb) + if tag === nothing + SFC.gridded_lag_sweep!(s, c, sf, data, sched, bins, vD, vV, vK; valid, weights, backend) + else + SFC.gridded_sweep!(s, c, sf, data, sched, bins, vD, vV, vK, tag; valid, weights, backend) + end + return s, c +end + +function _weighted_run(sf, f::Fields, sched, bins; weights = nothing, tag = nothing, backend = SERIAL) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + s = zeros(Float64, nb) + c = zeros(Float64, nb) + if tag === nothing + SFC.gridded_lag_sweep!(s, c, sf, f, sched, bins; weights, backend) + else + SFC.gridded_sweep!(s, c, sf, f, sched, bins, tag; weights, backend) + end + return s, c +end + +# The weighted pair statistic written out on flat points: Σ w_i w_j v_ij and Σ w_i w_j over the pairs +# each (lo, hi] bin holds. +function _flat_pair_loop(sf, x, u, bins, w) + nb = length(bins) - 1 + s = zeros(nb) + c = zeros(nb) + N = size(x, 2) + for i in 1:(N - 1), j in (i + 1):N + dx = x[:, j] .- x[:, i] + r = LA.norm(dx) + b = searchsortedfirst(bins, r) - 1 + 1 <= b <= nb || continue + ww = w[i] * w[j] + s[b] += ww * sf(u[:, j] .- u[:, i], dx ./ r) + c[b] += ww + end + return s, c +end + +# Grid coordinates as a point list, in the cell order the packed field uses. +function _grid_points(dims, spacing) + Dg = length(dims) + N = prod(dims) + x = zeros(Float64, Dg, N) + for (k, I) in enumerate(CartesianIndices(dims)), d in 1:Dg + x[d, k] = (I[d] - 1) * spacing[d] + end + return x +end + +# Bin edges between the separations a point set can produce, so no shell sits on an edge. +function _separated_bins(x, n_bins) + N = size(x, 2) + d = Float64[] + for i in 1:(N - 1), j in (i + 1):N + push!(d, LA.norm(x[:, j] .- x[:, i])) + end + sort!(d) + dist = Float64[d[1]] + for v in d + v - dist[end] > 1e-9 && push!(dist, v) + end + picks = unique(round.(Int, range(1, length(dist) - 1; length = n_bins))) + return [0.0; [(dist[k] + dist[k + 1]) / 2 for k in picks]] +end + +# The sphere's cells as the unstructured entry wants them: (λ, φ) in radians, flattened as the zonal +# sweep indexes cells. +function _sphere_points(lats, n_lon, dlon) + n_lat = length(lats) + x = Matrix{Float64}(undef, 2, n_lon * n_lat) + for j in 1:n_lat, i in 1:n_lon + k = i + (j - 1) * n_lon + x[1, k] = (i - 1) * dlon + x[2, k] = lats[j] + end + return x +end + +_close(a, b) = isapprox(a, b; rtol = 1e-9, atol = 1e-10 * max(1.0, maximum(abs, b))) + +# Bin averages agree where both are defined; an empty bin is NaN on both sides. +_same_average(a, b) = all(((x, y),) -> (isnan(x) && isnan(y)) || isapprox(x, y; rtol = 1e-9), zip(a, b)) + +const WEIGHT_OPS = (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.T3SFType(), + SFT.ProjectedStructureFunctionType{2, 2}()) + +Test.@testset "weights of one reproduce the unweighted results" begin + Random.seed!(9500) + dims, spacing = (9, 6), (0.1, 0.2) + N = prod(dims) + u = randn(2, dims...) + data = reshape(u, 2, N) + sched = SFC.UniformLagSchedule(dims, spacing, (false, false)) + x = _grid_points(dims, spacing) + bins = _separated_bins(x, 8) + ones_w = ones(N) + for sf in WEIGHT_OPS + ref_s, ref_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0)) + got_s, got_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0); weights = ones_w) + Test.@test got_s == ref_s + Test.@test got_c == ref_c + tr_s, tr_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0); tag = FFT_TAG) + tw_s, tw_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0); tag = FFT_TAG, weights = ones_w) + Test.@test _close(tw_s, tr_s) + Test.@test tw_c ≈ tr_c rtol = 1e-12 + for backend in (SERIAL, THREADED) + ref = SFC.calculate_structure_function(sf, x, data, bins, Float64; backend, verbose = false, + show_progress = false, output_type = RAW) + got = SFC.calculate_structure_function(sf, x, data, bins, Float64; backend, weights = ones_w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test got.sums == ref.sums + Test.@test got.counts == ref.counts + end + end + θ = randn(dims...) + f = Fields(vectors = (u,), scalars = (θ,)) + for sf in (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{2}(), SFT.VectorDotSFType(1, 1)), + backend in (SERIAL, THREADED) + + ref = SFC.calculate_structure_function(sf, x, f, bins, Float64; backend, verbose = false, + show_progress = false, output_type = RAW) + got = SFC.calculate_structure_function(sf, x, f, bins, Float64; backend, weights = ones_w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test got.sums == ref.sums + Test.@test got.counts == ref.counts + end +end + +Test.@testset "random weights equal the weighted pair loop on grids and points" begin + Random.seed!(9510) + for (dims, spacing, ops) in (((9, 6), (0.1, 0.2), WEIGHT_OPS), + ((5, 4, 4), (0.2, 0.25, 0.3), (SFT.L2SFType(), SFT.T3SFType(), SFT.S3SFType()))) + Dg = length(dims) + N = prod(dims) + u = randn(Dg, dims...) + data = reshape(u, Dg, N) + w = 0.5 .+ rand(N) + x = _grid_points(dims, spacing) + bins = _separated_bins(x, 8) + sched = SFC.UniformLagSchedule(dims, spacing, ntuple(_ -> false, Dg)) + for sf in ops + ref_s, ref_c = _flat_pair_loop(sf, x, data, bins, w) + Test.@test sum(ref_c) > 0 + for tag in (nothing, FFT_TAG) + got_s, got_c = _weighted_run(sf, data, sched, bins, Val(Dg), Val(1), Val(0); weights = w, tag) + Test.@test _close(got_s, ref_s) + Test.@test got_c ≈ ref_c rtol = 1e-11 + end + for backend in (SERIAL, THREADED) + got = SFC.calculate_structure_function(sf, x, data, bins, Float64; backend, weights = w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(got.sums, ref_s) + Test.@test got.counts ≈ ref_c rtol = 1e-11 + end + end + end +end + +Test.@testset "the weighted transform equals the weighted sweep with masks and wrapping, on the device too" begin + Random.seed!(9520) + for (dims, spacing, periodic) in (((8, 8), (0.25, 0.25), (true, true)), + ((10, 7), (0.15, 0.15), (true, false)), + ((6, 6, 4), (0.2, 0.2, 0.3), (true, false, true))) + Dg = length(dims) + N = prod(dims) + u = randn(Dg, dims...) + uf = reshape(u, Dg, N) + for k in 1:N + rand() < 0.3 && (uf[1, k] = NaN) + end + valid = SFC.field_validity(u) + Test.@test !(valid isa SFC.AllValid) + w = 0.5 .+ rand(N) + sched = SFC.UniformLagSchedule(dims, spacing, periodic) + bins = collect(range(0.0, 0.7 * sum(d -> spacing[d] * dims[d], 1:Dg); length = 9)) + for sf in (SFT.L2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.T3SFType(), + SFT.ProjectedStructureFunctionType{4, 0}()) + ref_s, ref_c = _weighted_run(sf, uf, sched, bins, Val(Dg), Val(1), Val(0); valid, weights = w) + Test.@test all(isfinite, ref_s) + Test.@test sum(ref_c) > 0 + for backend in (SERIAL, DEVICE) + got_s, got_c = _weighted_run(sf, uf, sched, bins, Val(Dg), Val(1), Val(0); + valid, weights = w, tag = FFT_TAG, backend) + Test.@test _close(got_s, ref_s) + Test.@test got_c ≈ ref_c rtol = 1e-11 + end + end + end +end + +Test.@testset "multi-fields carry weights on every route" begin + Random.seed!(9530) + dims, spacing = (9, 7), (0.1, 0.15) + N = prod(dims) + u = randn(2, dims...) + θ = randn(dims...) + a = randn(2, dims...) + x = _grid_points(dims, spacing) + bins = _separated_bins(x, 8) + w = 0.5 .+ rand(N) + sched = SFC.UniformLagSchedule(dims, spacing, (false, false)) + cases = ( + (Fields(vectors = (u,), scalars = (θ,)), + (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{2}(), SFT.MixedSFType{1, 0, 1}(), SFT.L2SFType())), + (Fields(vectors = (u, a)), (SFT.VectorDotSFType(1, 2), SFT.L2SFType())), + ) + for (f, ops) in cases, sf in ops + ref_s, ref_c = _weighted_run(sf, f, sched, bins; weights = w) + Test.@test sum(ref_c) > 0 + tr_s, tr_c = _weighted_run(sf, f, sched, bins; weights = w, tag = FFT_TAG) + Test.@test _close(tr_s, ref_s) + Test.@test tr_c ≈ ref_c rtol = 1e-11 + for backend in (SERIAL, THREADED) + got = SFC.calculate_structure_function(sf, x, f, bins, Float64; backend, weights = w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(got.sums, ref_s) + Test.@test got.counts ≈ ref_c rtol = 1e-11 + end + end +end + +Test.@testset "weights on the sphere: zonal sweep, transform, device and the point entry agree" begin + Random.seed!(9540) + n_lon, n_lat = 15, 7 + dlon = 2π / n_lon + lats = sort(0.9 .* (π .* rand(n_lat) .- π / 2)) + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, 1.0, true) + N = n_lon * n_lat + u = randn(2, n_lon, n_lat) + data = reshape(u, 2, N) + w = 0.5 .+ rand(N) + x = _sphere_points(lats, n_lon, dlon) + bins = collect(range(0.0, π; length = 8)) .+ 1e-3 + for sf in (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType()) + ref_s, ref_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0); weights = w) + Test.@test sum(ref_c) > 0 + for (tag, backend) in ((FFT_TAG, SERIAL), (FFT_TAG, DEVICE), (nothing, THREADED)) + got_s, got_c = _weighted_run(sf, data, sched, bins, Val(2), Val(1), Val(0); weights = w, tag, backend) + Test.@test _close(got_s, ref_s) + Test.@test got_c ≈ ref_c rtol = 1e-11 + end + for backend in (SERIAL, THREADED) + pts = SFC.calculate_structure_function(sf, x, data, bins, Float64; backend, weights = w, + distance_metric = SFH.SphericalDistance(1.0), verbose = false, + show_progress = false, output_type = RAW) + Test.@test _close(pts.sums, ref_s) + Test.@test pts.counts ≈ ref_c rtol = 1e-11 + end + end +end + +Test.@testset "cell_measure feeds a grid's cell areas as weights" begin + Random.seed!(9550) + geo = FG.Geometry.SphericalGeometry(1.0) + n_lon, n_lat = 15, 8 + lam = range(0.0, step = 2π / n_lon, length = n_lon) + phi = range(-π / 2 + π / (2n_lat), step = π / n_lat, length = n_lat) + grid = FG.Grids.StructuredGrid(geo, lam, phi) + w = SFC.cell_measure(grid) + N = n_lon * n_lat + Test.@test length(w) == N + Test.@test all(>(0), w) + Test.@test w[1] < w[n_lon * (n_lat ÷ 2) + 1] + u = randn(2, n_lon, n_lat) + bins = collect(range(0.0, π; length = 8)) .+ 1e-3 + got = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, Float64; weights = w, backend = SERIAL, + verbose = false, show_progress = false, output_type = RAW) + coords = FG.Grids.materialize(grid) + x = Matrix(hcat(coords[1], coords[2])') + ref = SFC.calculate_structure_function(SFT.L2SFType(), x, reshape(u, 2, N), bins, Float64; weights = w, + backend = SERIAL, distance_metric = SFH.SphericalDistance(1.0), + verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(got.sums, ref.sums) + Test.@test got.counts ≈ ref.counts rtol = 1e-11 + tr = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins, Float64, FFT_TAG; weights = w, + backend = SERIAL, verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(tr.sums, got.sums) + Test.@test tr.counts ≈ got.counts rtol = 1e-11 + plain = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, bins; backend = SERIAL, verbose = false, + show_progress = false, output_type = RAW) + Test.@test !(got.sums ./ got.counts ≈ plain.sums ./ plain.counts) + + # a Cartesian grid's cells are all alike, so its measure changes no average + cgrid = FG.Grids.StructuredGrid(FG.Geometry.CartesianGeometry(), range(0.0, step = 0.1, length = 7), + range(0.0, step = 0.2, length = 5)) + cw = SFC.cell_measure(cgrid) + Test.@test all(v -> v ≈ cw[1], cw) + uc = randn(2, 7, 5) + cbins = collect(range(0.0, 1.2; length = 7)) .+ 1e-3 + cgot = SFC.calculate_structure_function(SFT.L2SFType(), cgrid, uc, cbins, Float64; weights = cw, backend = SERIAL, + verbose = false, show_progress = false, output_type = RAW) + cplain = SFC.calculate_structure_function(SFT.L2SFType(), cgrid, uc, cbins; backend = SERIAL, verbose = false, + show_progress = false, output_type = RAW) + Test.@test _same_average(cgot.sums ./ cgot.counts, cplain.sums ./ cplain.counts) + Test.@test cgot.counts ≈ cplain.counts .* cw[1]^2 +end + +Test.@testset "area-weighted hard bins agree with the harmonic route's area average" begin + geo = FG.Geometry.SphericalGeometry(1.0) + n_lon, n_lat = 96, 48 + lam = range(0.0, step = 2π / n_lon, length = n_lon) + phi = range(-π / 2 + π / (2n_lat), step = π / n_lat, length = n_lat) + grid = FG.Grids.StructuredGrid(geo, lam, phi) + # the gradient of Φ = cos²φ cos 2λ, a degree-2 harmonic: u_E = ∂_λΦ / cos φ, u_N = ∂_φΦ + u = Array{Float64}(undef, 2, n_lon, n_lat) + for (j, φ) in enumerate(phi), (i, λ) in enumerate(lam) + u[1, i, j] = -2 * cos(φ) * sin(2λ) + u[2, i, j] = -2 * cos(φ) * sin(φ) * cos(2λ) + end + w = SFC.cell_measure(grid) + nodes = HarmonicNodes(24, 48; taper = SF.GaussianTaper(π / 48)) + harm = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, nodes, SB.DirectSumSpectralBackend(); + verbose = false, output_type = RAW) + β = nodes.separations + half = 0.04 + edges = sort(vcat(0.0, β .- half, β .+ half)) + zon = SFC.calculate_structure_function(SFT.L2SFType(), grid, u, edges, Float64; weights = w, backend = SERIAL, + verbose = false, show_progress = false, output_type = RAW) + hard = zon.sums ./ zon.counts + soft = harm.sums ./ harm.counts + compared = 0 + for (k, b) in enumerate(β) + 0.7 <= b <= 2.4 || continue + Test.@test isapprox(hard[2k], soft[k]; rtol = 4e-2) + compared += 1 + end + Test.@test compared >= 8 +end + +Test.@testset "weights are refused where they cannot be honoured" begin + Random.seed!(9560) + dims, spacing = (6, 5), (0.1, 0.1) + N = prod(dims) + u = randn(2, dims...) + data = reshape(u, 2, N) + sched = SFC.UniformLagSchedule(dims, spacing, (false, false)) + bins = collect(range(0.0, 0.5; length = 5)) + w = 0.5 .+ rand(N) + s = zeros(4) + L2 = SFT.L2SFType() + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!(s, zeros(Int, 4), L2, data, sched, bins, Val(2), Val(1), + Val(0); weights = w) + Test.@test_throws DimensionMismatch SFC.gridded_lag_sweep!(s, zeros(4), L2, data, sched, bins, Val(2), Val(1), + Val(0); weights = w[1:(end - 1)]) + bad = copy(w) + bad[3] = NaN + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!(s, zeros(4), L2, data, sched, bins, Val(2), Val(1), Val(0); + weights = bad) + Test.@test_throws ArgumentError SFC.gridded_sweep!(s, zeros(Int, 4), L2, data, sched, bins, Val(2), Val(1), Val(0), + FFT_TAG; weights = w) + x = _grid_points(dims, spacing) + Test.@test_throws ArgumentError SFC.calculate_structure_function(L2, x, data, bins; weights = w, backend = SERIAL, + verbose = false, show_progress = false) + Test.@test_throws ArgumentError SFC.calculate_structure_function(L2, x, data, bins, Float64; weights = w, + backend = DEVICE, verbose = false, + show_progress = false) + Test.@test_throws ArgumentError SFC.calculate_structure_function(L2, x, data, bins, Float64; weights = w, + backend = CB.DistributedBackend(), + verbose = false, show_progress = false) + Test.@test_throws ArgumentError SFC.calculate_structure_function(L2, x, data, bins, + collect(range(-3.0, 3.0; length = 5)), Float64; + weights = w, backend = SERIAL, verbose = false, + show_progress = false) + grid = FG.Grids.StructuredGrid(FG.Geometry.CartesianGeometry(), range(0.0, step = 0.1, length = 6), + range(0.0, step = 0.1, length = 5)) + Test.@test_throws ArgumentError SFC.calculate_structure_function(L2, grid, u, bins; weights = SFC.cell_measure(grid), + verbose = false, show_progress = false) +end diff --git a/test/test_gridded_zonal.jl b/test/test_gridded_zonal.jl index 5e94052..a5eb584 100644 --- a/test/test_gridded_zonal.jl +++ b/test/test_gridded_zonal.jl @@ -1,11 +1,14 @@ using Test: Test using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, HelperFunctions as SFH +using StructureFunctions: MultiFields as MF using StaticArrays: StaticArrays as SA using Distances: Distances as DI using LinearAlgebra: dot using Random: Random using FlowGeometries: FlowGeometries as FG +using SpectralBackends: SpectralBackends as SB +using FFTW: FFTW # `Distances.SphericalAngle` reports the central angle itself, so the geometry it implies has # unit radius; the schedule must be built on the same sphere for the comparison to mean anything. @@ -30,6 +33,19 @@ function _zonal_points(lats, n_lon, dlon, u) return x, uu end +# The field carried by the equatorial reflection `φ ↦ −φ`, on a latitude axis symmetric about the +# equator so the reflection maps the grid onto itself. The reflection's differential keeps east and +# reverses north, so the components mirror as `(u_E, −u_N)` with the latitude index reversed. +function _equator_mirror(u::AbstractArray{T, 3}) where {T} + n_lon, n_lat = size(u, 2), size(u, 3) + m = similar(u) + for j in 1:n_lat, i in 1:n_lon + m[1, i, j] = u[1, i, n_lat + 1 - j] + m[2, i, j] = -u[2, i, n_lat + 1 - j] + end + return m +end + Test.@testset "the geodesic frame does not depend on longitude" begin # The claim the whole zonal path rests on, checked against pair_frame itself. g = SFH.SphericalGeometry{2}(DI.SphericalAngle(), 1.0) @@ -71,7 +87,7 @@ Test.@testset "the zonal sweep equals the unstructured spherical path" begin got_s = zeros(nb); got_c = zeros(Int, nb) SFC.gridded_lag_sweep!(got_s, got_c, sf, u, sched, bins, Val(2)) ref_s = zeros(nb); ref_c = zeros(Int, nb) - SF.calculate_structure_function!(ref_s, ref_c, sf, x, uu, bins; + SFC.calculate_structure_function!(ref_s, ref_c, sf, x, uu, bins; distance_metric = DI.SphericalAngle()) Test.@test got_c == ref_c Test.@test isapprox(got_s, ref_s; rtol = 1e-9, atol = 1e-10) @@ -80,6 +96,62 @@ Test.@testset "the zonal sweep equals the unstructured spherical path" begin end end +Test.@testset "odd scalar moments on a lat-lon grid read south to north, then west to east" begin + # ⟨δu_L δθ⟩ changes sign when a pair is read from its other end; the zonal sweep and the + # unstructured spherical field path must read every pair the same way. An odd longitude count: + # two points exactly half a turn apart on one parallel have no first end, which the lattice knows + # from the integer offset while a point path sees sin(π) as round-off. + n_lon, lats = 11, collect(range(-0.6, 0.6; length = 5)) + n_lat = length(lats) + dlon = 2π / n_lon + Random.seed!(9150) + u = randn(2, n_lon, n_lat) + th = randn(n_lon, n_lat) + x, uu = _zonal_points(lats, n_lon, dlon, u) + f_grid = MF.Fields(vectors = (u,), scalars = (th,)) + f_pts = MF.Fields(vectors = (uu,), scalars = (vec(th),)) + bins = collect(range(0.0, 0.45 * π; length = 7)) + nb = length(bins) - 1 + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, R_UNIT, true) + for sf in (SFT.MixedSFType{1, 0, 1}(), SFT.ScalarSFType{3}(), SFT.MixedSFType{1, 0, 2}()) + got_s = zeros(nb); got_c = zeros(Int, nb) + SFC.gridded_lag_sweep!(got_s, got_c, sf, f_grid, sched, bins) + ref = SFC.calculate_structure_function(sf, x, f_pts, bins; distance_metric = DI.SphericalAngle(), + output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test got_c == Int.(ref.counts) + Test.@test isapprox(got_s, ref.sums; rtol = 1e-9, atol = 1e-10) + Test.@test any(!iszero, got_s) + end +end + +Test.@testset "a descending axis reads pairs the same way as an ascending one" begin + # The reading is fixed by the points, not by the order the grid stores them in: a grid whose + # latitudes run north to south, or whose longitudes run westward, must agree with the point path. + n_lon = 11 + Random.seed!(9160) + for (lats, dlon) in ((collect(range(0.6, -0.6; length = 5)), 2π / n_lon), + (collect(range(-0.6, 0.6; length = 5)), -2π / n_lon)) + n_lat = length(lats) + u = randn(2, n_lon, n_lat) + th = randn(n_lon, n_lat) + x, uu = _zonal_points(lats, n_lon, dlon, u) + f_grid = MF.Fields(vectors = (u,), scalars = (th,)) + f_pts = MF.Fields(vectors = (uu,), scalars = (vec(th),)) + bins = collect(range(0.0, 0.45 * π; length = 7)) + nb = length(bins) - 1 + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, R_UNIT, true) + for sf in (SFT.MixedSFType{1, 0, 1}(), SFT.ScalarSFType{3}()) + got_s = zeros(nb); got_c = zeros(Int, nb) + SFC.gridded_lag_sweep!(got_s, got_c, sf, f_grid, sched, bins) + ref = SFC.calculate_structure_function(sf, x, f_pts, bins; distance_metric = DI.SphericalAngle(), + output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test got_c == Int.(ref.counts) + Test.@test isapprox(got_s, ref.sums; rtol = 1e-9, atol = 1e-10) + Test.@test any(!iszero, got_s) + end + end +end + Test.@testset "the zonal sweep counts every pair once" begin n_lon = 10 lats = collect(range(-0.4, 0.4; length = 4)) @@ -121,7 +193,7 @@ Test.@testset "latitude-pair culling changes nothing but the work" begin SFC.gridded_lag_sweep!(st, ct, SFT.L2SFType(), u, sched, tight, Val(2)) x, uu = _zonal_points(lats, n_lon, dlon, u) rt_s = zeros(5); rt_c = zeros(Int, 5) - SF.calculate_structure_function!(rt_s, rt_c, SFT.L2SFType(), x, uu, tight; + SFC.calculate_structure_function!(rt_s, rt_c, SFT.L2SFType(), x, uu, tight; distance_metric = DI.SphericalAngle()) Test.@test ct == rt_c Test.@test isapprox(st, rt_s; rtol = 1e-9, atol = 1e-10) @@ -140,7 +212,7 @@ Test.@testset "the zonal sweep honours missing cells" begin for k in (3, 17, 28) uf[1, k] = NaN end - valid = SFC.field_validity(u, Val(2)) + valid = SFC.field_validity(u) sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, R_UNIT, true) bins = collect(range(0.0, 10.0; length = 4)) s = zeros(3); c = zeros(Int, 3) @@ -227,7 +299,7 @@ Test.@testset "a spherical grid reaches the zonal sweep through the public entry verbose = false, show_progress = false) x, uu = _zonal_points(collect(phi), n_lon, 2π / n_lon, u) ref_s = zeros(8); ref_c = zeros(UInt32, 8) - SF.calculate_structure_function!(ref_s, ref_c, SFT.L2SFType(), x, uu, bins; + SFC.calculate_structure_function!(ref_s, ref_c, SFT.L2SFType(), x, uu, bins; distance_metric = DI.SphericalAngle()) Test.@test got.counts == ref_c Test.@test isapprox(got.sums, ref_s; rtol = 1e-9, atol = 1e-10) @@ -257,9 +329,68 @@ Test.@testset "a spherical grid reaches the zonal sweep through the public entry xs[2, k] = phi[I[2]] end ref_str_s = zeros(8); ref_str_c = zeros(UInt32, 8) - SF.calculate_structure_function!(ref_str_s, ref_str_c, SFT.L2SFType(), xs, + SFC.calculate_structure_function!(ref_str_s, ref_str_c, SFT.L2SFType(), xs, reshape(us, 2, 4 * n_lat), bins; distance_metric = DI.SphericalAngle()) Test.@test r_str.counts == ref_str_c Test.@test isapprox(r_str.sums, ref_str_s; rtol = 1e-9, atol = 1e-10) end + +Test.@testset "the equatorial reflection flips exactly the odd-transverse operators" begin + # The reflection `φ ↦ −φ` is an isometry of the sphere that reverses orientation. It carries each + # pair's geodesic to the mirrored pair's, so every longitudinal increment is preserved, while the + # transverse basis vector `p̂ × ê₁` picks up the reflection's determinant and every transverse + # increment is negated. An operator's parity under the reflection is therefore the parity of its + # transverse degree, and a latitude axis symmetric about the equator maps the grid onto itself, + # so the two sweeps fill the same bins with the same counts. + tag = SB.FastFourierTransformSpectralBackend() + ops = ((SFT.L2SFType(), 1), (SFT.T2SFType(), 1), (SFT.S2SFType(), 1), (SFT.L3SFType(), 1), + (SFT.S3SFType(), 1), (SFT.L1T2SFType(), 1), (SFT.T3SFType(), -1), (SFT.L2T1SFType(), -1)) + for lats in ([-1.0, -0.6, -0.25, 0.25, 0.6, 1.0], [-0.8, -0.3, 0.0, 0.3, 0.8]) + # An odd longitude count: on a latitude axis symmetric about the equator an even one puts + # exactly antipodal pairs on the grid, and those carry a separation but no direction, which + # the lattice reads off the integer lag while a point path sees as round-off. The reflection + # law holds either way; the three routes are only comparable without them. + n_lon = 11 + dlon = 2π / n_lon + n_lat = length(lats) + Random.seed!(9400 + n_lat) + u = randn(2, n_lon, n_lat) + um = _equator_mirror(u) + x, uu = _zonal_points(lats, n_lon, dlon, u) + xm, uum = _zonal_points(lats, n_lon, dlon, um) + bins = collect(range(0.0, 0.8 * π; length = 9)) + nb = length(bins) - 1 + sched = SFC.ZonalLagSchedule(lats, n_lon, dlon, R_UNIT, true) + for (sf, parity) in ops + s0 = zeros(nb); c0 = zeros(Int, nb) + SFC.gridded_lag_sweep!(s0, c0, sf, u, sched, bins, Val(2)) + s1 = zeros(nb); c1 = zeros(Int, nb) + SFC.gridded_lag_sweep!(s1, c1, sf, um, sched, bins, Val(2)) + scale = maximum(abs, s0) + Test.@test c1 == c0 + Test.@test any(!iszero, s0) + Test.@test isapprox(s1, parity .* s0; rtol = 1e-10, atol = 1e-11 * scale) + + # the transform reads the same frames out of lag space + t0 = zeros(nb); tc0 = zeros(Int, nb) + SFC.gridded_sweep!(t0, tc0, sf, u, sched, bins, Val(2), tag) + t1 = zeros(nb); tc1 = zeros(Int, nb) + SFC.gridded_sweep!(t1, tc1, sf, um, sched, bins, Val(2), tag) + Test.@test tc1 == tc0 == c0 + Test.@test isapprox(t1, parity .* t0; rtol = 1e-10, atol = 1e-11 * scale) + Test.@test isapprox(t0, s0; rtol = 1e-10, atol = 1e-11 * scale) + + # the point path builds its frames from `pair_frame`, not from the zonal transport + p0 = zeros(nb); pc0 = zeros(Int, nb) + SFC.calculate_structure_function!(p0, pc0, sf, x, uu, bins; + distance_metric = DI.SphericalAngle()) + p1 = zeros(nb); pc1 = zeros(Int, nb) + SFC.calculate_structure_function!(p1, pc1, sf, xm, uum, bins; + distance_metric = DI.SphericalAngle()) + Test.@test pc1 == pc0 == c0 + Test.@test isapprox(p1, parity .* p0; rtol = 1e-10, atol = 1e-11 * scale) + Test.@test isapprox(p0, s0; rtol = 1e-9, atol = 1e-10 * scale) + end + end +end diff --git a/test/test_harmonic_sphere.jl b/test/test_harmonic_sphere.jl new file mode 100644 index 0000000..da95f1e --- /dev/null +++ b/test/test_harmonic_sphere.jl @@ -0,0 +1,448 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO, HelperFunctions as SFH, HarmonicNodes +using StructureFunctions.MultiFields: Fields +using SpectralBackends: SpectralBackends as SB +using NUFSHT: NUFSHT +using NonuniformFFTs: NonuniformFFTs +using FlowGeometries: FlowGeometries as FG +using Distances: Distances as DI +using StaticArrays: StaticArrays as SA +using LinearAlgebra: dot, cross +using Random: Random + +const DS = SB.DirectSumSpectralBackend() +const NU = SB.NUFSHTSpectralBackend() + +# Wigner's explicit sum, independent of the recurrence under test. +function _wigner_explicit(j, mp, m, β) + (abs(mp) > j || abs(m) > j) && return 0.0 + c, s = cos(β / 2), sin(β / 2) + f(n) = factorial(big(n)) + pref = sqrt(f(j + mp) * f(j - mp) * f(j + m) * f(j - m)) + tot = big(0.0) + for k in max(0, m - mp):min(j + m, j - mp) + tot += (-1)^(mp - m + k) * big(c)^(2j + m - mp - 2k) * big(s)^(mp - m + 2k) / + (f(j + m - k) * f(k) * f(mp - m + k) * f(j - mp - k)) + end + return Float64(pref * tot) +end + +# A band-limited test field: the surface gradient of the degree-2 potential Φ = 0.7xy + 0.3xz + 0.5x + +# 0.6(3z² − 1)/2, and its curl p̂ × ∇Φ, in (east, north) components; and a scalar of degree 2. +function _field_at(p::SA.SVector{3}) + grad = SA.SVector(0.7p[2] + 0.3p[3] + 0.5, 0.7p[1], 0.3p[1] + 1.8p[3]) + return grad - dot(grad, p) * p +end +_scalar_at(p::SA.SVector{3}) = 0.9p[1] * p[2] - 0.4p[3] + 0.5 * (3p[3]^2 - 1) / 2 +_east(lon, lat) = SA.SVector(-sin(lon), cos(lon), 0.0) +_north(lon, lat) = SA.SVector(-sin(lat) * cos(lon), -sin(lat) * sin(lon), cos(lat)) +_position(lon, lat) = SA.SVector(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat)) + +# Gauss–Legendre grid with exact quadrature weights, and the test fields on it. +function _gl_grid(nlat, nlon) + μ, wμ = SF.gauss_legendre(nlat) + lats = asin.(μ) + lons = (0:(nlon - 1)) .* (2π / nlon) + N = nlat * nlon + x = Matrix{Float64}(undef, 2, N) + w = Vector{Float64}(undef, N) + ug = Matrix{Float64}(undef, 2, N) + uc = Matrix{Float64}(undef, 2, N) + Φ = Vector{Float64}(undef, N) + k = 0 + for j in 1:nlat, i in 1:nlon + k += 1 + lon, lat = lons[i], lats[j] + x[1, k] = lon + x[2, k] = lat + w[k] = wμ[j] * 2π / nlon + p = _position(lon, lat) + t = _field_at(p) + E, Nn = _east(lon, lat), _north(lon, lat) + ug[1, k], ug[2, k] = dot(t, E), dot(t, Nn) + c = cross(p, t) + uc[1, k], uc[2, k] = dot(c, E), dot(c, Nn) + Φ[k] = _scalar_at(p) + end + return x, w, ug, uc, Φ +end + +# Fibonacci points with the test fields. +function _fibonacci(N) + φg = (1 + sqrt(5)) / 2 + x = Matrix{Float64}(undef, 2, N) + u = Matrix{Float64}(undef, 2, N) + Φ = Vector{Float64}(undef, N) + for i in 1:N + lat = asin(1 - 2 * (i - 0.5) / N) + lon = mod(2π * i / φg, 2π) + x[1, i], x[2, i] = lon, lat + p = _position(lon, lat) + t = _field_at(p) + u[1, i], u[2, i] = dot(t, _east(lon, lat)), dot(t, _north(lon, lat)) + Φ[i] = _scalar_at(p) + end + return x, u, Φ +end + +# The continuous rotation average of `sf(δu)` over every pair at separation β, by a quadrature over +# the first point (Gauss–Legendre in latitude, uniform in longitude) and over the bearing of the +# geodesic to the second: exact for a band-limited field, since every integrand is a polynomial in +# the coordinates and a trigonometric polynomial in the angles. +function _rotation_average(sf, β; nlat = 40, nlon = 81, nα = 64, field = _field_at, scalar = false) + μ, wμ = SF.gauss_legendre(nlat) + acc = 0.0 + total = 0.0 + for j in 1:nlat, i in 1:nlon, a in 1:nα + lat = asin(μ[j]) + lon = (i - 1) * 2π / nlon + α = (a - 1) * 2π / nα + p = _position(lon, lat) + θ̂ = -_north(lon, lat) + φ̂ = _east(lon, lat) + tA = cos(α) * θ̂ + sin(α) * φ̂ # geodesic tangent at p, toward q + q = cos(β) * p + sin(β) * tA + tB = -sin(β) * p + cos(β) * tA # the geodesic's tangent at q, continuing + m̂ = cross(p, tA) + w = wμ[j] + if scalar + inc = SF.MultiFields.FieldIncrement{0, 0, 1, Float64}((), (_scalar_at(q) - _scalar_at(p),)) + acc += w * sf(inc, SA.SVector(1.0, 0.0)) + else + uA, uB = field(p), field(q) + δu = SA.SVector(dot(uB, tB) - dot(uA, tA), dot(uB - uA, m̂)) + acc += w * sf(δu, SA.SVector(1.0, 0.0)) + end + total += w + end + return acc / total +end + +# `_rotation_average` for the mixed operator needs the scalar with the vector. +function _rotation_average(sf::SFT.MixedStructureFunctionType, β; nlat = 40, nlon = 81, nα = 64) + μ, wμ = SF.gauss_legendre(nlat) + acc = 0.0 + total = 0.0 + for j in 1:nlat, i in 1:nlon, a in 1:nα + lat = asin(μ[j]) + lon = (i - 1) * 2π / nlon + α = (a - 1) * 2π / nα + p = _position(lon, lat) + tA = cos(α) * (-_north(lon, lat)) + sin(α) * _east(lon, lat) + q = cos(β) * p + sin(β) * tA + tB = -sin(β) * p + cos(β) * tA + m̂ = cross(p, tA) + uA, uB = _field_at(p), _field_at(q) + δu = SA.SVector(dot(uB, tB) - dot(uA, tA), dot(uB - uA, m̂)) + inc = SF.MultiFields.FieldIncrement{2, 1, 1, Float64}((δu,), (_scalar_at(q) - _scalar_at(p),)) + acc += wμ[j] * sf(inc, SA.SVector(1.0, 0.0)) + total += wμ[j] + end + return acc / total +end + +Test.@testset "the Wigner-d recurrence agrees with the explicit formula and the tables" begin + worst = 0.0 + for β in (0.0, 0.3, 1.2, 2.5, π), m in -3:3, n in -3:3 + col = SFC.wigner_d_column(m, n, β, 12) + for l in 0:12 + worst = max(worst, abs(col[l + 1] - _wigner_explicit(l, m, n, β))) + end + end + Test.@test worst < 1e-13 + β = 0.7 + c, s = cos(β), sin(β) + Test.@test SFC.wigner_d_column(1, 1, β, 2)[2:3] ≈ [(1 + c) / 2, (2c^2 + c - 1) / 2] + Test.@test SFC.wigner_d_column(1, -1, β, 2)[2:3] ≈ [(1 - c) / 2, (-2c^2 + c + 1) / 2] + Test.@test SFC.wigner_d_column(2, 0, β, 2)[3] ≈ sqrt(3 / 8) * s^2 + Test.@test SFC.wigner_d_column(1, 0, β, 2)[2:3] ≈ [-s / sqrt(2), -sqrt(3 / 8) * sin(2β)] + # spin zero is Legendre + Test.@test SFC.wigner_d_column(0, 0, β, 3)[4] ≈ (5c^3 - 3c) / 2 + # the closed forms the spherical inversion of G4 rests on + x = c + P, dP = SFC._legendre_values(x, 7), nothing + for l in 1:6 + dPl = l * (x * P[l + 1] - P[l]) / (x^2 - 1) + Test.@test SFC.wigner_d_column(1, 1, β, 6)[l + 1] ≈ (1 - x) * dPl / (l * (l + 1)) + P[l + 1] + Test.@test SFC.wigner_d_column(1, -1, β, 6)[l + 1] ≈ (1 + x) * dPl / (l * (l + 1)) - P[l + 1] + end +end + +Test.@testset "the harmonic nodes and their weights" begin + n = HarmonicNodes(12, 20) + Test.@test length(n) == 12 + Test.@test issorted(n.separations) + Test.@test sum(n.weights) ≈ 2.0 + Test.@test SF.midpoints(n) === n.separations + Test.@test SF.n_histogram_bins(n) == 12 + μ, w = SF.gauss_legendre(8) + Test.@test sum(w .* μ .^ 6) ≈ 2 / 7 # exact for degree 15 + m = HarmonicNodes([0.2, 0.9, 2.0], 10; taper = SF.Bartlett()) + Test.@test sum(m.weights) ≈ 2.0 + Test.@test_throws ArgumentError HarmonicNodes([0.9, 0.2], 10) + Test.@test_throws ArgumentError HarmonicNodes([0.2, 3.5], 10) + res = SF.StructureFunctionSumsAndCounts(SFT.L2SFType(), m, zeros(3), zeros(3)) + Test.@test length(res.sums) == 3 + Test.@test_throws DimensionMismatch SF.StructureFunctionSumsAndCounts(SFT.L2SFType(), m, zeros(4), zeros(4)) +end + +Test.@testset "a scalar's kernel-binned moments are the pseudo-spectral series exactly" begin + # The identity, with arbitrary weights and a mask: Σ_ij w_i w_j (θ_j − θ_i)^p K_L(γ_ij, β) equals the + # series of the masked monomials' cross pseudo-spectra, term for term, to round-off. + Random.seed!(3100) + N, L = 110, 8 + x = Matrix(vcat((2π .* rand(N))', (asin.(2 .* rand(N) .- 1))')) + f = randn(N) + w = 0.5 .+ rand(N) + valid = rand(N) .> 0.3 + nodes = HarmonicNodes([0.3, 1.0, 2.0, 2.9], L) + pts = [_position(x[1, i], x[2, i]) for i in 1:N] + Pβ = [SFC.wigner_d_column(0, 0, β, L) for β in nodes.separations] + Pγ = [SFC.wigner_d_column(0, 0, acos(clamp(dot(pts[i], pts[j]), -1, 1)), L) for i in 1:N, j in 1:N] + for sf in (SFT.ScalarSFType{2}(), SFT.ScalarSFType{3}(), SFT.ScalarSFType{4}()) + P = SFT.order(sf) + if isodd(P) + Test.@test_throws ArgumentError SFC.calculate_structure_function(sf, x, Fields(scalars = (f,)), nodes, DS; + weights = w, valid, verbose = false) + continue + end + res = SFC.calculate_structure_function(sf, x, Fields(scalars = (f,)), nodes, DS; weights = w, valid, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + for (k, β) in enumerate(nodes.separations) + ss = 0.0 + cc = 0.0 + for i in 1:N, j in 1:N + (valid[i] && valid[j]) || continue + Kl = sum((2l + 1) * Pγ[i, j][l + 1] * Pβ[k][l + 1] for l in 0:L) / (16π^2) + cc += w[i] * w[j] * Kl + ss += w[i] * w[j] * (f[j] - f[i])^P * Kl + end + Test.@test isapprox(res.sums[k], ss; rtol = 1e-11) + Test.@test isapprox(res.counts[k], cc; rtol = 1e-11) + end + end +end + +Test.@testset "second-order vector statistics equal the spin-1 closed forms on a Gauss–Legendre grid" begin + # A pure degree-2 potential: C^E_2 = l(l+1)·4π⟨Φ²⟩/5, ξ₊ = (5/4π)C^E_2 d²_{11}, ξ₋ = −(5/4π)C^E_2 d²_{1,−1}; + # with exact quadrature the pseudo-coefficients are the coefficients and the identity is exact. + μ, wμ = SF.gauss_legendre(12) + nlon = 25 + N = 12 * nlon + x = Matrix{Float64}(undef, 2, N) + w = Vector{Float64}(undef, N) + ug = Matrix{Float64}(undef, 2, N) + uc = Matrix{Float64}(undef, 2, N) + Φ = Vector{Float64}(undef, N) + k = 0 + for j in 1:12, i in 1:nlon + k += 1 + lon, lat = (i - 1) * 2π / nlon, asin(μ[j]) + x[1, k], x[2, k], w[k] = lon, lat, wμ[j] * 2π / nlon + p = _position(lon, lat) + Φ[k] = p[1] * p[2] + grad = SA.SVector(p[2], p[1], 0.0) + t = grad - dot(grad, p) * p + ug[1, k], ug[2, k] = dot(t, _east(lon, lat)), dot(t, _north(lon, lat)) + c = cross(p, t) + uc[1, k], uc[2, k] = dot(c, _east(lon, lat)), dot(c, _north(lon, lat)) + end + meanΦ2 = sum(w .* Φ .^ 2) / (4π) + CE2 = 6 * 4π * meanΦ2 / 5 + L = 8 + nodes = HarmonicNodes(9, L) + d11 = [SFC.wigner_d_column(1, 1, β, 2)[3] for β in nodes.separations] + d1m1 = [SFC.wigner_d_column(1, -1, β, 2)[3] for β in nodes.separations] + ξp = (5 / (4π)) * CE2 .* d11 + ξm = -(5 / (4π)) * CE2 .* d1m1 + CLL, CTT = (ξp .+ ξm) ./ 2, (ξp .- ξm) ./ 2 + C0 = (5 / (4π)) * CE2 / 2 + DLL, DTT = 2 .* (C0 .- CLL), 2 .* (C0 .- CTT) + for (sf, ref) in ((SFT.L2SFType(), DLL), (SFT.T2SFType(), DTT), (SFT.S2SFType(), DLL .+ DTT), + (SFT.T2ComponentSFType(), DTT)) + r = SFC.calculate_structure_function(sf, x, ug, nodes, DS; weights = w, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + Test.@test maximum(abs, r.counts .- 1) < 1e-12 # ∫∫ K dΩ dΩ′ = 1 on the full sphere + Test.@test maximum(abs, r.sums ./ r.counts .- ref) < 1e-12 * maximum(abs, ref) + end + for (sf, ref) in ((SFT.L2SFType(), DTT), (SFT.T2SFType(), DLL)) + r = SFC.calculate_structure_function(sf, x, uc, nodes, DS; weights = w, verbose = false) + Test.@test maximum(abs, r.values .- ref) < 1e-12 * maximum(abs, ref) + end + # the same numbers through a multi-field, and the scalar's own closed form 2⟨Φ²⟩(1 − P₂) + fb = Fields(vectors = (ug,), scalars = (Φ,)) + rL = SFC.calculate_structure_function(SFT.L2SFType(), x, fb, nodes, DS; weights = w, verbose = false) + Test.@test maximum(abs, rL.values .- DLL) < 1e-12 * maximum(abs, DLL) + rΦ = SFC.calculate_structure_function(SFT.ScalarSFType{2}(), x, fb, nodes, DS; weights = w, verbose = false) + P2 = [SFC.wigner_d_column(0, 0, β, 2)[3] for β in nodes.separations] + Test.@test maximum(abs, rΦ.values .- 2 .* meanΦ2 .* (1 .- P2)) < 1e-12 * meanΦ2 + # gradient is E, curl is B, and the scalar's spectrum is its own + sg = SFC.harmonic_spectra(x, ug, L, DS; weights = w) + sc = SFC.harmonic_spectra(x, uc, L, DS; weights = w) + Test.@test sg.EE[3] ≈ CE2 rtol = 1e-12 + Test.@test maximum(abs, sg.BB) < 1e-12 * CE2 + Test.@test maximum(abs, sg.EE[[1, 2, 4, 5, 6, 7, 8, 9]]) < 1e-12 * CE2 + Test.@test sc.BB[3] ≈ CE2 rtol = 1e-12 + Test.@test maximum(abs, sc.EE) < 1e-12 * CE2 + Test.@test sum((2l + 1) / (4π) * (sg.EE[l + 1] + sg.BB[l + 1]) for l in 0:L) ≈ sum(w .* vec(sum(abs2, ug; dims = 1))) / (4π) rtol = 1e-12 + Test.@test SFC.harmonic_spectra(x, reshape(Φ, 1, :), L, DS; weights = w).C[3] ≈ 4π * meanΦ2 / 5 rtol = 1e-12 +end + +Test.@testset "higher-order statistics on a band-limited field equal the exact rotation average" begin + # A degree-2 field's cubic and quartic products have degree ≤ 6 and 8, so the series terminate: with + # lmax above that and exact quadrature, the kernel-binned statistic IS the continuous rotation average, + # which an independent quadrature over pairs computes. + x, w, ug, uc, Φ = _gl_grid(14, 29) + nodes = HarmonicNodes([0.4, 1.1, 1.9, 2.6], 10) + for sf in (SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType(), SFT.L2T1SFType(), SFT.T3SFType(), + SFT.ProjectedStructureFunctionType{4, 0}(), SFT.L2SFType(), SFT.T2SFType()) + r = SFC.calculate_structure_function(sf, x, ug, nodes, DS; weights = w, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + Test.@test maximum(abs, r.counts .- 1) < 1e-12 + ref = [_rotation_average(sf, β) for β in nodes.separations] + scale = max(maximum(abs, ref), 1e-3) + Test.@test maximum(abs, r.sums .- ref) < 1e-9 * scale + end + # a mixed multi-field: the scalar with the vector, at third order + fb = Fields(vectors = (ug,), scalars = (Φ,)) + r = SFC.calculate_structure_function(SFT.MixedSFType{1, 0, 2}(), x, fb, nodes, DS; weights = w, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + ref = [_rotation_average(SFT.MixedSFType{1, 0, 2}(), β) for β in nodes.separations] + Test.@test maximum(abs, r.sums .- ref) < 1e-9 * maximum(abs, ref) + # the scalar alone at fourth order + r4 = SFC.calculate_structure_function(SFT.ScalarSFType{4}(), x, Fields(scalars = (Φ,)), nodes, DS; weights = w, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + ref4 = [_rotation_average(SFT.ScalarSFType{4}(), β; scalar = true) for β in nodes.separations] + Test.@test maximum(abs, r4.sums .- ref4) < 1e-9 * maximum(abs, ref4) +end + +Test.@testset "on a point set the kernel-binned statistic converges to the rotation average as lmax grows" begin + N = 1500 # equal-area points ≈ 0.09 rad apart + x, u, Φ = _fibonacci(N) + βs = [0.6, 1.2, 1.8, 2.4] + for (sf, field, scalar) in ((SFT.L2SFType(), u, false), (SFT.T2SFType(), u, false), (SFT.L3SFType(), u, false), + (SFT.ScalarSFType{2}(), Fields(scalars = (Φ,)), true)) + exact = [_rotation_average(sf, β; scalar) for β in βs] + scale = maximum(abs, exact) + # kernels wider than the point spacing: the error falls with the kernel width + errs = [maximum(abs.(SFC.calculate_structure_function(sf, x, field, HarmonicNodes(βs, L; taper = SF.GaussianTaper(1.0 / L)), + DS; verbose = false).values .- exact)) / scale for L in (6, 12, 24, 48)] + Test.@test issorted(errs; rev = true) + Test.@test errs[end] < 2e-3 + end +end + +Test.@testset "the fast transform gives the direct sum's answer" begin + Random.seed!(3200) + N = 400 + x, u, Φ = _fibonacci(N) + valid = rand(N) .> 0.25 + w = 0.5 .+ rand(N) + nodes = HarmonicNodes(6, 24; taper = SF.Bartlett()) + fb = Fields(vectors = (u,), scalars = (Φ,)) + for sf in (SFT.L2SFType(), SFT.L3SFType(), SFT.L1T2SFType(), SFT.ScalarSFType{2}(), SFT.MixedSFType{1, 0, 2}()) + a = SFC.calculate_structure_function(sf, x, fb, nodes, DS; weights = w, valid, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + b = SFC.calculate_structure_function(sf, x, fb, nodes, NU; weights = w, valid, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + Test.@test maximum(abs, a.sums .- b.sums) < 1e-8 * maximum(abs, a.sums) + Test.@test maximum(abs, a.counts .- b.counts) < 1e-8 * maximum(abs, a.counts) + end + sa = SFC.harmonic_spectra(x, u, 24, DS; weights = w, valid) + sb = SFC.harmonic_spectra(x, u, 24, NU; weights = w, valid) + Test.@test maximum(abs, sa.EE .- sb.EE) < 1e-8 * maximum(sa.EE) + Test.@test maximum(abs, sa.BB .- sb.BB) < 1e-8 * maximum(sa.EE) +end + +Test.@testset "the harmonic route refuses what it cannot mean" begin + x, u, Φ = _fibonacci(60) + nodes = HarmonicNodes(4, 6) + # odd in a scalar: both readings of every pair are summed, so the moment is identically zero + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.ScalarSFType{3}(), x, Fields(scalars = (Φ,)), nodes, DS; verbose = false) + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.MixedSFType{1, 0, 1}(), x, Fields(vectors = (u,), scalars = (Φ,)), nodes, DS; verbose = false) + # a norm is no polynomial + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.FullVectorStructureFunctionType{3}(), x, u, nodes, DS; verbose = false) + # the sphere is the only geometry + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.L2SFType(), x, u, nodes, DS; distance_metric = DI.Euclidean(), verbose = false) + # no provider without its package + Test.@test_throws ArgumentError SFC.harmonic_sweep!(zeros(4), zeros(4), SFT.L2SFType(), + SFH.SphericalGeometry{2}(DI.SphericalAngle(), 1.0), x, ones(60), u, nodes, Val(2), Val(1), Val(0), :none) + # a field the multi-field lacks + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.VectorDotSFType(1, 2), x, Fields(vectors = (u,)), nodes, DS; verbose = false) +end + +Test.@testset "a spherical grid reaches the harmonic route with its cell measure as weights" begin + geo = FG.Geometry.SphericalGeometry(1.0) + grid = FG.Connectivity.structured_grid(FG.SphericalSampling.GaussLegendreSampling(), 12; geometry = geo, nlon = 25) + coords = FG.Grids.materialize(grid) + N = length(coords[1]) + u = Matrix{Float64}(undef, 2, N) + for i in 1:N + lon, lat = coords[1][i], coords[2][i] + t = _field_at(_position(lon, lat)) + u[1, i], u[2, i] = dot(t, _east(lon, lat)), dot(t, _north(lon, lat)) + end + nodes = HarmonicNodes(6, 10) + ug = reshape(u, 2, size(FG.Grids.mask(grid))...) + got = SFC.calculate_structure_function(SFT.L2SFType(), grid, ug, nodes, DS; verbose = false, + output_type = SF.StructureFunctionSumsAndCounts) + x = Matrix(hcat(coords[1], coords[2])') + ref = SFC.calculate_structure_function(SFT.L2SFType(), x, u, nodes, DS; weights = vec(FG.Grids.measure_array(grid)), + output_type = SF.StructureFunctionSumsAndCounts, verbose = false) + Test.@test got.sums ≈ ref.sums rtol = 1e-12 + Test.@test got.counts ≈ ref.counts rtol = 1e-12 + Test.@test got.distance === nodes +end + +Test.@testset "kernel-binned results invert to the spectra they came from" begin + g = SFH.SphericalGeometry{2}(SFH.SphericalDistance(1.0), 1.0) + # exact on a Gauss–Legendre grid: the nodes' quadrature integrates a band-limited D(β) exactly + x, w, ug, _, Φ = _gl_grid(16, 33) + nodes = HarmonicNodes(10, 8) + rs = SFC.calculate_structure_function(SFT.ScalarSFType{2}(), x, Fields(scalars = (Φ,)), nodes, DS; weights = w, verbose = false) + C = SFC.isotropic_spectrum(rs, g, 6) + Test.@test C.l == 1:6 + Test.@test C.C ≈ [0.16 * 4π / 9, (0.2π + 3.24π / 15) / 5, 0, 0, 0, 0] atol = 1e-12 # from the scalar's coefficients + L2 = SFC.calculate_structure_function(SFT.L2SFType(), x, ug, nodes, DS; weights = w, verbose = false) + T2 = SFC.calculate_structure_function(SFT.T2SFType(), x, ug, nodes, DS; weights = w, verbose = false) + variance = sum(w .* vec(sum(abs2, ug; dims = 1))) / (4π) + eb = SFC.helmholtz_spectra(L2, T2, g, 6; variance) + Test.@test eb.E ≈ [2π / 9, 6 * (1.96π / 15 + 0.36π / 15 + 0.288π) / 5, 0, 0, 0, 0] atol = 1e-12 # l(l+1) C^Φ_l + Test.@test maximum(abs, eb.B) < 1e-12 + Test.@test_throws ArgumentError SFC.helmholtz_spectra(L2, SFC.calculate_structure_function(SFT.T2SFType(), x, ug, + HarmonicNodes(10, 9), DS; weights = w, verbose = false), g, 6; variance) + # a masked ensemble: the ratio of kernel-binned sums to kernel-binned counts, inverted, follows the + # exact spectrum of each realisation where the pseudo-spectrum of the masked field does not + Random.seed!(3) + xg, wg, _, _, _ = _gl_grid(24, 48) + N = size(xg, 2) + Lf = 6 + Ct = [1 / (l + 1)^2 for l in 1:Lf] + plan = NUFSHT.make_spin_plan(ComplexF64, π / 2 .- xg[2, :], xg[1, :], Lf, 0) + mask = rand(N) .> 0.4 + L = 24 + nodes = HarmonicNodes(32, L; taper = SF.GaussianTaper(1.0 / L)) + lmax = 8 + ratio = zeros(lmax) + pseudo = zeros(lmax + 1) + full = zeros(lmax + 1) + R = 60 + for _ in 1:R + a = zeros(ComplexF64, Lf + 1, 2Lf + 1) + for l in 1:Lf, m in -l:l + a[l + 1, m + Lf + 1] = sqrt(Ct[l]) * randn(ComplexF64) + end + f = real.(NUFSHT.nusht_type2_spin!(zeros(ComplexF64, N), a, plan)) + res = SFC.calculate_structure_function(SFT.ScalarSFType{2}(), xg, Fields(scalars = (f,)), nodes, DS; + weights = wg, valid = mask, verbose = false) + ratio .+= SFC.isotropic_spectrum(res, g, lmax).C + pseudo .+= SFC.harmonic_spectra(xg, reshape(f, 1, :), lmax, DS; weights = wg, valid = mask).C + full .+= SFC.harmonic_spectra(xg, reshape(f, 1, :), lmax, DS; weights = wg).C + end + truth = Ct ./ 2 # the real part of a circular field carries half the power + Test.@test maximum(abs.(full[2:(Lf + 1)] .- R .* truth) ./ (R .* truth)) < 0.1 + Test.@test maximum(abs.(ratio[1:Lf] .- full[2:(Lf + 1)]) ./ (R .* truth)) < 0.1 + Test.@test all(pseudo[2:(Lf + 1)] ./ full[2:(Lf + 1)] .< 0.6) + Test.@test maximum(abs, ratio[(Lf + 1):lmax]) < 0.05 * R * truth[end] +end diff --git a/test/test_helpers.jl b/test/test_helpers.jl index 8d9178d..c1b887c 100644 --- a/test/test_helpers.jl +++ b/test/test_helpers.jl @@ -1,8 +1,11 @@ -using StructureFunctions: StructureFunctions as SF, HelperFunctions as SFH +using StructureFunctions: StructureFunctions as SF, HelperFunctions as SFH, StructureFunctionTypes as SFT using Test: Test using LinearAlgebra: LinearAlgebra as LA using StaticArrays: StaticArrays as SA +struct FlippedTransverseBasis <: SFH.AbstractTransverseBasisConvention end +SFH.transverse_basis(::FlippedTransverseBasis, r_hat) = (-SFH.n̂(r_hat),) + Test.@testset "HelperFunctions.jl Unit Tests" begin Test.@testset "digitize" begin bins = [0.0, 1.0, 2.0, 5.0] @@ -86,22 +89,71 @@ Test.@testset "HelperFunctions.jl Unit Tests" begin z_basis = SFH.ReferenceAxisTransverseBasis(SA.SVector(0.0, 0.0, 1.0)) e = SFH.transverse_basis_vector(r_hat, z_basis) - Test.@test e ≈ SA.SVector(0.0, 0.0, 1.0) - Test.@test SFH.transverse_component(δu, r_hat, z_basis) ≈ 4.0 + Test.@test e ≈ SA.SVector(0.0, 1.0, 0.0) + Test.@test e == SFH.n̂(r_hat) + Test.@test SFH.transverse_component(δu, r_hat, z_basis) ≈ 3.0 y_basis = SFH.ReferenceAxisTransverseBasis(SA.SVector(0.0, 1.0, 0.0)) basis_vectors = SFH.transverse_basis(y_basis, r_hat) Test.@test length(basis_vectors) == 2 - Test.@test basis_vectors[1] ≈ SA.SVector(0.0, 1.0, 0.0) - Test.@test basis_vectors[2] ≈ SA.SVector(0.0, 0.0, 1.0) + Test.@test basis_vectors[1] ≈ SA.SVector(0.0, 0.0, -1.0) + Test.@test basis_vectors[2] ≈ SA.SVector(0.0, 1.0, 0.0) + Test.@test SFH.transverse_basis_vector(r_hat, y_basis, 2) ≈ SA.SVector(0.0, 1.0, 0.0) bad_basis = SFH.ReferenceAxisTransverseBasis(SA.SVector(1.0, 0.0, 0.0)) Test.@test_throws ArgumentError SFH.transverse_basis(bad_basis, r_hat) + Test.@test_throws ArgumentError SFH.transverse_basis(z_basis, SA.SVector(1.0, 0.0)) + end - gauge_basis = SFH.transverse_basis(SFH.CoordinateGaugeTransverseBasis(), r_hat) - Test.@test length(gauge_basis) == 2 - Test.@test LA.dot(gauge_basis[1], r_hat) ≈ 0.0 - Test.@test LA.dot(gauge_basis[2], r_hat) ≈ 0.0 + Test.@testset "the transverse direction is defined along ẑ and reaches the operators through their convention" begin + ẑ = SA.SVector(0.0, 0.0, 1.0) + Test.@test SFH.n̂(ẑ) == SA.SVector(0.0, -1.0, 0.0) + Test.@test SFH.n̂(-ẑ) == SA.SVector(0.0, 1.0, 0.0) + near = LA.normalize(SA.SVector(1e-9, 0.0, 1.0)) + Test.@test all(isfinite, SFH.n̂(near)) + Test.@test LA.norm(SFH.n̂(near)) ≈ 1.0 + Test.@test abs(LA.dot(SFH.n̂(near), near)) < 1e-12 + Test.@test SFH.n̂([0.0, 0.0, 1.0]) == SA.SVector(0.0, -1.0, 0.0) + δu = SA.SVector(2.0, 3.0, 4.0) + Test.@test SFT.T3SF(δu, ẑ) == (-3.0)^3 + Test.@test SFT.L2T1SF(δu, ẑ) == 4.0^2 * (-3.0) + + canonical = SFH.CanonicalTransverseBasis() + Test.@test SFT.T3SFType().basis === canonical + Test.@test SFT.ProjectedStructureFunctionType(0, 3).basis === canonical + Test.@test SFT.ProjectedStructureFunctionType{2, 1}(canonical) === SFT.L2T1SF + Test.@test SFH.transverse_basis(canonical, ẑ) == (SFH.n̂(ẑ), LA.cross(ẑ, SFH.n̂(ẑ))) + Test.@test SFH.transverse_basis(canonical, SA.SVector(1.0, 0.0)) == (SA.SVector(0.0, 1.0),) + Test.@test SFH.transverse_basis(canonical, [0.0, 0.0, 1.0]) == SFH.transverse_basis(canonical, ẑ) + Test.@test_throws ArgumentError SFH.transverse_basis(canonical, SA.SVector(1.0, 0.0, 0.0, 0.0)) + + flipped = FlippedTransverseBasis() + Test.@test SFT.ProjectedStructureFunctionType{0, 3}(flipped)(δu, ẑ) == -SFT.T3SF(δu, ẑ) + Test.@test SFT.ProjectedStructureFunctionType{2, 1}(flipped)(δu, ẑ) == -SFT.L2T1SF(δu, ẑ) + Test.@test SFT.ProjectedStructureFunctionType{0, 2}(flipped)(δu, ẑ) == SFT.T2SF(δu, ẑ) + Test.@test SFT.ProjectedStructureFunctionType{0, 4}(flipped)(δu, ẑ) == SFT.ProjectedStructureFunctionType{0, 4}()(δu, ẑ) + + x̂ = SA.SVector(1.0, 0.0, 0.0) + about_z = SFH.ReferenceAxisTransverseBasis(ẑ) + Test.@test SFT.ProjectedStructureFunctionType{0, 3}(about_z)(δu, x̂) == SFT.T3SF(δu, x̂) + Test.@test_throws ArgumentError SFT.ProjectedStructureFunctionType{0, 3}(about_z)(δu, ẑ) + a = LA.normalize(SA.SVector(1.0, sqrt(2.0), sqrt(3.0))) + about_a = SFH.ReferenceAxisTransverseBasis(a) + r̂ = LA.normalize(SA.SVector(0.3, -1.1, 0.7)) + e1 = LA.normalize(LA.cross(a, r̂)) + Test.@test SFT.ProjectedStructureFunctionType{0, 3}(about_a)(δu, r̂) ≈ LA.dot(δu, e1)^3 + Test.@test !(SFT.ProjectedStructureFunctionType{0, 3}(about_a)(δu, r̂) ≈ SFT.T3SF(δu, r̂)) + + # every rule: unit, perpendicular, first vector odd in r̂, so odd operators read a pair the same from either end + for rule in (canonical, about_a, flipped), r in (r̂, ẑ, x̂) + e = SFH.transverse_basis(rule, r) + Test.@test all(v -> abs(LA.norm(v) - 1) < 1e-14, e) + Test.@test all(v -> abs(LA.dot(v, r)) < 1e-14, e) + Test.@test SFH.transverse_basis(rule, -r)[1] ≈ -e[1] + for op in (SFT.ProjectedStructureFunctionType{0, 3}(rule), SFT.ProjectedStructureFunctionType{2, 1}(rule)) + Test.@test op(-δu, -r) ≈ op(δu, r) + end + end end Test.@testset "Projection identity in multiple dimensions" begin diff --git a/test/test_inplace.jl b/test/test_inplace.jl index 708901a..d8d7e3f 100644 --- a/test/test_inplace.jl +++ b/test/test_inplace.jl @@ -138,7 +138,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, # 1D Public AutoBackend (resolves to threaded or serial) sums_pub = zeros(Float64, n_dist) counts_pub = zeros(UInt32, n_dist) - SF.calculate_structure_function!(sums_pub, counts_pub, SFT.L2SF, x_mat, u_mat, distance_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) + SFC.calculate_structure_function!(sums_pub, counts_pub, SFT.L2SF, x_mat, u_mat, distance_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) sums_bas = zeros(Float64, n_dist) counts_bas = zeros(UInt32, n_dist) @@ -150,7 +150,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, # 2D Public AutoBackend sums_2d_pub = zeros(Float64, n_dist, n_vals) counts_2d_pub = zeros(UInt32, n_dist, n_vals) - SF.calculate_structure_function!(sums_2d_pub, counts_2d_pub, SFT.L2SF, x_mat, u_mat, distance_bins, value_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) + SFC.calculate_structure_function!(sums_2d_pub, counts_2d_pub, SFT.L2SF, x_mat, u_mat, distance_bins, value_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) sums_2d_bas = zeros(Float64, n_dist, n_vals) counts_2d_bas = zeros(UInt32, n_dist, n_vals) @@ -162,8 +162,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, end # Every `!` entry ACCUMULATES into the caller's buffers; zeroing belongs to the non-mutating -# wrappers. Batch-leading drivers used to overwrite (via `permutedims!`) and the tensor driver used -# to `fill!` the caller's arrays, so which contract you got depended only on the rank of the input. +# wrappers. One contract for every rank of input, checked here rank by rank. @testset "Mutating API accumulates for every input shape" begin Random.seed!(4242) FT = Float64 @@ -182,7 +181,7 @@ end @test s2 ≈ 2 .* s1 @test c2 == 2 .* c1 - # (b) batch / auxiliary axes: previously overwrote. + # (b) batch / auxiliary axes bs1, bc1 = zeros(FT, nb, B), zeros(UInt32, nb, B) SFC.calculate_structure_function!(bs1, bc1, sft, x2, u3, bins; verbose = false, show_progress = false) bs2, bc2 = copy(bs1), copy(bc1) @@ -190,7 +189,7 @@ end @test bs2 ≈ 2 .* bs1 @test bc2 == 2 .* bc1 - # (c) tensor: previously `fill!`ed the caller's arrays, so it could never accumulate. + # (c) tensor ts1, tc1 = zeros(FT, 2, 2, nb), zeros(UInt32, nb) SFC.calculate_structure_function_tensor!(ts1, tc1, Val(2), x2, u2, bins; verbose = false, show_progress = false) ts2, tc2 = copy(ts1), copy(tc1) diff --git a/test/test_jet.jl b/test/test_jet.jl index fa0630d..45cda54 100644 --- a/test/test_jet.jl +++ b/test/test_jet.jl @@ -18,8 +18,8 @@ Test.@testset "JET Stability Audit" begin # Audit type stability of the compute kernel on a concrete backend. The default (averaged) # path exercises the full backend compute (which produces the raw # `StructureFunctionSumsAndCounts`) plus `_finalize`, so any kernel instability surfaces - # here. We audit `SerialBackend` (concrete) rather than `AutoBackend` because AutoBackend's - # runtime backend selection is an intended runtime branch, not a fixable instability. We + # here. The audit takes `SerialBackend`, which is concrete: `AutoBackend`'s backend + # selection is an intended runtime branch, not a fixable instability. It # only audit the SF module to ignore internal Base.Threads dispatches. (Passing a # non-default `output_type` explicitly incurs a single by-design dynamic-dispatch barrier # in `_finalize`; it is checked for error-freedom via @test_call below, not @test_opt.) diff --git a/test/test_multifields.jl b/test/test_multifields.jl new file mode 100644 index 0000000..b83b842 --- /dev/null +++ b/test/test_multifields.jl @@ -0,0 +1,325 @@ +using ComputationalBackends: ComputationalBackends as CB +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, + StructureFunctionTypes as SFT, MultiFields as MF +using StructureFunctions.StructureFunctionTypes: MixedSFType, ScalarSFType, VectorDotSFType, ScalarDotSFType, + MixedStructureFunctionType +using StaticArrays: StaticArrays as SA +using LinearAlgebra: dot +using OhMyThreads: OhMyThreads +using Distances: Distances as DI +using KernelAbstractions: KernelAbstractions as KA +using Random: Random + +# Every pair, evaluated straight from the inputs. Independent of the packing and of the sweep. +function _brute(op, x, vectors, scalars, bins) + N = size(x, 2) + D = isempty(vectors) ? 0 : size(first(vectors), 1) + nb = length(bins) - 1 + sums = zeros(Float64, nb) + counts = zeros(Int, nb) + for i in 1:(N - 1), j in (i + 1):N + dx = SA.SVector{size(x, 1)}(x[:, j] - x[:, i]) + r = sqrt(dot(dx, dx)) + b = searchsortedfirst(bins, r) - 1 + 1 <= b <= nb || continue + rh = dx / r + dv = [SA.SVector{D}(v[:, j] - v[:, i]) for v in vectors] + ds = [s[j] - s[i] for s in scalars] + sums[b] += op(dv, ds, rh) + counts[b] += 1 + end + return sums, counts +end + +_run(op, x, f, bins) = SFC.calculate_structure_function( + op, x, f, bins, UInt32; output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + +Test.@testset "a field of one vector field is the array path" begin + # The adapter must be a no-op for what callers already pass: same kernel, same answer, bit for bit. + Random.seed!(1200) + x = rand(2, 80) + u = randn(2, 80) + bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal + for op in (SFT.L2SFType(), SFT.T2SFType(), SFT.S2SFType(), SFT.L3SFType()) + bare = SFC.calculate_structure_function(op, x, u, bins, UInt32; + output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + multi = _run(op, x, MF.Fields(vectors = (u,)), bins) + Test.@test multi.counts == bare.counts + Test.@test multi.sums == bare.sums # identical, not merely close + end + # and the packing itself copies nothing it need not + Test.@test MF.packed(MF.Fields(vectors = (u,))) == u +end + +Test.@testset "packing lays fields out as declared" begin + Random.seed!(1300) + u = randn(3, 6) + a = randn(3, 6) + th = randn(6) + ph = randn(6) + f = MF.Fields(vectors = (u, a), scalars = (th, ph)) + Test.@test MF.field_dimension(f) == 3 + Test.@test MF.n_vector_fields(f) == 2 + Test.@test MF.n_scalar_fields(f) == 2 + d = MF.packed(f) + Test.@test size(d) == (3 * 2 + 2, 6) + Test.@test d[1:3, :] == u + Test.@test d[4:6, :] == a + Test.@test d[7, :] == th + Test.@test d[8, :] == ph +end + +Test.@testset "the multi-field refuses what it cannot mean" begin + Test.@test_throws ArgumentError MF.Fields() + Test.@test_throws DimensionMismatch MF.Fields(vectors = (randn(2, 5), randn(3, 5))) + Test.@test_throws DimensionMismatch MF.Fields(vectors = (randn(2, 5),), scalars = (randn(4),)) + Test.@test_throws ArgumentError MF.Fields(vectors = (randn(5),)) + Test.@test_throws DimensionMismatch MF.Fields(vectors = (randn(2, 5, 2),), scalars = (randn(5, 3),)) + # a grid-shaped field is one vector field over the flattened cells + Test.@test size(MF.packed(MF.Fields(vectors = (randn(2, 5, 2),), scalars = (randn(5, 2),)))) == (3, 10) +end + +Test.@testset "the scalar structure function matches brute force" begin + Random.seed!(1400) + N = 70 + x = rand(2, N) + th = randn(N) + bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal + f = MF.Fields(vectors = (randn(2, N),), scalars = (th,)) + for P in (2, 3) + got = _run(SFT.ScalarSFType{P}(), x, f, bins) + # an odd power reads the pair from the lower to the upper end along the first separating axis + orient(rh) = isodd(P) ? (rh[1] != 0 ? sign(rh[1]) : sign(rh[2])) : 1.0 + ref_s, ref_c = _brute((dv, ds, rh) -> orient(rh) * ds[1]^P, x, (), (th,), bins) + Test.@test got.counts == ref_c + Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) + Test.@test sum(got.counts) == N * (N - 1) ÷ 2 + end +end + +Test.@testset "Yaglom's mixed moment matches brute force" begin + # ⟨δu_L (δθ)²⟩ — the velocity part read from a transported field, the scalar part from a + # differenced one, so the two never share a frame by accident. + Random.seed!(1500) + N = 70 + x = rand(2, N) + u = randn(2, N) + th = randn(N) + bins = collect(range(0.0, 1.5; length = 7)) # spans the unit square diagonal + f = MF.Fields(vectors = (u,), scalars = (th,)) + got = _run(SFT.MixedSFType{1, 0, 2}(), x, f, bins) + ref_s, ref_c = _brute((dv, ds, rh) -> dot(dv[1], rh) * ds[1]^2, x, (u,), (th,), bins) + Test.@test got.counts == ref_c + Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) + + # and the first-order flux of the tracer itself + got1 = _run(SFT.MixedSFType{1, 0, 1}(), x, f, bins) + orient(rh) = rh[1] != 0 ? sign(rh[1]) : sign(rh[2]) # odd in θ: read along the first separating axis + ref1_s, _ = _brute((dv, ds, rh) -> orient(rh) * dot(dv[1], rh) * ds[1], x, (u,), (th,), bins) + Test.@test isapprox(got1.sums, ref1_s; rtol = 1e-10, atol = 1e-12) +end + +Test.@testset "a field of scalars alone is located by its coordinates" begin + # With no vector field there is no velocity dimension to read the geometry from; the points + # carry it. Checked against brute force on two- and three-dimensional points. + Random.seed!(1550) + N = 60 + for Dx in (2, 3) + x = rand(Dx, N) + th = randn(N) + ph = randn(N) + bins = collect(range(0.0, 1.2; length = 6)) + f = MF.Fields(scalars = (th, ph)) + got = _run(SFT.ScalarSFType{2}(), x, f, bins) + ref_s, ref_c = _brute((dv, ds, rh) -> ds[1]^2, x, (), (th, ph), bins) + Test.@test got.counts == ref_c + Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) + gotx = _run(SFT.ScalarDotSFType(1, 2), x, f, bins) + refx_s, _ = _brute((dv, ds, rh) -> ds[1] * ds[2], x, (), (th, ph), bins) + Test.@test isapprox(gotx.sums, refx_s; rtol = 1e-10, atol = 1e-12) + end +end + +Test.@testset "odd scalar moments do not depend on how the points are ordered" begin + # ⟨δu_L δθ⟩ and ⟨(δθ)³⟩ change sign when a pair is read from its other end, so their value is fixed + # by reading every pair from the lower to the upper end along the first separating coordinate — + # never by the order the points arrive in. + Random.seed!(1570) + N = 60 + for (Dx, metric) in ((2, DI.Euclidean()), (3, DI.Euclidean()), (2, DI.Haversine(6.371e6))) + x = Dx == 2 && metric isa DI.Haversine ? vcat(120 .* rand(1, N) .- 60, 100 .* rand(1, N) .- 50) : rand(Dx, N) + u = randn(Dx == 3 ? 3 : 2, N) + th = randn(N) + bins = metric isa DI.Haversine ? collect(range(0.0, 1.2e7; length = 6)) : + collect(range(0.0, 1.5; length = 6)) + perm = Random.randperm(N) + f = MF.Fields(vectors = (u,), scalars = (th,)) + fp = MF.Fields(vectors = (u[:, perm],), scalars = (th[perm],)) + for sf in (SFT.MixedSFType{1, 0, 1}(), SFT.ScalarSFType{3}()) + a = SFC.calculate_structure_function(sf, x, f, bins; backend = CB.SerialBackend(), + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + b = SFC.calculate_structure_function(sf, x[:, perm], fp, bins; backend = CB.SerialBackend(), + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + Test.@test a.counts == b.counts + Test.@test isapprox(a.sums, b.sums; rtol = 1e-10, atol = 1e-12) + Test.@test any(!iszero, a.sums) + c = SFC.calculate_structure_function(sf, x[:, perm], fp, bins; backend = CB.ThreadedBackend(), + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + Test.@test isapprox(c.sums, a.sums; rtol = 1e-10, atol = 1e-12) + d = SFC.calculate_structure_function(sf, x[:, perm], fp, bins; + backend = CB.GPUBackend(KA.CPU()), distance_metric = metric, + output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test d.counts == a.counts + Test.@test isapprox(d.sums, a.sums; rtol = 1e-10, atol = 1e-12) + if metric isa DI.Euclidean + # the reading is the lexicographic one on the displacement, checked pair by pair + ref_s, ref_c = _brute((dv, ds, rh) -> (rh[1] != 0 ? sign(rh[1]) : sign(rh[2])) * + (sf isa SFT.ScalarSFType ? ds[1]^3 : dot(dv[1], rh) * ds[1]), x, (u,), (th,), bins) + Test.@test a.counts == ref_c + Test.@test isapprox(a.sums, ref_s; rtol = 1e-10, atol = 1e-12) + end + end + end +end + +Test.@testset "cross-field moments are what an advective structure function is" begin + # ⟨δu · δ𝓐⟩ and ⟨δω δ𝓐_ω⟩ — second-order moments between two different fields. + Random.seed!(1600) + N = 60 + x = rand(2, N) + u = randn(2, N) + adv = randn(2, N) + w = randn(N) + advw = randn(N) + bins = collect(range(0.0, 1.3; length = 6)) + + fv = MF.Fields(vectors = (u, adv)) + got = _run(SFT.VectorDotSFType(1, 2), x, fv, bins) + ref_s, ref_c = _brute((dv, ds, rh) -> dot(dv[1], dv[2]), x, (u, adv), (), bins) + Test.@test got.counts == ref_c + Test.@test isapprox(got.sums, ref_s; rtol = 1e-10, atol = 1e-12) + + fs = MF.Fields(vectors = (u,), scalars = (w, advw)) + gots = _run(SFT.ScalarDotSFType(1, 2), x, fs, bins) + refs_s, _ = _brute((dv, ds, rh) -> ds[1] * ds[2], x, (u,), (w, advw), bins) + Test.@test isapprox(gots.sums, refs_s; rtol = 1e-10, atol = 1e-12) + + # the diagonal of the vector cross-moment IS the second-order structure function + diag = _run(SFT.VectorDotSFType(1, 1), x, fv, bins) + s2 = _run(SFT.S2SFType(), x, MF.Fields(vectors = (u,)), bins) + Test.@test diag.counts == s2.counts + Test.@test isapprox(diag.sums, s2.sums; rtol = 1e-12) +end + +Test.@testset "asking for a field a field does not carry says so" begin + Random.seed!(1700) + x = rand(2, 20) + u = randn(2, 20) + bins = collect(range(0.0, 1.0; length = 4)) + # a plain velocity has no scalar field + Test.@test_throws ArgumentError _run(SFT.ScalarSFType{2}(), x, MF.Fields(vectors = (u,)), bins) + # and only one vector field + Test.@test_throws ArgumentError _run(SFT.VectorDotSFType(1, 2), x, MF.Fields(vectors = (u,)), bins) +end + +Test.@testset "fields are transported on a sphere, scalars are not" begin + # A vector field is carried as an ambient 3-vector on a sphere, so a multi-field must widen every + # vector field exactly as the array path widens the one it has. A scalar has nothing to + # transport and passes through untouched. + Random.seed!(1800) + N = 50 + x = vcat(reshape(2π .* rand(N), 1, N), reshape((rand(N) .- 0.5) .* 1.4, 1, N)) + u = randn(2, N) + th = randn(N) + bins = collect(range(0.0, 2.4; length = 6)) + metric = SFC.DI.SphericalAngle() + + # one vector field: the same kernel as the array path, so identical to the last bit + # Both pinned to the same backend: the claim is that the multi-field takes the *same kernel*, and a + # different backend would differ in summation order alone, which would not test that. + bare_s = zeros(5); bare_c = zeros(UInt32, 5) + SFC.calculate_structure_function!(bare_s, bare_c, SFT.L2SFType(), x, u, bins; + distance_metric = metric, backend = CB.SerialBackend()) + multi = SFC.calculate_structure_function( + SFT.L2SFType(), x, MF.Fields(vectors = (u,)), bins, UInt32; distance_metric = metric, + backend = CB.SerialBackend(), + output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test multi.counts == bare_c + Test.@test multi.sums == bare_s + + # a scalar rides along without disturbing the velocity part: L2SF on the multi-field must still equal + # L2SF on the velocity alone + with_tracer = SFC.calculate_structure_function( + SFT.L2SFType(), x, MF.Fields(vectors = (u,), scalars = (th,)), bins, UInt32; + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + Test.@test with_tracer.counts == bare_c + Test.@test isapprox(with_tracer.sums, bare_s; rtol = 1e-12) + + # the scalar structure function on a sphere: transport-free, so it is the plain difference + scalar_only = SFC.calculate_structure_function( + SFT.ScalarSFType{2}(), x, MF.Fields(scalars = (th,)), bins, UInt32; + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + ref_s = zeros(5); ref_c = zeros(Int, 5) + for i in 1:(N - 1), j in (i + 1):N + r = SFC.DI.SphericalAngle()(view(x, :, i), view(x, :, j)) + b = searchsortedfirst(bins, r) - 1 + 1 <= b <= 5 || continue + ref_s[b] += (th[j] - th[i])^2 + ref_c[b] += 1 + end + Test.@test scalar_only.counts == UInt32.(ref_c) + Test.@test isapprox(scalar_only.sums, ref_s; rtol = 1e-10, atol = 1e-12) + Test.@test sum(scalar_only.counts) > 0 + + # Yaglom on a sphere runs and stays finite; its velocity half is transported, so it is not the + # flat answer + yag = SFC.calculate_structure_function( + SFT.MixedSFType{1, 0, 2}(), x, MF.Fields(vectors = (u,), scalars = (th,)), bins, UInt32; + distance_metric = metric, output_type = SF.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false) + Test.@test all(isfinite, yag.sums) + Test.@test yag.counts == bare_c +end + +Test.@testset "the threaded backend gives the serial answer" begin + # Multi-field across threads: the setup happens once above the task loop and each task sweeps + # its own outer indices, so the only thing that may differ from serial is summation order. + Random.seed!(1900) + N = 400 + x = rand(2, N) + u = randn(2, N) + adv = randn(2, N) + th = randn(N) + bins = collect(range(0.0, 1.5; length = 8)) # spans the unit square diagonal + nb = length(bins) - 1 + + for (f, op) in ((MF.Fields(vectors = (u,), scalars = (th,)), SFT.MixedSFType{1, 0, 2}()), + (MF.Fields(vectors = (u, adv)), SFT.VectorDotSFType(1, 2)), + (MF.Fields(vectors = (u,), scalars = (th,)), SFT.ScalarSFType{2}()), + (MF.Fields(vectors = (u,)), SFT.L2SFType())) + ser_s = zeros(nb); ser_c = zeros(Int, nb) + SFC.serial_calculate_structure_function!(ser_s, ser_c, op, x, f, bins; + verbose = false, show_progress = false) + thr_s = zeros(nb); thr_c = zeros(Int, nb) + SFC.threaded_calculate_structure_function!(thr_s, thr_c, op, x, f, bins; + verbose = false, show_progress = false) + Test.@test thr_c == ser_c + Test.@test isapprox(thr_s, ser_s; rtol = 1e-10, atol = 1e-12) + Test.@test sum(thr_c) == N * (N - 1) ÷ 2 + end +end + +Test.@testset "the field operators are exported" begin + Test.@test MixedSFType === MixedStructureFunctionType + Test.@test MixedSFType{1, 0, 2}() === SFT.MixedSFType{1, 0, 2}() + Test.@test ScalarSFType{2}() === SFT.ScalarSFType{2}() + Test.@test VectorDotSFType(1, 2) === SFT.VectorDotSFType(1, 2) + Test.@test ScalarDotSFType(1, 2) === SFT.ScalarDotSFType(1, 2) +end diff --git a/test/test_operator_contract.jl b/test/test_operator_contract.jl new file mode 100644 index 0000000..ed16a2f --- /dev/null +++ b/test/test_operator_contract.jl @@ -0,0 +1,134 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, StructureFunctionTypes as SFT, MultiFields as MF +using StaticArrays: StaticArrays as SA +using LinearAlgebra: normalize +using Random: Random + +Random.seed!(20260907) + +# The rank-p moment tensor of a single pair, δu ⊗ … ⊗ δu, in the engine's symmetric storage. +function _outer(δu::SA.SVector{W, T}, ::Val{P}) where {W, T, P} + js = SFT.symmetric_indices(Val(W), Val(P)) + data = SA.SVector{length(js), T}(ntuple(n -> prod(δu[j] for j in js[n]), length(js))) + return SFT.SymmetricMoments{W, P}(data) +end + +# The increment the operator itself consumes: the plain vector for one vector field and no +# scalars, a FieldIncrement for every other shape. +function _increment(δu::SA.SVector{W, T}, ::Val{D}, ::Val{V}, ::Val{K}) where {W, T, D, V, K} + V == 1 && K == 0 && return SA.SVector{D, T}(ntuple(d -> δu[d], Val(D))) + vectors = ntuple(a -> SA.SVector{D, T}(ntuple(d -> δu[(a - 1) * D + d], Val(D))), Val(V)) + scalars = ntuple(k -> δu[V * D + k], Val(K)) + return MF.FieldIncrement{D, V, K, T}(vectors, scalars) +end + +function _check_operator(sf, D, V, K; n = 40) + W = V * D + K + p = SFT.order(sf) + Test.@test SFT.is_polynomial_operator(sf) + for _ in 1:n + δu = SA.SVector{W, Float64}(randn(W)) + r̂ = D == 0 ? SA.SVector{0, Float64}() : SA.SVector{D, Float64}(normalize(randn(D))) + want = sf(_increment(δu, Val(D), Val(V), Val(K)), r̂) + got = SFT.moment_contract(sf, _outer(δu, Val(p)), r̂, Val(V), Val(K)) + Test.@test isapprox(got, want; atol = 1e-11, rtol = 1e-11) + end +end + +Test.@testset "symmetric storage: indices are sorted, complete and ranked by position" begin + for (W, P) in ((2, 2), (3, 3), (4, 4), (3, 5), (5, 1)) + js = SFT.symmetric_indices(Val(W), Val(P)) + Test.@test length(js) == binomial(W + P - 1, P) + Test.@test all(issorted, js) + Test.@test allunique(js) + for (n, j) in enumerate(js) + Test.@test SFT.symmetric_rank(Val(W), Val(P), j) == n + Test.@test SFT.symmetric_rank(Val(W), Val(P), reverse(j)) == n + end + end + Test.@test_throws DimensionMismatch SFT.SymmetricMoments{3, 2}(SA.SVector{4, Float64}(1, 2, 3, 4)) +end + +Test.@testset "order is defined for every polynomial operator" begin + Test.@test SFT.order(SFT.ScalarSFType{3}()) == 3 + Test.@test SFT.order(SFT.MixedSFType{1, 0, 2}()) == 3 + Test.@test SFT.order(SFT.MixedSFType{2, 2, 1}()) == 5 + Test.@test SFT.order(SFT.ScalarDotSFType(1, 2)) == 2 + Test.@test SFT.order(SFT.VectorDotSFType(1, 2)) == 2 + Test.@test SFT.order(SFT.ProjectedStructureFunctionType{0, 4}()) == 4 +end + +Test.@testset "single vector field: contraction equals the operator, D = $D" for D in (2, 3) + for sf in ( + SFT.S2SFType(), SFT.L2SFType(), SFT.T2SFType(), SFT.T2ComponentSFType(), + SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType(), SFT.L1T2ComponentSFType(), + SFT.L2T1SFType(), SFT.T3SFType(), + SFT.ProjectedStructureFunctionType{4, 0}(), SFT.ProjectedStructureFunctionType{0, 4}(), + SFT.ProjectedStructureFunctionType{2, 2}(), SFT.ProjectedStructureFunctionType{1, 4}(), + SFT.FullVectorStructureFunctionType{2}(), SFT.FullVectorStructureFunctionType{4}(), + SFT.VectorDotSFType(1, 1), + ) + _check_operator(sf, D, 1, 0) + end +end + +Test.@testset "vector and scalar fields" begin + for sf in ( + SFT.ScalarSFType{2}(), SFT.ScalarSFType{3}(), SFT.ScalarSFType{4}(), + SFT.MixedSFType{1, 0, 2}(), SFT.MixedSFType{1, 0, 1}(), SFT.MixedSFType{1, 2, 1}(), + SFT.MixedSFType{0, 2, 2}(), SFT.MixedSFType{0, 0, 3}(), SFT.L2SFType(), SFT.S3SFType(), + ) + _check_operator(sf, 2, 1, 1) + _check_operator(sf, 3, 1, 1) + end + _check_operator(SFT.MixedSFType{0, 4, 1}(), 2, 1, 1) # two transverse pairs, W = 3, rank 5 + for sf in (SFT.VectorDotSFType(1, 2), SFT.VectorDotSFType(2, 2), SFT.MixedSFType{1, 2, 1}(2, 1)) + _check_operator(sf, 2, 2, 1) + end + for sf in (SFT.ScalarDotSFType(1, 2), SFT.ScalarSFType{3}(2), SFT.ScalarDotSFType(2, 2)) + _check_operator(sf, 0, 0, 2) + end +end + +struct AbsoluteIncrementOperator <: SFT.AbstractPairwiseStructureFunctionType end +(::AbsoluteIncrementOperator)(δu, r̂) = abs(SFT.SFC_field_vector(δu, 1)[1]) + +Test.@testset "non-polynomial operators are refused by name" begin + δu = SA.SVector{2, Float64}(0.3, -1.2) + r̂ = SA.SVector{2, Float64}(1.0, 0.0) + M3 = _outer(δu, Val(3)) + for sf in (SFT.FullVectorStructureFunctionType{3}(), SFT.MixedSFType{1, 1, 1}(), + AbsoluteIncrementOperator()) + Test.@test !SFT.is_polynomial_operator(sf) + end + Test.@test_throws ArgumentError SFT.moment_contract( + SFT.FullVectorStructureFunctionType{3}(), M3, r̂, Val(1), Val(0), + ) + err = try + SFT.moment_contract(AbsoluteIncrementOperator(), _outer(δu, Val(1)), r̂, Val(1), Val(0)) + nothing + catch e + e + end + Test.@test err isa ArgumentError + Test.@test occursin("AbsoluteIncrementOperator", err.msg) + Test.@test occursin("lag sweep", err.msg) + Test.@test_throws ArgumentError SFT.moment_contract( + SFT.MixedSFType{1, 1, 1}(), _outer(SA.SVector{3, Float64}(randn(3)), Val(3)), r̂, Val(1), Val(1), + ) +end + +Test.@testset "a field the field does not carry is refused" begin + δu = SA.SVector{2, Float64}(randn(2)) + r̂ = SA.SVector{2, Float64}(1.0, 0.0) + M2 = _outer(δu, Val(2)) + Test.@test_throws ArgumentError SFT.moment_contract(SFT.VectorDotSFType(1, 2), M2, r̂, Val(1), Val(0)) + Test.@test_throws ArgumentError SFT.moment_contract(SFT.ScalarSFType{2}(), M2, r̂, Val(1), Val(0)) + Test.@test_throws ArgumentError SFT.moment_contract( + SFT.L2SFType(), M2, SA.SVector{0, Float64}(), Val(0), Val(2), + ) + Test.@test_throws ArgumentError SFT.moment_contract( + SFT.T2ComponentSFType(), _outer(SA.SVector{1, Float64}(1.0), Val(2)), + SA.SVector{1, Float64}(1.0), Val(1), Val(0), + ) +end diff --git a/test/test_scattered_modes.jl b/test/test_scattered_modes.jl new file mode 100644 index 0000000..e2a984e --- /dev/null +++ b/test/test_scattered_modes.jl @@ -0,0 +1,308 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO +using ComputationalBackends: ComputationalBackends as CB +using StaticArrays: StaticArrays as SA +using LinearAlgebra: LinearAlgebra as LA +using FFTW: FFTW +using NonuniformFFTs: NonuniformFFTs +using FINUFFT: FINUFFT +using SpectralBackends: SpectralBackends as SB +using KernelAbstractions: KernelAbstractions as KA +using Random: Random + +const PROVIDERS = (SFC.NonuniformFFTsSpectralBackend(), SFC.FINUFFTSpectralBackend()) +const FFT_TAG = SB.FastFourierTransformSpectralBackend() +const SERIAL = CB.SerialBackend() +const DEVICE = CB.GPUBackend(KA.CPU()) +const RAW = SFO.StructureFunctionSumsAndCounts + +_provider_name(tag) = nameof(typeof(tag)) + +# The lattice of a periodic uniform schedule as a point list, in the cell order the packed field uses. +function _lattice_points(dims, spacing) + Dg = length(dims) + x = zeros(Float64, Dg, prod(dims)) + for (k, I) in enumerate(CartesianIndices(dims)), d in 1:Dg + x[d, k] = (I[d] - 1) * spacing[d] + end + return x +end + +# A schedule whose box is exactly the lattice's periodic domain, so its modes are the lattice's own. +function _lattice_schedule(x, dims, spacing; taper = SF.NoTaper()) + Dg = length(dims) + return SFC.ScatteredModesSchedule(x, ntuple(_ -> 0.0, Dg), ntuple(d -> dims[d] * spacing[d], Dg), dims, taper) +end + +function _gridded_run(sf, data, sched, bins, vD, vV, vK; valid = SFC.AllValid(), weights = nothing, tag = FFT_TAG, + backend = SERIAL) + nb = SFC.n_histogram_bins(SFC.squared_digitize_plan(bins)) + s = zeros(Float64, nb) + c = zeros(Float64, nb) + SFC.gridded_sweep!(s, c, sf, data, sched, bins, vD, vV, vK, tag; valid, weights, backend) + return s, c +end + +_close(a, b; rtol = 1e-9) = isapprox(a, b; rtol, atol = 1e-9 * max(1.0, maximum(abs, b))) + +Test.@testset "points on the mode grid reproduce the periodic gridded transform ($(_provider_name(tag)))" for tag in PROVIDERS + Random.seed!(9700) + cases = ( + ((12,), (0.3,), (SFT.L2SFType(), SFT.L3SFType())), + ((12, 8), (0.25, 0.4), (SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.T3SFType(), + SFT.ProjectedStructureFunctionType{2, 2}())), + ((8, 8, 8), (0.2, 0.2, 0.3), (SFT.L2SFType(), SFT.S3SFType(), SFT.T3SFType())), + ) + for (dims, spacing, ops) in cases + Dg = length(dims) + N = prod(dims) + x = _lattice_points(dims, spacing) + u = randn(Dg, dims...) + data = reshape(u, Dg, N) + grid = SFC.UniformLagSchedule(dims, spacing, ntuple(_ -> true, Dg)) + modes = _lattice_schedule(x, dims, spacing) + r_max = 0.45 * minimum(dims .* spacing) + bins = collect(range(0.0, r_max; length = 6)) + # every node held, a random subset held, and random weights + held = rand(N) .< 0.7 + valid = SFC.field_validity(reshape(ifelse.(held', data, NaN), Dg, N)) + w = 0.5 .+ rand(N) + for sf in ops + for (v, wt) in ((SFC.AllValid(), nothing), (valid, nothing), (SFC.AllValid(), w), (valid, w)) + ref_s, ref_c = _gridded_run(sf, data, grid, bins, Val(Dg), Val(1), Val(0); valid = v, weights = wt) + got_s, got_c = _gridded_run(sf, data, modes, bins, Val(Dg), Val(1), Val(0); + valid = v, weights = wt, tag) + Test.@test _close(got_c, ref_c) + Test.@test _close(got_s, ref_s) + Test.@test sum(ref_c) > 0 + end + end + end + # a multi-field on the lattice + dims, spacing = (12, 8), (0.25, 0.4) + x = _lattice_points(dims, spacing) + f = SF.MultiFields.Fields(vectors = (randn(2, dims...),), scalars = (randn(dims...),)) + grid = SFC.UniformLagSchedule(dims, spacing, (true, true)) + modes = _lattice_schedule(x, dims, spacing) + bins = collect(range(0.0, 1.3; length = 6)) + for sf in (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{2}(), SFT.MixedSFType{1, 0, 1}()) + ref_s, ref_c = _gridded_run(sf, SF.MultiFields.packed(f), grid, bins, Val(2), Val(1), Val(1)) + got_s, got_c = _gridded_run(sf, SF.MultiFields.packed(f), modes, bins, Val(2), Val(1), Val(1); tag) + Test.@test _close(got_c, ref_c) + Test.@test _close(got_s, ref_s) + end +end + +# The periodic kernel of M modes with the taper's squared mode weights, on a box of length L. +function _kernel_1d(M, φ, L, taper) + acc = 0.0 + for k in (-((M - 1) ÷ 2)):(M ÷ 2) + b = SF.mode_taper(taper, (2π * k / L)^2) + acc += b * b * cos(k * φ) + end + return acc / M +end + +# The soft-binned statistic written out for one-dimensional points: every ordered pair, the self +# pairs included, against the kernel centred on each representative lag; a half-turn lag is its own +# reverse and carries half of its pairs, and an odd operator averages to zero over its two images. +function _oracle_1d(order, x, u, w, s, bins) + N = length(x) + M = s.modes[1] + L = s.box[1] + Δ = L / M + θ = 2π .* (x .- s.origin[1]) ./ L + nb = length(bins) - 1 + sums = zeros(nb) + cnts = zeros(nb) + for h in 1:(M ÷ 2) + val = 0.0 + cnt = 0.0 + for i in 1:N, j in 1:N + K = _kernel_1d(M, θ[j] - θ[i] - 2π * h / M, L, s.taper) + ww = w[i] * w[j] + val += ww * (u[j] - u[i])^order * K + cnt += ww * K + end + if iseven(M) && h == M ÷ 2 + cnt /= 2 + val = isodd(order) ? 0.0 : val / 2 + end + b = searchsortedfirst(bins, h * Δ) - 1 + 1 <= b <= nb || continue + sums[b] += val + cnts[b] += cnt + end + return sums, cnts +end + +Test.@testset "off the grid: the kernel identity written out in one dimension ($(_provider_name(tag)))" for tag in PROVIDERS + Random.seed!(9710) + N = 7 + x = sort(rand(N)) .* 0.8 + u = randn(1, N) + w = 0.5 .+ rand(N) + for M in (9, 8), taper in (SF.NoTaper(), SF.GaussianTaper(0.05)) + s = SFC.ScatteredModesSchedule(reshape(x, 1, N), 0.6, (M,); taper) + Test.@test s.box[1] ≈ maximum(x) - minimum(x) + 0.6 + bins = collect(range(0.0, 0.7; length = 5)) + for (sf, order) in ((SFT.L2SFType(), 2), (SFT.L3SFType(), 3)) + ref_s, ref_c = _oracle_1d(order, x, u[1, :], w, s, bins) + got_s, got_c = _gridded_run(sf, u, s, bins, Val(1), Val(1), Val(0); weights = w, tag) + Test.@test isapprox(got_c, ref_c; rtol = 1e-9, atol = 1e-10) + Test.@test isapprox(got_s, ref_s; rtol = 1e-9, atol = 1e-10 * maximum(abs, ref_s)) + Test.@test sum(abs, ref_c) > 0 + end + end +end + +Test.@testset "the soft bins converge to the hard bins as the modes grow ($(_provider_name(tag)))" for tag in PROVIDERS + Random.seed!(9720) + N = 200 + x = rand(2, N) + u = vcat(sin.(2π .* x[1:1, :]) .* cos.(2π .* x[2:2, :]), cos.(2π .* x[1:1, :]) .* sin.(2π .* x[2:2, :])) + r_max = 0.6 + bins = collect(range(0.0, r_max; length = 5)) + hard = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Float64; backend = SERIAL, verbose = false, + show_progress = false, output_type = RAW) + hard_avg = hard.sums ./ hard.counts + errs = Float64[] + for M in (16, 32, 64) + s = SFC.ScatteredModesSchedule(x, r_max, (M, M); taper = SF.GaussianTaper(maximum(x) / M)) + soft = SFC.calculate_structure_function(SFT.L2SFType(), s, u, bins, tag; backend = SERIAL, verbose = false, + output_type = RAW) + Test.@test soft.distance isa SF.ModeBinEdges + Test.@test soft.distance.schedule === s + Test.@test sum(soft.counts) ≈ sum(hard.counts) rtol = 0.2 + push!(errs, maximum(abs.(soft.sums ./ soft.counts .- hard_avg) ./ abs.(hard_avg))) + end + Test.@test errs[2] < errs[1] + Test.@test errs[3] < errs[2] + Test.@test errs[3] < 0.1 +end + +Test.@testset "the two providers compute the same transforms" begin + Random.seed!(9760) + for (Dg, modes, r_max) in ((1, (64,), 0.4), (2, (32, 24), 0.4), (3, (12, 10, 8), 0.5)) + N = 150 + x = rand(Dg, N) + u = randn(Dg, N) + u[1, rand(N) .< 0.15] .= NaN + valid = SFC.field_validity(u) + w = 0.5 .+ rand(N) + s = SFC.ScatteredModesSchedule(x, r_max, modes; taper = SF.GaussianTaper(0.02)) + bins = collect(range(0.0, r_max; length = 5)) + for sf in (SFT.L2SFType(), SFT.S3SFType()) + a_s, a_c = _gridded_run(sf, u, s, bins, Val(Dg), Val(1), Val(0); valid, weights = w, tag = PROVIDERS[1]) + b_s, b_c = _gridded_run(sf, u, s, bins, Val(Dg), Val(1), Val(0); valid, weights = w, tag = PROVIDERS[2]) + Test.@test isapprox(a_c, b_c; rtol = 1e-10, atol = 1e-10 * maximum(abs, a_c)) + Test.@test isapprox(a_s, b_s; rtol = 1e-10, atol = 1e-10 * maximum(abs, a_s)) + Test.@test sum(a_c) > 0 + end + end +end + +Test.@testset "the device engine runs the non-uniform route ($(_provider_name(tag)))" for tag in PROVIDERS + Random.seed!(9730) + N = 60 + x = rand(2, N) .* (1.0, 0.7) + u = randn(2, N) + uf = copy(u) + uf[1, rand(N) .< 0.2] .= NaN + valid = SFC.field_validity(uf) + w = 0.5 .+ rand(N) + s = SFC.ScatteredModesSchedule(x, 0.5, (24, 16); taper = SF.GaussianTaper(0.03)) + bins = collect(range(0.0, 0.5; length = 6)) + for sf in (SFT.L2SFType(), SFT.S3SFType(), SFT.T3SFType()) + ref_s, ref_c = _gridded_run(sf, uf, s, bins, Val(2), Val(1), Val(0); valid, weights = w, tag) + dev_s, dev_c = _gridded_run(sf, uf, s, bins, Val(2), Val(1), Val(0); valid, weights = w, tag, + backend = DEVICE) + Test.@test _close(dev_c, ref_c) + Test.@test _close(dev_s, ref_s) + Test.@test all(isfinite, ref_s) + end +end + +Test.@testset "the box is padded so that no pair within r_max wraps ($(_provider_name(tag)))" for tag in PROVIDERS + Random.seed!(9740) + half = 20 + x = reshape(vcat(0.1 .* rand(half), 2.0 .+ 0.1 .* rand(half)), 1, 2half) + u = randn(1, 2half) + r_max = 0.3 + s = SFC.ScatteredModesSchedule(x, r_max, (512,); taper = SF.GaussianTaper(0.01)) + Test.@test s.box[1] ≈ maximum(x) - minimum(x) + r_max + # bins starting above the kernel's width, so no self pair's mass is counted; the two clusters' pairs + # sit at separations 1.9 … 2.1, which a box without the padding wraps to 0 … 0.2 + bins = collect(range(0.02, 0.25; length = 4)) + soft = SFC.calculate_structure_function(SFT.L2SFType(), s, u, bins, tag; backend = SERIAL, verbose = false, + output_type = RAW) + hard = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Float64; backend = SERIAL, verbose = false, + show_progress = false, output_type = RAW) + unpadded = SFC.ScatteredModesSchedule(x, (minimum(x),), (maximum(x) - minimum(x),), (512,), + SF.GaussianTaper(0.01)) + wrapped = SFC.calculate_structure_function(SFT.L2SFType(), unpadded, u, bins, tag; backend = SERIAL, + verbose = false, output_type = RAW) + inter = half * half + Test.@test sum(hard.counts) > 0 + Test.@test abs(sum(soft.counts) - sum(hard.counts)) / sum(hard.counts) < 0.1 + Test.@test sum(wrapped.counts) - sum(soft.counts) > 0.5 * inter +end + +Test.@testset "the route is asked for by name and refuses what it cannot mean" begin + Random.seed!(9750) + N = 30 + x = rand(2, N) + u = randn(2, N) + bins = collect(range(0.0, 0.5; length = 5)) + s = SFC.ScatteredModesSchedule(x, 0.5, (16, 16)) + Test.@test_throws ArgumentError SFC.ScatteredModesSchedule(x, 0.5, (16, 16); taper = SF.Bartlett()) + Test.@test_throws ArgumentError SFC.ScatteredModesSchedule(x, 0.0, (16, 16)) + Test.@test_throws ArgumentError SFC.ScatteredModesSchedule(x, 0.5, (1, 16)) + Test.@test_throws DimensionMismatch SFC.ScatteredModesSchedule(x, 0.5, (16,)) + # the transforms' accuracy is one tolerance on either tag; NonuniformFFTs' kernel half-support follows from it + for make in (SFC.NonuniformFFTsSpectralBackend, SFC.FINUFFTSpectralBackend) + Test.@test_throws ArgumentError make(tolerance = 0.0) + Test.@test_throws ArgumentError make(tolerance = 1.0) + Test.@test make(tolerance = 1e-9).tolerance == 1e-9 + Test.@test make().tolerance == 1e-12 + end + Test.@test SFC.nufft_half_support(SFC.NonuniformFFTsSpectralBackend(tolerance = 1e-7)) == 4 + Test.@test SFC.nufft_half_support(SFC.NonuniformFFTsSpectralBackend(tolerance = 1e-12)) == 7 + Test.@test SFC.nufft_half_support(SFC.NonuniformFFTsSpectralBackend(tolerance = 1e-15)) == 8 + # NonuniformFFTs' spreading kernel needs at least its half-support in modes; FINUFFT pads its own fine grid + small = SFC.ScatteredModesSchedule(x, 0.5, (4, 16)) + Test.@test_throws ArgumentError _gridded_run(SFT.L2SFType(), u, small, bins, Val(2), Val(1), Val(0); + tag = SFC.NonuniformFFTsSpectralBackend()) + Test.@test all(isfinite, _gridded_run(SFT.L2SFType(), u, small, bins, Val(2), Val(1), Val(0); + tag = SFC.NonuniformFFTsSpectralBackend(tolerance = 1e-7))[1]) + Test.@test all(isfinite, _gridded_run(SFT.L2SFType(), u, small, bins, Val(2), Val(1), Val(0); + tag = SFC.FINUFFTSpectralBackend())[1]) + # the generic SpectralBackends NUFFT tag names no provider + Test.@test_throws ArgumentError _gridded_run(SFT.L2SFType(), u, s, bins, Val(2), Val(1), Val(0); + tag = SB.NonUniformFastFourierTransformSpectralBackend()) + sums = zeros(4) + Test.@test_throws ArgumentError SFC.gridded_sweep!(sums, zeros(4), SFT.L2SFType(), u, s, bins, Val(2), Val(1), Val(0), FFT_TAG) + Test.@test_throws ArgumentError SFC.gridded_sweep!(sums, zeros(4), SFT.L2SFType(), u, s, bins, Val(2), Val(1), Val(0), + SB.AutoSpectralBackend()) + Test.@test_throws ArgumentError SFC.gridded_sweep!(sums, zeros(Int, 4), SFT.L2SFType(), u, s, bins, Val(2), Val(1), Val(0), + PROVIDERS[1]) + Test.@test_throws ArgumentError SFC.gridded_lag_sweep!(sums, zeros(4), SFT.L2SFType(), u, s, bins, Val(2), Val(1), Val(0)) + grid = SFC.UniformLagSchedule((6, 5), (0.2, 0.2), (true, true)) + for tag in PROVIDERS + Test.@test_throws ArgumentError SFC.gridded_sweep!(sums, zeros(4), SFT.L2SFType(), randn(2, 30), grid, bins, Val(2), + Val(1), Val(0), tag) + end + Test.@test_throws DimensionMismatch SFC.calculate_structure_function(SFT.L2SFType(), s, randn(2, N + 1), bins, + PROVIDERS[1]; verbose = false) + # a point list without a schedule stays on the exact pair loop + plain = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.AutoBackend(), verbose = false, + show_progress = false, output_type = RAW) + Test.@test !(plain.distance isa SF.ModeBinEdges) + for tag in PROVIDERS + res = SFC.calculate_structure_function(SFT.L2SFType(), s, u, bins, tag; verbose = false) + Test.@test res isa SFO.StructureFunction + Test.@test SF.midpoints(res.distance) == SF.midpoints(bins) + Test.@test SF.n_histogram_bins(res.distance) == 4 + end +end diff --git a/test/test_shorthands.jl b/test/test_shorthands.jl index ab0c34e..dc9cd02 100644 --- a/test/test_shorthands.jl +++ b/test/test_shorthands.jl @@ -1,6 +1,7 @@ using Test: Test using StructureFunctions: - StructureFunctions as SF, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT + StructureFunctions as SF, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT, + Calculations as SFC using StaticArrays: StaticArrays as SA Test.@testset "Structure function resolver API" begin @@ -10,17 +11,17 @@ Test.@testset "Structure function resolver API" begin u = rand(FT, 2, N) bins = SA.SVector(0.0, 1.4) - Test.@test SF.get_structure_function_type(:L2SF) === SF.L2SF - Test.@test SF.get_structure_function_type(Val(:L2SF)) === SF.L2SF - Test.@test SF.get_structure_function_type(2, :longitudinal) === SF.L2SF - Test.@test SF.get_structure_function_type(Val(2), Val(:long)) === SF.L2SF + Test.@test SFT.get_structure_function_type(:L2SF) === SFT.L2SF + Test.@test SFT.get_structure_function_type(Val(:L2SF)) === SFT.L2SF + Test.@test SFT.get_structure_function_type(2, :longitudinal) === SFT.L2SF + Test.@test SFT.get_structure_function_type(Val(2), Val(:long)) === SFT.L2SF - op = SF.get_structure_function_type(:L2SF) - res = SF.calculate_structure_function(op, x, u, bins; verbose = false, show_progress = false) + op = SFT.get_structure_function_type(:L2SF) + res = SFC.calculate_structure_function(op, x, u, bins; verbose = false, show_progress = false) Test.@test res isa SF.StructureFunction - Test.@test res.operator === SF.L2SF + Test.@test res.operator === SFT.L2SF - Test.@test_throws MethodError SF.calculate_structure_function( + Test.@test_throws MethodError SFC.calculate_structure_function( :L2SF, x, u, @@ -28,7 +29,7 @@ Test.@testset "Structure function resolver API" begin verbose = false, show_progress = false, ) - Test.@test_throws MethodError SF.calculate_structure_function( + Test.@test_throws MethodError SFC.calculate_structure_function( 2, :longitudinal, x, @@ -40,8 +41,8 @@ Test.@testset "Structure function resolver API" begin x_tuple = (vec(x[1, :]), vec(x[2, :])) u_tuple = (vec(u[1, :]), vec(u[2, :])) - Test.@test_throws ArgumentError SF.calculate_structure_function( - SF.L2SF, + Test.@test_throws ArgumentError SFC.calculate_structure_function( + SFT.L2SF, x_tuple, u_tuple, bins; @@ -49,20 +50,20 @@ Test.@testset "Structure function resolver API" begin show_progress = false, ) - Test.@test SF.S2SF === SFT.SecondOrderStructureFunction - Test.@test SF.S3SF === SFT.ThirdOrderStructureFunction - Test.@test SF.T3SF === SFT.OffDiagonalConsistentThirdOrderStructureFunction - Test.@test SF.L2T1SF === SFT.DiagonalInconsistentThirdOrderStructureFunction - Test.@test SF.L1T2SF === SFT.OffDiagonalInconsistentThirdOrderStructureFunction + Test.@test SFT.S2SF === SFT.SecondOrderStructureFunction + Test.@test SFT.S3SF === SFT.ThirdOrderStructureFunction + Test.@test SFT.T3SF === SFT.OffDiagonalConsistentThirdOrderStructureFunction + Test.@test SFT.L2T1SF === SFT.DiagonalInconsistentThirdOrderStructureFunction + Test.@test SFT.L1T2SF === SFT.OffDiagonalInconsistentThirdOrderStructureFunction - Test.@test SF.get_structure_function_type(2, :rotational) === - SF.RotationalSecondOrderStructureFunction - Test.@test SF.get_structure_function_type(2, :divergent) === - SF.DivergentSecondOrderStructureFunction - Test.@test SF.RotationalSecondOrderStructureFunction isa SF.AbstractDerivedStructureFunctionType - Test.@test SF.DivergentSecondOrderStructureFunction isa SF.AbstractDerivedStructureFunctionType - Test.@test_throws ArgumentError SF.calculate_structure_function( - SF.RotationalSecondOrderStructureFunction, + Test.@test SFT.get_structure_function_type(2, :rotational) === + SFT.RotationalSecondOrderStructureFunction + Test.@test SFT.get_structure_function_type(2, :divergent) === + SFT.DivergentSecondOrderStructureFunction + Test.@test SFT.RotationalSecondOrderStructureFunction isa SFT.AbstractDerivedStructureFunctionType + Test.@test SFT.DivergentSecondOrderStructureFunction isa SFT.AbstractDerivedStructureFunctionType + Test.@test_throws ArgumentError SFC.calculate_structure_function( + SFT.RotationalSecondOrderStructureFunction, x, u, bins; diff --git a/test/test_sorted_line.jl b/test/test_sorted_line.jl new file mode 100644 index 0000000..f832014 --- /dev/null +++ b/test/test_sorted_line.jl @@ -0,0 +1,224 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + MultiFields as MF +using StructureFunctions.MultiFields: Fields +using ComputationalBackends: ComputationalBackends as CB +using StaticArrays: StaticArrays as SA +using OhMyThreads: OhMyThreads +using Random: Random + +const RAW = SF.StructureFunctionSumsAndCounts +const SERIAL = CB.SerialBackend() +const THREADED = CB.ThreadedBackend() +const AUTO = CB.AutoBackend() + +const LINE_OPS = ( + SFT.S2SFType(), SFT.L2SFType(), SFT.T2SFType(), SFT.L3SFType(), SFT.S3SFType(), SFT.L1T2SFType(), + SFT.ProjectedStructureFunctionType{4, 0}(), SFT.ProjectedStructureFunctionType{2, 2}(), + SFT.FullVectorStructureFunctionType{2}(), SFT.FullVectorStructureFunctionType{4}(), +) + +# One pair's increment, read from point `i` to point `j`: the plain vector for one vector field, else +# the multi-field. +function _line_increment(data, i, j, ::Val{D}, ::Val{V}, ::Val{K}) where {D, V, K} + T = eltype(data) + V == 1 && K == 0 && return SA.SVector{D, T}(ntuple(d -> data[d, j] - data[d, i], Val(D))) + vectors = ntuple(Val(V)) do a + o = (a - 1) * D + SA.SVector{D, T}(ntuple(d -> data[o + d, j] - data[o + d, i], Val(D))) + end + scalars = ntuple(c -> data[V * D + c, j] - data[V * D + c, i], Val(K)) + return MF.FieldIncrement{D, V, K, T}(vectors, scalars) +end + +# The pair statistic written out on a line: Σ w_i w_j sf(δu, r̂) and Σ w_i w_j over the pairs each (lo, hi] +# bin holds, every pair read from its lower to its upper coordinate. +function _line_pair_loop(sf, x::AbstractVector, data::AbstractMatrix, bins, w, vD::Val{D}, vV::Val{V}, vK) where {D, V} + nb = length(bins) - 1 + s = zeros(nb) + c = zeros(nb) + N = length(x) + Dr = V == 0 ? 1 : D + r̂ = SA.SVector{Dr, Float64}(ntuple(d -> d == 1 ? 1.0 : 0.0, Dr)) + for i in 1:(N - 1), j in (i + 1):N + lo, hi = x[i] <= x[j] ? (i, j) : (j, i) + b = searchsortedfirst(bins, x[hi] - x[lo]) - 1 + 1 <= b <= nb || continue + ww = w[i] * w[j] + s[b] += ww * sf(_line_increment(data, lo, hi, vD, vV, vK), r̂) + c[b] += ww + end + return s, c +end + +_close(a, b; rtol = 1e-12) = isapprox(a, b; rtol, atol = rtol * max(maximum(abs, b), 1e-300)) + +Test.@testset "every polynomial operator on a line equals the pair loop" begin + Random.seed!(4210) + N = 300 + x = rand(N) .* 10.0 + u = randn(1, N) + bins = [0.0; sort(rand(7)) .* 4.0] + ones_w = ones(N) + x1 = reshape(x, 1, :) + for sf in LINE_OPS + ref_s, ref_c = _line_pair_loop(sf, x, u, bins, ones_w, Val(1), Val(1), Val(0)) + Test.@test sum(ref_c) > 0 + for backend in (SERIAL, THREADED, AUTO) + got = SFC.calculate_structure_function(sf, x1, u, bins; backend, verbose = false, + show_progress = false, output_type = RAW) + Test.@test got.counts == UInt32.(ref_c) + Test.@test _close(got.sums, ref_s) + end + end + # the averaged result object comes out of the same route + res = SFC.calculate_structure_function(SFT.L2SFType(), x1, u, bins; backend = SERIAL, verbose = false, + show_progress = false) + ref_s, ref_c = _line_pair_loop(SFT.L2SFType(), x, u, bins, ones_w, Val(1), Val(1), Val(0)) + Test.@test _close(res.values, ref_s ./ ref_c) +end + +Test.@testset "multi-fields on a line" begin + Random.seed!(4220) + N = 240 + x = rand(N) .* 6.0 + x1 = reshape(x, 1, :) + u = randn(1, N) + a = randn(1, N) + θ = randn(N) + φ = randn(N) + bins = [0.0; sort(rand(6)) .* 3.0] + ones_w = ones(N) + cases = ( + (Fields(vectors = (u,), scalars = (θ,)), + (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{2}(), SFT.ScalarSFType{1}(), SFT.ScalarSFType{3}(), + SFT.MixedSFType{2, 0, 1}(), SFT.MixedSFType{1, 0, 1}(), SFT.L2SFType())), + (Fields(vectors = (u, a)), (SFT.VectorDotSFType(1, 2), SFT.L3SFType())), + (Fields(scalars = (θ, φ)), (SFT.ScalarDotSFType(1, 2), SFT.ScalarSFType{4}(2), SFT.ScalarSFType{3}(1))), + ) + for (f, ops) in cases, sf in ops + D, V, K = MF.field_dimension(f), MF.n_vector_fields(f), MF.n_scalar_fields(f) + ref_s, ref_c = _line_pair_loop(sf, x, MF.packed(f), bins, ones_w, Val(D), Val(V), Val(K)) + Test.@test sum(ref_c) > 0 + for backend in (SERIAL, THREADED) + got = SFC.calculate_structure_function(sf, x1, f, bins; backend, verbose = false, + show_progress = false, output_type = RAW) + Test.@test got.counts == UInt32.(ref_c) + Test.@test _close(got.sums, ref_s) + end + end +end + +Test.@testset "pair weights on a line" begin + Random.seed!(4230) + N = 260 + x = rand(N) .* 8.0 + x1 = reshape(x, 1, :) + u = randn(1, N) + θ = randn(N) + w = 0.5 .+ rand(N) + bins = [0.0; sort(rand(7)) .* 3.5] + for sf in (SFT.L2SFType(), SFT.L3SFType(), SFT.ProjectedStructureFunctionType{4, 0}()) + ref_s, ref_c = _line_pair_loop(sf, x, u, bins, w, Val(1), Val(1), Val(0)) + for backend in (SERIAL, THREADED) + got = SFC.calculate_structure_function(sf, x1, u, bins, Float64; backend, weights = w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(got.counts, ref_c) + Test.@test _close(got.sums, ref_s) + end + end + f = Fields(vectors = (u,), scalars = (θ,)) + for sf in (SFT.MixedSFType{1, 0, 2}(), SFT.ScalarSFType{3}()) + ref_s, ref_c = _line_pair_loop(sf, x, MF.packed(f), bins, w, Val(1), Val(1), Val(1)) + got = SFC.calculate_structure_function(sf, x1, f, bins, Float64; backend = SERIAL, weights = w, + verbose = false, show_progress = false, output_type = RAW) + Test.@test _close(got.counts, ref_c) + Test.@test _close(got.sums, ref_s) + end + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.L2SFType(), x1, u, bins; backend = SERIAL, + weights = w, verbose = false, show_progress = false) +end + +Test.@testset "the order of the points and coincident points change nothing" begin + Random.seed!(4240) + N = 320 + x = rand(1:60, N) .* 0.1 + u = randn(1, N) + θ = randn(N) + bins = [0.0; sort(rand(6)) .* 3.0] + ones_w = ones(N) + perm = Random.randperm(N) + for sf in (SFT.L3SFType(), SFT.S2SFType()) + ref_s, ref_c = _line_pair_loop(sf, x, u, bins, ones_w, Val(1), Val(1), Val(0)) + Test.@test sum(ref_c) > 0 + sorted_res = SFC.calculate_structure_function(sf, reshape(sort(x), 1, :), u[:, sortperm(x)], bins; + backend = SERIAL, verbose = false, show_progress = false, + output_type = RAW) + shuffled_res = SFC.calculate_structure_function(sf, reshape(x[perm], 1, :), u[:, perm], bins; + backend = SERIAL, verbose = false, show_progress = false, + output_type = RAW) + Test.@test sorted_res.counts == UInt32.(ref_c) + Test.@test shuffled_res.counts == UInt32.(ref_c) + Test.@test _close(sorted_res.sums, ref_s) + Test.@test _close(shuffled_res.sums, ref_s) + end + # an odd scalar moment reads every pair from its lower to its upper coordinate, whatever the input order + f = Fields(vectors = (u,), scalars = (θ,)) + fp = Fields(vectors = (u[:, perm],), scalars = (θ[perm],)) + for sf in (SFT.ScalarSFType{3}(), SFT.MixedSFType{1, 0, 1}()) + ref_s, ref_c = _line_pair_loop(sf, x, MF.packed(f), bins, ones_w, Val(1), Val(1), Val(1)) + got = SFC.calculate_structure_function(sf, reshape(x[perm], 1, :), fp, bins; backend = SERIAL, + verbose = false, show_progress = false, output_type = RAW) + Test.@test got.counts == UInt32.(ref_c) + Test.@test _close(got.sums, ref_s) + Test.@test maximum(abs, ref_s) > 0 + end +end + +Test.@testset "what the sorted route does not take stays on the pair loop, and it refuses by name" begin + Random.seed!(4250) + N = 150 + x = rand(N) .* 5.0 + x1 = reshape(x, 1, :) + u = randn(1, N) + bins = [0.0; sort(rand(5)) .* 2.5] + ones_w = ones(N) + cubic = SFT.FullVectorStructureFunctionType{3}() + Test.@test !SFT.is_polynomial_operator(cubic) + ref_s, ref_c = _line_pair_loop(cubic, x, u, bins, ones_w, Val(1), Val(1), Val(0)) + for backend in (SERIAL, THREADED) + got = SFC.calculate_structure_function(cubic, x1, u, bins; backend, verbose = false, show_progress = false, + output_type = RAW) + Test.@test got.counts == UInt32.(ref_c) + Test.@test _close(got.sums, ref_s) + end + nb = length(bins) - 1 + Test.@test_throws ArgumentError SFC.sorted_line_sweep!(zeros(nb), zeros(Int, nb), cubic, x, u, bins, + Val(1), Val(1), Val(0)) + Test.@test_throws DimensionMismatch SFC.sorted_line_sweep!(zeros(nb), zeros(Int, nb), SFT.L2SFType(), x, + randn(2, N), bins, Val(1), Val(1), Val(0)) + Test.@test_throws ArgumentError SFC.calculate_structure_function(SFT.L2SFType(), x1, u, bins; backend = SERIAL, + culling = SFC.AlwaysCulling(), verbose = false, + show_progress = false) + # the serial entry on a one-dimensional list returns a result + direct = SFC.serial_calculate_structure_function(SFT.L2SFType(), x1, u, bins; verbose = false, show_progress = false) + ref_s, ref_c = _line_pair_loop(SFT.L2SFType(), x, u, bins, ones_w, Val(1), Val(1), Val(0)) + Test.@test direct isa RAW + Test.@test direct.counts == UInt32.(ref_c) + Test.@test _close(direct.sums, ref_s) +end + +Test.@testset "the sorted route is linear in the points" begin + Random.seed!(4260) + bins = collect(range(0.0, 0.5; length = 21)) + small = rand(1, 2000) + SFC.calculate_structure_function(SFT.L2SFType(), small, randn(1, 2000), bins, Int64; backend = SERIAL, + verbose = false, show_progress = false) + N = 100_000 + x = rand(1, N) .* 100.0 + u = randn(1, N) + t = @elapsed res = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins, Int64; backend = SERIAL, + verbose = false, show_progress = false, output_type = RAW) + Test.@test sum(res.counts) > 0 + Test.@test t < 2.0 +end diff --git a/test/test_spectra_lagspace.jl b/test/test_spectra_lagspace.jl new file mode 100644 index 0000000..f5c10de --- /dev/null +++ b/test/test_spectra_lagspace.jl @@ -0,0 +1,343 @@ +using Test: Test +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO, HelperFunctions as SFH +using StructureFunctions.MultiFields: Fields +using Bessels: Bessels +using FFTW: FFTW +using SpectralBackends: SpectralBackends as SB +using ComputationalBackends: ComputationalBackends as CB +using Distances: Distances as DI +using StaticArrays: StaticArrays as SA +using Random: Random +using Statistics: mean, var + +const FFT_TAG = SB.FastFourierTransformSpectralBackend() + +# The gradient of a Gaussian-correlated potential on the plane, in the package's convention that a +# density integrates over d²k to the variance: C_LL(0) = C_TT(0) = 1/ℓ², P_E = k² P_Φ / (2π)². +function _gradient_gaussian(ℓ) + CLL(r) = (1 / ℓ^2 - r^2 / ℓ^4) * exp(-r^2 / (2ℓ^2)) + CTT(r) = exp(-r^2 / (2ℓ^2)) / ℓ^2 + DLL(r) = 2 * (1 / ℓ^2 - CLL(r)) + DTT(r) = 2 * (1 / ℓ^2 - CTT(r)) + PE(k) = k^2 * 2π * ℓ^2 * exp(-k^2 * ℓ^2 / 2) / (2π)^2 + return DLL, DTT, PE +end + +Test.@testset "the two-line Helmholtz inversion recovers gradient and curl spectra" begin + ℓ = 0.7 + DLL, DTT, PE = _gradient_gaussian(ℓ) + edges = collect(range(0.0, 40ℓ; length = 20_001)) + mids = collect(SF.midpoints(edges)) + kq = collect(range(0.3, 6.0; length = 60)) + exact = PE.(kq) + scale = maximum(exact) + asym = 4 / ℓ^2 + + L2 = SF.StructureFunction(SFT.L2SFType(), edges, DLL.(mids)) + T2 = SF.StructureFunction(SFT.T2SFType(), edges, DTT.(mids)) + spec = SFC.helmholtz_spectra(L2, T2, kq; asymptote = asym) + Test.@test maximum(abs, spec.divergent .- exact) < 2e-3 * scale + Test.@test maximum(abs, spec.rotational) < 2e-3 * scale + + # the curl of the same potential swaps the two projections and the two spectra + L2c = SF.StructureFunction(SFT.L2SFType(), edges, DTT.(mids)) + T2c = SF.StructureFunction(SFT.T2SFType(), edges, DLL.(mids)) + specc = SFC.helmholtz_spectra(L2c, T2c, kq; asymptote = asym) + Test.@test maximum(abs, specc.rotational .- exact) < 2e-3 * scale + Test.@test maximum(abs, specc.divergent) < 2e-3 * scale + + # the sum of the two is the trace's spectrum, by construction of the first line + trace = SFC.isotropic_spectrum(SFT.S2SFType(), mids, DLL.(mids) .+ DTT.(mids), kq, Val(2); asymptote = asym) + Test.@test spec.rotational .+ spec.divergent ≈ trace rtol = 1e-12 + + # sums-and-counts inputs give the same answer, and empty bins are dropped from both + counts = ones(UInt32, length(mids)) + counts[7] = 0 + rawL = SF.StructureFunctionSumsAndCounts(SFT.L2SFType(), edges, DLL.(mids) .* counts, counts) + rawT = SF.StructureFunctionSumsAndCounts(SFT.T2SFType(), edges, DTT.(mids) .* counts, counts) + spec2 = SFC.helmholtz_spectra(rawL, rawT, kq; asymptote = asym) + Test.@test maximum(abs, spec2.divergent .- exact) < 2e-3 * scale + + # the arguments are the two projections, in that order, on one set of bins + Test.@test_throws ArgumentError SFC.helmholtz_spectra(T2, L2, kq) + Test.@test_throws ArgumentError SFC.helmholtz_spectra( + L2, SF.StructureFunction(SFT.T2SFType(), 2 .* edges, DTT.(mids)), kq) + Test.@test_throws ArgumentError SFC.helmholtz_spectra( + SF.StructureFunction(SFT.S2SFType(), edges, DLL.(mids)), T2, kq) +end + +# The Blackman–Tukey estimator written out: the unbiased autocovariance from the pairs a lag names on +# the grid as given, weighted by the taper, transformed on the padded grid `P`. +function _bt_reference(u, dims, spacing, periodic, P, weight) + D = size(u, 1) + N = prod(dims) + uf = reshape(u, D, N) + σ2 = sum(var(uf[c, :]; corrected = false) for c in 1:D) + Dg = length(dims) + cov = zeros(P) + cart = CartesianIndices(dims) + lin = LinearIndices(dims) + for I in CartesianIndices(P) + h = ntuple(d -> (m = I[d] - 1; m > P[d] ÷ 2 ? m - P[d] : m), Dg) + acc = 0.0 + n = 0 + for c in cart + j = ntuple(d -> c[d] + h[d], Dg) + ok = true + j = ntuple(Dg) do d + if periodic[d] + mod(j[d] - 1, dims[d]) + 1 + else + (1 <= j[d] <= dims[d]) || (ok = false) + j[d] + end + end + ok || continue + acc += sum(abs2, uf[:, lin[j...]] .- uf[:, lin[c]]) + n += 1 + end + n == 0 && continue + r = sqrt(sum(d -> (h[d] * spacing[d])^2, 1:Dg)) + cov[I] = weight(r) * (σ2 - acc / (2n)) + end + dens = real.(FFTW.fft(cov)) .* (prod(abs, spacing) / (2π)^Dg) + return σ2, dens +end + +Test.@testset "the bounded-domain estimator is the transform of the unbiased autocovariance" begin + Random.seed!(8100) + for (dims, spacing, periodic) in (((14,), (0.3,), (false,)), ((9, 7), (0.2, 0.25), (false, false)), + ((8, 7), (0.2, 0.25), (true, false))) + Dg = length(dims) + u = randn(Dg, dims...) + s = SFC.UniformLagSchedule(dims, spacing, periodic) + r_max = sqrt(sum(d -> (periodic[d] ? (dims[d] ÷ 2) * spacing[d] : (dims[d] - 1) * spacing[d])^2, 1:Dg)) + for (taper, weight) in ((SFC.NoTaper(), r -> 1.0), (SFC.Bartlett(), r -> max(0.0, 1 - r / r_max)), + (SFC.GaussianTaper(0.5), r -> exp(-r^2 / 0.5))) + kax, dens = SFC.gridded_spectrum(u, s, Val(Dg), FFT_TAG; taper) + P = size(dens) + Test.@test all(d -> periodic[d] ? P[d] == dims[d] : P[d] >= 2dims[d] - 1, 1:Dg) + Test.@test all(d -> length(kax[d]) == P[d], 1:Dg) + σ2, ref = _bt_reference(u, dims, spacing, periodic, P, weight) + Test.@test maximum(abs, dens .- ref) < 1e-12 * maximum(abs, ref) + # the density integrates to the variance of the cells, whatever the taper: w(0) = 1 + dk = prod(d -> kax[d][2] - kax[d][1], 1:Dg) + Test.@test sum(dens) * dk ≈ σ2 rtol = 1e-10 + end + end +end + +Test.@testset "a bounded window of a periodic field converges to its spectrum as the window grows" begin + # A single line seen through a window: the line's power spreads over the window's spectral kernel, + # whose width in wavenumber is the resolution 2π/(P dx). At a fixed physical distance from the line + # the leaked power therefore falls with the window, as 1/n for the boxcar of lags |h| < n. The + # unbiased autocovariance is not positive-definite, so the leaked power carries a sign. + A, dx = 1.3, 0.1 + δ = 3 * 2π / (32 * dx) # three bins of the coarsest window + outside = Float64[] + for n in (32, 64, 128) + M = n ÷ 16 # periods in the window + k0 = 2π * M / (n * dx) + x = (0:(n - 1)) .* dx + u = reshape(A .* cos.(k0 .* x .+ 0.4), 1, n) + s = SFC.UniformLagSchedule((n,), (dx,), (false,)) + kax, dens = SFC.gridded_spectrum(u, s, Val(1), FFT_TAG) + dk = kax[1][2] - kax[1][1] + near = abs.(abs.(kax[1]) .- k0) .<= δ + push!(outside, abs(sum(dens[.!near]) * dk) / (A^2 / 2)) + Test.@test sum(dens) * dk ≈ var(vec(u); corrected = false) rtol = 1e-10 + end + Test.@test issorted(outside; rev = true) + Test.@test outside[1] > 1.5 * outside[end] + Test.@test outside[end] < 0.05 +end + +Test.@testset "the Bartlett taper trims the estimator's variance" begin + # A Gaussian-correlated periodic field, windowed: the far lags are averaged over few pairs, and + # weighting them down lowers the scatter of the estimate across realisations. + Random.seed!(8200) + n_big, n, dx, ℓ = 512, 64, 0.1, 0.4 + kfull = 2π .* FFTW.fftfreq(n_big, 1 / dx) + s = SFC.UniformLagSchedule((n,), (dx,), (false,)) + plain = Vector{Vector{Float64}}() + tapered = Vector{Vector{Float64}}() + kax = nothing + for _ in 1:40 + amp = exp.(-(kfull .* ℓ) .^ 2 ./ 4) + f = real.(FFTW.ifft(amp .* FFTW.fft(randn(n_big)))) + u = reshape(f[1:n], 1, n) + kax, d0 = SFC.gridded_spectrum(u, s, Val(1), FFT_TAG) + _, d1 = SFC.gridded_spectrum(u, s, Val(1), FFT_TAG; taper = SFC.Bartlett()) + push!(plain, d0) + push!(tapered, d1) + end + band = findall(k -> 0.5 <= k <= 4.0, kax[1]) + v0 = mean(var([p[j] for p in plain]) for j in band) + v1 = mean(var([p[j] for p in tapered]) for j in band) + Test.@test v1 < 0.85 * v0 + # and both keep the mean level of the band + m0 = mean(mean(p[j] for p in plain) for j in band) + m1 = mean(mean(p[j] for p in tapered) for j in band) + Test.@test isapprox(m0, m1; rtol = 0.25) +end + +Test.@testset "a lag no held pair names is refused by default and zeroed on request" begin + n = 16 + u = reshape(randn(n), 1, n) + valid = falses(n) + valid[1:3] .= true # lags 4…8 join no two held cells + s = SFC.UniformLagSchedule((n,), (0.1,), (true,)) + Test.@test_throws ArgumentError SFC.gridded_spectrum(u, s, Val(1), FFT_TAG; valid) + kax, dens = SFC.gridded_spectrum(u, s, Val(1), FFT_TAG; valid, missing_lags = SFC.ZeroDeviationAtMissingLags()) + Test.@test all(isfinite, dens) + dk = kax[1][2] - kax[1][1] + Test.@test sum(dens) * dk ≈ var(u[1, 1:3]; corrected = false) rtol = 1e-10 +end + +# P_0 … P_L and their derivatives at x, by the recurrences, for the test's own series. +function _legendre_and_derivative(x, L) + P = zeros(L + 1) + dP = zeros(L + 1) + P[1] = 1.0 + L >= 1 && (P[2] = x; dP[2] = 1.0) + for l in 1:(L - 1) + P[l + 2] = ((2l + 1) * x * P[l + 1] - l * P[l]) / (l + 1) + dP[l + 2] = dP[l] + (2l + 1) * P[l + 1] + end + return P, dP +end + +Test.@testset "the spherical inversion recovers a prescribed angular spectrum" begin + R = 6.371e6 + g = SFH.SphericalGeometry{2}(SFH.SphericalDistance(R), R) + L = 10 + Cl = [0.0; [1.7 / (l + 1)^2 for l in 1:L]] + edges_σ = collect(range(0.0, π; length = 4001)) + mids_σ = collect(SF.midpoints(edges_σ)) + edges = R .* edges_σ + + # a scalar: C(σ) = Σ (2l+1)/(4π) C_l P_l(cos σ), D = 2[C(0) − C] + C(σ) = sum((2l + 1) / (4π) * Cl[l + 1] * _legendre_and_derivative(cos(σ), L)[1][l + 1] for l in 0:L) + D = [2 * (C(0.0) - C(σ)) for σ in mids_σ] + for op in (SFT.ScalarSFType{2}(), SFT.S2SFType()) + sf = SF.StructureFunction(op, edges, D) + out = SFC.isotropic_spectrum(sf, g, L + 2) + Test.@test out.l == 1:(L + 2) + Test.@test maximum(abs, out.C[1:L] .- Cl[2:end]) < 1e-5 * maximum(Cl) + Test.@test maximum(abs, out.C[(L + 1):end]) < 1e-5 * maximum(Cl) + end + Test.@test_throws ArgumentError SFC.isotropic_spectrum(SF.StructureFunction(SFT.L2SFType(), edges, D), g, L) + Test.@test_throws ArgumentError SFC.isotropic_spectrum( + SF.StructureFunction(SFT.S2SFType(), 2 .* edges, D), g, L) # beyond a half turn + raw = SF.StructureFunctionSumsAndCounts(SFT.S2SFType(), edges, D .* 3, fill(UInt32(3), length(D))) + Test.@test SFC.isotropic_spectrum(raw, g, L).C ≈ SFC.isotropic_spectrum(SF.StructureFunction(SFT.S2SFType(), edges, D), g, L).C + raw.counts[5] = 0 + Test.@test_throws ArgumentError SFC.isotropic_spectrum(raw, g, L) + + # a tangent vector field: ξ₊ from d^l_{11}, ξ₋ from d^l_{1,−1}, both in closed form from P_l, P_l' + CE = [0.0; [0.9 / l^2 for l in 1:L]] + CB = [0.0; [0.4 / (l + 2)^2 for l in 1:L]] + variance = sum((2l + 1) / (4π) * (CE[l + 1] + CB[l + 1]) for l in 1:L) + function ξ(σ) + x = cos(σ) + P, dP = _legendre_and_derivative(x, L) + plus = 0.0 + minus = 0.0 + for l in 1:L + d11 = (l * (l + 1) * P[l + 1] + (1 - x) * dP[l + 1]) / (l * (l + 1)) + d1m1 = (-l * (l + 1) * P[l + 1] + (1 + x) * dP[l + 1]) / (l * (l + 1)) + plus += (2l + 1) / (4π) * (CE[l + 1] + CB[l + 1]) * d11 + minus -= (2l + 1) / (4π) * (CE[l + 1] - CB[l + 1]) * d1m1 + end + return plus, minus + end + DLL = Float64[] + DTT = Float64[] + for σ in mids_σ + p, m = ξ(σ) + push!(DLL, 2 * (variance / 2 - (p + m) / 2)) + push!(DTT, 2 * (variance / 2 - (p - m) / 2)) + end + L2 = SF.StructureFunction(SFT.L2SFType(), edges, DLL) + T2 = SF.StructureFunction(SFT.T2SFType(), edges, DTT) + out = SFC.helmholtz_spectra(L2, T2, g, L + 2; variance) + Test.@test maximum(abs, out.E[1:L] .- CE[2:end]) < 1e-5 * maximum(CE) + Test.@test maximum(abs, out.B[1:L] .- CB[2:end]) < 1e-5 * maximum(CE) + Test.@test maximum(abs, out.E[(L + 1):end]) < 1e-5 * maximum(CE) + Test.@test maximum(abs, out.B[(L + 1):end]) < 1e-5 * maximum(CE) + Test.@test_throws UndefKeywordError SFC.helmholtz_spectra(L2, T2, g, L) +end + +# Fibonacci points and a degree-2 harmonic Φ = xy with its surface gradient in (east, north). +function _sphere_harmonic_field(N) + φg = (1 + sqrt(5)) / 2 + x = Matrix{Float64}(undef, 2, N) + Φ = Vector{Float64}(undef, N) + u = Matrix{Float64}(undef, 2, N) + for i in 1:N + lat = asin(1 - 2 * (i - 0.5) / N) + lon = mod(2π * i / φg, 2π) + x[1, i] = lon + x[2, i] = lat + p = SA.SVector(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat)) + Φ[i] = p[1] * p[2] + grad = SA.SVector(p[2], p[1], 0.0) + tang = grad - (grad ⋅ p) * p + E = SA.SVector(-sin(lon), cos(lon), 0.0) + Nn = SA.SVector(-sin(lat) * cos(lon), -sin(lat) * sin(lon), cos(lat)) + u[1, i] = tang ⋅ E + u[2, i] = tang ⋅ Nn + end + return x, Φ, u +end +using LinearAlgebra: ⋅ + +Test.@testset "the spherical inversion of the package's own pair sums" begin + # Φ = xy is a pure l = 2 harmonic: C_2 = 4π⟨Φ²⟩/5 and every other C_l vanishes; its gradient has + # C^E_2 = l(l+1) C^Φ_2 and no curl. Pair sums over a point set carry Monte-Carlo scatter. + N = 4000 + x, Φ, u = _sphere_harmonic_field(N) + g = SFH.SphericalGeometry{2}(SFH.SphericalDistance(1.0), 1.0) + edges = collect(range(0.0, π; length = 41)) + meanΦ2 = sum(abs2, Φ) / N + l = 2 + C2 = 4π * meanΦ2 / 5 + + sfΦ = SFC.calculate_structure_function(SFT.ScalarSFType{2}(), x, Fields(scalars = (Φ,)), edges; + distance_metric = SFH.SphericalDistance(1.0), backend = CB.SerialBackend(), + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false) + Test.@test all(>(0), sfΦ.counts) + outΦ = SFC.isotropic_spectrum(sfΦ, g, 6) + Test.@test abs(outΦ.C[2] - C2) < 0.03 * C2 + Test.@test all(abs.(outΦ.C[[1, 3, 4, 5, 6]]) .< 0.03 * C2) + + nb = length(edges) - 1 + sL = zeros(nb); cL = zeros(Int, nb) + SFC.calculate_structure_function!(sL, cL, SFT.L2SFType(), x, u, edges; distance_metric = SFH.SphericalDistance(1.0)) + sT = zeros(nb); cT = zeros(Int, nb) + SFC.calculate_structure_function!(sT, cT, SFT.T2SFType(), x, u, edges; distance_metric = SFH.SphericalDistance(1.0)) + L2 = SF.StructureFunctionSumsAndCounts(SFT.L2SFType(), edges, sL, cL) + T2 = SF.StructureFunctionSumsAndCounts(SFT.T2SFType(), edges, sT, cT) + variance = sum(abs2, u) / N + Test.@test variance ≈ l * (l + 1) * meanΦ2 rtol = 0.02 + out = SFC.helmholtz_spectra(L2, T2, g, 6; variance) + E2 = l * (l + 1) * C2 + Test.@test abs(out.E[2] - E2) < 0.05 * E2 + Test.@test all(abs.(out.E[[1, 3, 4, 5, 6]]) .< 0.05 * E2) + Test.@test all(abs.(out.B) .< 0.05 * E2) +end + +Test.@testset "helmholtz_decompose_2d carries each component's own counts" begin + edges = collect(range(0.0, 2.0; length = 11)) + mids = SF.midpoints(edges) + DLL = [r^(2 / 3) for r in mids] + DTT = (5 / 3) .* DLL + cL = fill(UInt32(4), 10) + cT = fill(UInt32(7), 10) + h = SFC.helmholtz_decompose_2d(edges, DLL .* cL, cL, DTT .* cT, cT) + Test.@test h.rotational_counts == cT + Test.@test h.divergent_counts == cL + Test.@test h.rotational_sums ./ h.rotational_counts .+ h.divergent_sums ./ h.divergent_counts ≈ DLL .+ DTT + Test.@test eltype(h.rotational_sums) == Float64 +end diff --git a/test/test_stability.jl b/test/test_stability.jl index ee6d5ad..34b7b01 100644 --- a/test/test_stability.jl +++ b/test/test_stability.jl @@ -32,6 +32,4 @@ Test.@testset "Stability Verification" begin u_batched = rand(FT, 2, N, 2) @inferred SFC.calculate_structure_functions_single_pass(x, u_batched, bins; backend = CB.SerialBackend()) - # 2. Distributed Stability Check (if DistributedExt is loaded) - # We'll just check if the method exists for now, or skip if not tested here. end diff --git a/test/test_tensor_khm.jl b/test/test_tensor_khm.jl index 5b80f8a..4a53738 100644 --- a/test/test_tensor_khm.jl +++ b/test/test_tensor_khm.jl @@ -1,9 +1,15 @@ using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, - StructureFunctionTypes as SFT + StructureFunctionTypes as SFT, HelperFunctions as SFH +using StructureFunctions: StructureFunctionObjects as SFO, MultiFields as MF using OhMyThreads: OhMyThreads using KernelAbstractions: KernelAbstractions as KA using Distances: Distances as DI +using StaticArrays: StaticArrays as SA +using LinearAlgebra: LinearAlgebra as LA +using FFTW: FFTW +using SpectralBackends: SpectralBackends as SB +using FlowGeometries: FlowGeometries as FG using Random: Random using Test: Test @@ -149,3 +155,179 @@ Test.@testset "every backend computes the same tensor" begin Test.@test ts.counts == rs.counts Test.@test isapprox(ts.sums, rs.sums; rtol = 1e-10, atol = 1e-12) end + +# --- Tensors from the transform, higher orders, and the joint tensor over angle --- + +const RAW_T = SF.StructureFunctionTensorSumsAndCounts +const RAW_T2 = SFO.StructureFunctionTensor2DSumsAndCounts +const FFT_TAG = SB.FastFourierTransformSpectralBackend() + +# Grid coordinates as a point list, in the cell order the packed field uses. +function _tensor_grid_points(dims, spacing) + Dg = length(dims) + x = zeros(Float64, Dg, prod(dims)) + for (k, I) in enumerate(CartesianIndices(dims)), d in 1:Dg + x[d, k] = (I[d] - 1) * spacing[d] + end + return x +end + +# The rank-P moment tensor of a point set by brute force: Σ over pairs of δu^{⊗P}, per (lo, hi] bin, +# an odd rank read from the lower to the upper end along the first coordinate that separates the pair. +function _brute_tensor(P, x, u, bins) + D = size(u, 1) + nb = length(bins) - 1 + sums = zeros(ntuple(_ -> D, P)..., nb) + counts = zeros(Int, nb) + N = size(x, 2) + for i in 1:(N - 1), j in (i + 1):N + dx = x[:, j] .- x[:, i] + r = LA.norm(dx) + b = searchsortedfirst(bins, r) - 1 + 1 <= b <= nb || continue + du = u[:, j] .- u[:, i] + if isodd(P) + lead = dx[findfirst(!iszero, dx)] + du = (lead > 0 ? 1 : -1) .* du + end + for I in CartesianIndices(ntuple(_ -> D, P)) + sums[I, b] += prod(du[I[k]] for k in 1:P) + end + counts[b] += 1 + end + return sums, counts +end + +Test.@testset "the tensor from the transform equals the point tensor on a grid's points" begin + Random.seed!(4100) + geo = FG.Geometry.CartesianGeometry() + for (dims, spacing, orders) in (((9, 6), (0.1, 0.2), (2, 3, 4)), ((5, 4, 4), (0.2, 0.25, 0.3), (2, 3))) + Dg = length(dims) + N = prod(dims) + grid = FG.Grids.StructuredGrid(geo, ntuple(d -> range(0.0, step = spacing[d], length = dims[d]), Dg)...) + u = randn(Dg, dims...) + x = _tensor_grid_points(dims, spacing) + r_max = 0.7 * sum(d -> spacing[d] * dims[d], 1:Dg) + bins = collect(range(0.0, r_max; length = 7)) .+ 1e-3 + for P in orders + ref = SFC.calculate_structure_function_tensor(Val(P), x, reshape(u, Dg, N), bins; backend = CB.SerialBackend(), + output_type = RAW_T) + for tag in (FFT_TAG, SB.AutoSpectralBackend()), backend in (CB.SerialBackend(), CB.ThreadedBackend()) + got = SFC.calculate_structure_function_tensor(Val(P), grid, u, bins, tag; backend, verbose = false, + output_type = RAW_T) + Test.@test got.counts == ref.counts + Test.@test isapprox(got.sums, ref.sums; rtol = 1e-9, atol = 1e-10 * maximum(abs, ref.sums)) + end + # a masked field: the point tensor over the held cells + um = copy(u) + umf = reshape(um, Dg, N) + held = rand(N) .< 0.75 + umf[1, .!held] .= NaN + refm = SFC.calculate_structure_function_tensor(Val(P), x[:, held], umf[:, held], bins; + backend = CB.SerialBackend(), output_type = RAW_T) + gotm = SFC.calculate_structure_function_tensor(Val(P), grid, um, bins, FFT_TAG; verbose = false, + output_type = RAW_T) + Test.@test gotm.counts == refm.counts + Test.@test isapprox(gotm.sums, refm.sums; rtol = 1e-9, atol = 1e-10 * maximum(abs, refm.sums)) + # weights of one change nothing but the count type + gotw = SFC.calculate_structure_function_tensor(Val(P), grid, u, bins, FFT_TAG; weights = ones(N), + count_eltype = Float64, verbose = false, output_type = RAW_T) + Test.@test gotw.counts ≈ ref.counts + Test.@test isapprox(gotw.sums, ref.sums; rtol = 1e-9, atol = 1e-10 * maximum(abs, ref.sums)) + end + # the averaged tensor is the default representation + mean = SFC.calculate_structure_function_tensor(Val(2), grid, u, bins, FFT_TAG; verbose = false) + Test.@test mean isa SF.StructureFunctionTensor{2} + ref2 = SFC.calculate_structure_function_tensor(Val(2), x, reshape(u, Dg, N), bins; backend = CB.SerialBackend()) + Test.@test isapprox(mean.values, ref2.values; rtol = 1e-9, atol = 1e-10, nans = true) + # one algorithm: the direct sum is refused, a multi-field of fields is refused + Test.@test_throws ArgumentError SFC.calculate_structure_function_tensor(Val(2), grid, u, bins, + SB.DirectSumSpectralBackend(); verbose = false) + Test.@test_throws ArgumentError SFC.calculate_structure_function_tensor( + Val(2), grid, MF.Fields(vectors = (u,), scalars = (randn(dims...),)), bins, FFT_TAG; verbose = false) + end +end + +Test.@testset "the tensor on a lat-lon grid is the point tensor in the geodesic frame" begin + Random.seed!(4110) + n_lon, n_lat = 15, 7 + lam = range(0.0, step = 2π / n_lon, length = n_lon) + phi = range(-1.1, step = 0.35, length = n_lat) + grid = FG.Grids.StructuredGrid(FG.Geometry.SphericalGeometry(1.0), lam, phi) + u = randn(2, n_lon, n_lat) + coords = FG.Grids.materialize(grid) + x = Matrix(hcat(coords[1], coords[2])') + bins = collect(range(0.0, π; length = 7)) .+ 1e-3 + for P in (2, 3) + ref = SFC.calculate_structure_function_tensor(Val(P), x, reshape(u, 2, :), bins; backend = CB.SerialBackend(), + distance_metric = SFH.SphericalDistance(1.0), output_type = RAW_T) + got = SFC.calculate_structure_function_tensor(Val(P), grid, u, bins, FFT_TAG; verbose = false, output_type = RAW_T) + Test.@test got.counts == ref.counts + Test.@test isapprox(got.sums, ref.sums; rtol = 1e-9, atol = 1e-10 * maximum(abs, ref.sums)) + Test.@test sum(ref.counts) > 0 + end +end + +Test.@testset "higher orders on points match brute force on every CPU backend" begin + Random.seed!(4120) + N = 40 + x = rand(2, N) + u = randn(2, N) + bins = collect(range(0.0, 1.2; length = 6)) + for P in (1, 4, 5) + ref_s, ref_c = _brute_tensor(P, x, u, bins) + for backend in (CB.SerialBackend(), CB.ThreadedBackend()) + got = SFC.calculate_structure_function_tensor(Val(P), x, u, bins; backend, output_type = RAW_T) + Test.@test got.counts == ref_c + Test.@test isapprox(got.sums, ref_s; rtol = 1e-11, atol = 1e-12) + end + end + Test.@test_throws ArgumentError SFC.calculate_structure_function_tensor(Val(4), x, u, bins; + backend = CB.GPUBackend(KA.CPU())) + Test.@test_throws ArgumentError SFT.MomentTensorOperator{2}()(SA.SVector(1.0, 0.0), SA.SVector(1.0, 0.0)) +end + +Test.@testset "the joint tensor over angle marginalises to the tensor and to the joint histogram" begin + Random.seed!(4130) + N = 60 + x = rand(2, N) + u = randn(2, N) + bins = collect(range(0.0, 1.0; length = 6)) + θbins = collect(range(prevfloat(0.0), π; length = 5)) + axis = SFC.SeparationAngleAxis(SA.SVector(1.0, 0.0)) + t1 = SFC.calculate_structure_function_tensor(Val(2), x, u, bins; backend = CB.SerialBackend(), output_type = RAW_T) + for backend in (CB.SerialBackend(), CB.ThreadedBackend()) + joint = SFC.calculate_structure_function_tensor(Val(2), x, u, bins, θbins; second_axis = axis, backend) + Test.@test joint isa RAW_T2 + Test.@test size(joint.sums) == (2, 2, 5, 4) + Test.@test dropdims(sum(joint.counts; dims = 2); dims = 2) == t1.counts + Test.@test isapprox(dropdims(sum(joint.sums; dims = 4); dims = 4), t1.sums; rtol = 1e-11, atol = 1e-12) + # the trace of the joint tensor is the joint histogram of S2 + s2 = SFC.serial_calculate_structure_function(SFT.S2SFType(), x, u, bins, θbins; second_axis = axis, + verbose = false, show_progress = false) + Test.@test joint.counts == s2.counts + Test.@test isapprox(joint.sums[1, 1, :, :] .+ joint.sums[2, 2, :, :], s2.sums; rtol = 1e-11, atol = 1e-12) + end + Test.@test_throws ArgumentError SFC.calculate_structure_function_tensor(Val(2), x, u, bins, θbins; second_axis = axis, + backend = CB.GPUBackend(KA.CPU())) + Test.@test_throws ArgumentError SFC.calculate_structure_function_tensor(Val(2), x, cat(u, 2u; dims = 3), bins, θbins; + second_axis = axis) + # on a grid, from the transform + dims, spacing = (9, 6), (0.1, 0.2) + grid = FG.Grids.StructuredGrid(FG.Geometry.CartesianGeometry(), range(0.0, step = 0.1, length = 9), + range(0.0, step = 0.2, length = 6)) + ug = randn(2, dims...) + xg = _tensor_grid_points(dims, spacing) + gbins = collect(range(0.0, 1.1; length = 6)) .+ 1e-3 + # angle edges placed between the angles a lattice can produce (its diagonals sit exactly on π/4 and 3π/4) + gθbins = [prevfloat(0.0); collect(range(0.3011, π - 0.3; length = 5)); π + 1e-9] + for P in (2, 3) + refj = SFC.calculate_structure_function_tensor(Val(P), xg, reshape(ug, 2, :), gbins, gθbins; second_axis = axis, + backend = CB.SerialBackend()) + gotj = SFC.calculate_structure_function_tensor(Val(P), grid, ug, gbins, gθbins, FFT_TAG; second_axis = axis, + verbose = false) + Test.@test gotj isa RAW_T2 + Test.@test gotj.counts ≈ refj.counts + Test.@test isapprox(gotj.sums, refj.sums; rtol = 1e-9, atol = 1e-10 * maximum(abs, refj.sums)) + end +end diff --git a/test/test_transforms.jl b/test/test_transforms.jl index 9c324d6..ad5717c 100644 --- a/test/test_transforms.jl +++ b/test/test_transforms.jl @@ -271,11 +271,16 @@ Test.@testset "the gridded transform survives missing data" begin end end -Test.@testset "the gridded transform refuses a bounded direction" begin - # A bounded direction has no natural Fourier basis, and picking one is a windowing choice. - Test.@test_throws ArgumentError SFC.gridded_spectrum( - zeros(1, 8), SFC.UniformLagSchedule((8,), (0.1,), (false,)), Val(1), - SB.FastFourierTransformSpectralBackend()) +Test.@testset "the gridded transform of a bounded direction is the windowed estimate" begin + # A bounded direction has no Fourier basis of its own, so its spectrum is the transform of the + # unbiased autocovariance on a padded lag grid: every lag |h| < n, and the variance conserved. + n, dx = 24, 0.1 + Random.seed!(2400) + u = randn(1, n) + kax, dens = SFC.gridded_spectrum(u, SFC.UniformLagSchedule((n,), (dx,), (false,)), Val(1), + SB.FastFourierTransformSpectralBackend()) + Test.@test length(kax[1]) == length(dens) >= 2n - 1 + Test.@test sum(dens) * (kax[1][2] - kax[1][1]) ≈ sum(abs2, u .- sum(u) / n) / n rtol = 1e-10 end Test.@testset "shell averaging conserves the spectrum" begin @@ -318,15 +323,15 @@ Test.@testset "the flux quadrature matches a closed-form integral" begin Test.@test all(<(0), got) end -Test.@testset "a flux needs a cross-channel moment" begin - # ⟨δφ δ𝓐_φ⟩ is a moment across two channels; the diagonal is a variance and carries no flux. +Test.@testset "a flux needs a cross-field moment" begin + # ⟨δφ δ𝓐_φ⟩ is a moment across two fields; the diagonal is a variance and carries no flux. for op in (SFT.VectorDotSFType(1, 1), SFT.ScalarDotSFType(2, 2)) err = Test.@test_throws ArgumentError SFC.assert_advective(op) Test.@test occursin("diagonal", err.value.msg) end for op in (SFT.S2SFType(), SFT.L2SFType(), SFT.L3SFType()) err = Test.@test_throws ArgumentError SFC.assert_advective(op) - Test.@test occursin("cross-channel", err.value.msg) + Test.@test occursin("cross-field", err.value.msg) end Test.@test SFC.assert_advective(SFT.VectorDotSFType(1, 2)) === nothing Test.@test SFC.assert_advective(SFT.ScalarDotSFType(1, 2)) === nothing @@ -335,6 +340,69 @@ Test.@testset "a flux needs a cross-channel moment" begin Test.@test_throws ArgumentError SFC.spectral_flux(SFT.S2SFType(), r, fill(1.0, 100), [1.0]) end +Test.@testset "third-order flux routes" begin + J0(x) = Bessels.besselj0(x) + J1(x) = Bessels.besselj1(x) + J2(x) = Bessels.besselj(2, x) + R = 3.0 + r = collect(range(0.0, R; length = 300_001)) + Ks = [0.7, 2.0, 5.0] + trapz(f) = sum((f[1:(end - 1)] .+ f[2:end]) ./ 2 .* diff(r)) + # the power-law family closes in Bessel functions: S3 = c·r gives −(c/2)(1 − J₀(KR)) on every route + c, c3, a = 1.3, 0.8, 0.6 + S3 = c .* r + expected = [-(c / 2) * (1 - J0(K * R)) for K in Ks] + Test.@test SFC.spectral_flux(SFT.S3SFType(), r, S3, Ks) ≈ expected rtol = 1e-6 + Test.@test SFC.spectral_flux(SFT.MixedSFType{1, 0, 2}(), r, S3, Ks) ≈ expected rtol = 1e-6 + L3 = c3 .* r # S3 = (1/3r²) d(r³ L3)/dr = (4/3) c3 r + Test.@test SFC.spectral_flux(SFT.L3SFType(), r, L3, (4c3 / 3) .* r, Ks) ≈ + [-(2c3 / 3) * (1 - J0(K * R)) for K in Ks] rtol = 1e-6 + Au = a .* r .^ 2 # SF_Aω = −∇² SF_Au = −4a + Test.@test SFC.enstrophy_flux(SFT.VectorDotSFType(1, 2), r, Au, Ks) ≈ [2a * (1 - J0(K * R)) for K in Ks] rtol = 1e-5 + Test.@test SFC.enstrophy_flux(SFT.VectorDotSFType(1, 2), r, Au, Ks) ≈ + SFC.spectral_flux(SFT.ScalarDotSFType(1, 2), r, fill(-4a, length(r)), Ks) rtol = 1e-5 + # the boundary terms carry the answer: the integrals alone are not within tolerance + for (i, K) in pairs(Ks) + Test.@test !isapprox(-(K^2 / 4) * trapz(S3 .* J2.(K .* r)), expected[i]; rtol = 1e-2) + Test.@test !isapprox(-(K^3 / 12) * trapz(L3 .* Bessels.besselj.(3, K .* r) .* r), -(2c3 / 3) * (1 - J0(K * R)); rtol = 1e-2) + Test.@test !isapprox((K^3 / 2) * trapz(Au .* (Bessels.besselj.(3, K .* r) .- J1.(K .* r)) ./ 2), 2a * (1 - J0(K * R)); rtol = 1e-2) + end + # a smooth isotropic family with nothing decayed at R: the three routes of each flux agree + ℓ = 1.5 + L(r) = c3 * r * exp(-r^2 / ℓ^2) + S(r) = (c3 / 3) * exp(-r^2 / ℓ^2) * (4r - 2r^3 / ℓ^2) # (1/3r²) d(r³ L)/dr + A(r) = (c3 / 6) * exp(-r^2 / ℓ^2) * (8 - 16r^2 / ℓ^2 + 4r^4 / ℓ^4) # (1/2r) d(r S)/dr + f14 = SFC.spectral_flux(SFT.VectorDotSFType(1, 2), r, A.(r), Ks) + Test.@test maximum(abs, f14) > 0.1 + Test.@test SFC.spectral_flux(SFT.S3SFType(), r, S.(r), Ks) ≈ f14 rtol = 1e-6 + Test.@test SFC.spectral_flux(SFT.L3SFType(), r, L.(r), S.(r), Ks) ≈ f14 rtol = 1e-6 + Auf(r) = a * r^2 * exp(-r^2 / ℓ^2) + Aω(r) = -a * exp(-r^2 / ℓ^2) * (4 - 12r^2 / ℓ^2 + 4r^4 / ℓ^4) # −(1/r) d(r Au')/dr + Lωω(r) = -2a * exp(-r^2 / ℓ^2) * (2r - 2r^3 / ℓ^2) # (2/r) ∫₀^r s Aω ds = −2 Au' + g17 = SFC.spectral_flux(SFT.ScalarDotSFType(1, 2), r, Aω.(r), Ks) + Test.@test maximum(abs, g17) > 0.1 + Test.@test SFC.enstrophy_flux(SFT.VectorDotSFType(1, 2), r, Auf.(r), Ks) ≈ g17 rtol = 1e-5 + Test.@test SFC.spectral_flux(SFT.MixedSFType{1, 0, 2}(), r, Lωω.(r), Ks) ≈ g17 rtol = 1e-6 + # result objects: bins both hold, in the operator order the relation needs + edges = collect(range(0.0, R; length = 41)) + mids = SF.midpoints(edges) + cnt = fill(UInt32(3), 40) + cnt[7] = 0 + keep = findall(>(0), cnt) + L3o = SF.StructureFunctionSumsAndCounts(SFT.L3SFType(), edges, 3 .* L.(mids) .* (cnt .> 0), cnt) + S3o = SF.StructureFunctionSumsAndCounts(SFT.S3SFType(), edges, 3 .* S.(mids) .* (cnt .> 0), cnt) + Test.@test SFC.spectral_flux(L3o, S3o, Ks) ≈ SFC.spectral_flux(SFT.L3SFType(), mids[keep], L.(mids[keep]), S.(mids[keep]), Ks) + Test.@test SFC.spectral_flux(S3o, Ks) ≈ SFC.spectral_flux(SFT.S3SFType(), mids[keep], S.(mids[keep]), Ks) + Test.@test_throws ArgumentError SFC.spectral_flux(S3o, L3o, Ks) + Auo = SF.StructureFunction(SFT.VectorDotSFType(1, 2), edges, Auf.(mids)) + Test.@test SFC.enstrophy_flux(Auo, Ks) ≈ SFC.enstrophy_flux(SFT.VectorDotSFType(1, 2), collect(mids), Auf.(mids), Ks) + # refusals + Test.@test_throws ArgumentError SFC.enstrophy_flux(SFT.VectorDotSFType(1, 1), r, Auf.(r), Ks) + Test.@test_throws ArgumentError SFC.enstrophy_flux(SFT.VectorDotSFType(1, 2), [1.0], [1.0], Ks) + Test.@test_throws DimensionMismatch SFC.spectral_flux(SFT.L3SFType(), r, L.(r), S.(r[1:10]), Ks) + Test.@test_throws ArgumentError SFC.spectral_flux(SFT.S3SFType(), reverse(r), S.(r), Ks) +end + Test.@testset "a result object carries into the flux relation" begin edges = collect(range(0.0, 10.0; length = 21)) sums = fill(2.0, 20)