Pipeline
CoarseGrainingEnergyFluxes.Pipeline.CoarseGrainBatchResult — Type
CoarseGrainBatchResult(grid, Nscales, batch_size; execution = SerialBackend())Batched result storage plus the per-slice CoarseGrainResult views a batch sweep writes into.
The batch axes trail: Π is (spatial..., Nscales, batch...) and the per-scale arrays are (Nscales, batch...), so slices[i] is a CoarseGrainResult of contiguous views into this storage. batch_size may hold any number of axes: (Nt,), (Nlevels,), (Nlevels, Nt). Π lives in the memory of execution and the per-scale arrays in host memory; under a DistributedBackend every array is shared with the worker processes (Distributed extension), which write the slices. slopes and spectrum_maps add the slopes and maps of CoarseGrainResult, the maps shaped like Π.
CoarseGrainingEnergyFluxes.Pipeline.CoarseGrainResult — Type
CoarseGrainResult(scales, Π, cumulative_energy, wavenumber, filtering_spectrum[, spectral_slope, spectrum_map,
slope_map])Results of a coarse-graining sweep over scales.
Fields
scales::AbstractVector{T}: filter scales ℓ in metersΠ::A: specific energy-flux maps (m² s⁻³) in one(spatial dims..., Nscales)array; scalesisselectdim(Π, ndims(Π), s)cumulative_energy::AbstractArray{T}: cumulative coarse specific KE ½⟨|ūℓ|²⟩ per scale (Sadek–Aluie Eq. 15); the residual's ½⟨|u − ūℓ|²⟩ underpass = Diagnostics.HighPass()wavenumber::AbstractVector{T}: filtering wavenumberk_ℓ = L/ℓper scalefiltering_spectrum::AbstractArray{T}: filtering spectral densityẼ(k_ℓ)per scale (Eq. 14), of the pass's cumulative energy (Diagnostics.filtering_spectrum)spectral_slope:d ln Ẽ/d ln k_ℓper scale underslopes = Diagnostics.Slopes(),nothingotherwisespectrum_map: the local spectrumẼ(x, k_ℓ), shaped likeΠ, underspectrum_maps = Diagnostics.SpectrumMaps(),nothingotherwiseslope_map: its slope per cell, under both,nothingotherwise
Examples
res = coarse_grain(u, v, grid; scales=[10e3, 20e3, 30e3], kernel=TopHatKernel())
# Access results:
res.scales[1] # First scale (10 km)
res.Π[:, :, 1] # Energy-flux map at 10 km (a copy; `@view res.Π[:, :, 1]` aliases it)
res.cumulative_energy[1] # cumulative coarse KE at 10 km
res.filtering_spectrum[1] # filtering spectral density at k_ℓ = res.wavenumber[1]CoarseGrainingEnergyFluxes.Pipeline.SetupReport — Type
SetupReportWhat check_setup found; show prints it as a report.
Fields
grid_kind::String,grid_size::Tuple: the gridspacing::Tuple,coarsest_spacing::Tuple: the smallest and largest physical distance between index-adjacent cells, per axis, in the units ofℓscale::Float64,cells_per_scale::Tuple:ℓ, andℓ / coarsest_spacingper axis — the fewest cellsℓspans anywhere on the gridkernel::String,mask_strategy::String,method::Stringexecution_requested::String,execution_resolved::String: the execution backend asked for, and the one that will runengine::String: which real-space engine class the filter will takeresolvable::Bool:ℓspans more than 2 cells on every axis everywhere on the gridsupports_flux::Bool: the kernel is non-negative, soτis realizable andΠis a pointwise transfersupports_spectrum::Bool:Kernels.transfer_monotone: the spectral density is guaranteed non-negative, and the defaultDiagnostics.AutoSpectrumcomputes it (NaNotherwise).Diagnostics.ForceSpectrum()computes it regardless.supports_spectral_method::Bool: the kernel has an isotropic transfer function, somethod = Spectral()is availableboundary_buffer_cells::Tuple: the kernel radius over the smallest spacing — how many cells from a coast or domain edge the result depends on the mask strategynotes::Vector{String}: everything above that needs acting on, in words
CoarseGrainingEnergyFluxes.Pipeline._batch_base — Method
_batch_base(batch, u, v, w, grid, Val(R), ctx, t) -> (; scratch, rate)What a batch's workers share, built once: entry 1 of each pool the caller supplied, and a workspace, per-scale filter plans and derivative route built here for each pool left nothing (filter_plans stays nothing where the workspace's generalized convolution reads none, _sweep_setup), with the rate route of slice t's fields. A family whose rate route is its real-space scale rates holds them, so the workers' copies share their tables. Worker 1 sweeps on scratch itself.
CoarseGrainingEnergyFluxes.Pipeline._result_maps — Method
_result_maps(execution, T, dims) -> AbstractArray{T}
_result_values(execution, T, dims) -> AbstractArray{T}Zeroed storage for a result's flux maps, in execution's memory, and for its per-scale values, in host memory. The Distributed extension gives a DistributedBackend memory the worker processes share.
CoarseGrainingEnergyFluxes.Pipeline._run_base! — Method
_run_base!(batch, u, v, w, grid, Val(R), ctx, slices) -> batchSweep slices on one base built from the first of them: the loop of a driver whose workers are separate processes.
CoarseGrainingEnergyFluxes.Pipeline._run_slices! — Method
_run_slices!(batch, u, v, w, grid, Val(R), ctx, slices, scratch) -> batchSweep each slice in slices on one worker's scratch and one rate route; the loop compiles against their concrete types.
CoarseGrainingEnergyFluxes.Pipeline._sweep_setup — Method
_sweep_setup(grid, batch_size, w, workspace, filter_plans, kernel, scales, execution, mask_strategy,
method, vector_filter, transform) -> (workspace, plans)The workspace a sweep runs on, workspace or one built for the vector filter vector_filter resolves to, and its per-scale plans: filter_plans, a family built here, or nothing where the workspace's generalized convolution filters every field and no plans are given.
CoarseGrainingEnergyFluxes.Pipeline._worker_scratch — Method
_worker_scratch(ctx, base, grid, p) -> (; workspace, filter_plans, deriv_plan)Worker p's scratch for a batch sweep: entry p of each pool the caller supplied, and for each pool left nothing a worker copy of the base's (Filtering.worker_copy), which shares its tables and holds its own buffers. A derivative plan is read-only and shared; a series gradient holds buffers and is built from the worker's plans.
CoarseGrainingEnergyFluxes.Pipeline.batch_concurrency — Method
batch_concurrency(ctx, nslices) -> IntHow many slices a batch may run at once: min(nslices, n), with n the length of the supplied scratch pools or Threads.nthreads() without any. A worker indexes its scratch by chunk, so no two workers share scratch.
CoarseGrainingEnergyFluxes.Pipeline.check_setup — Method
check_setup(grid, kernel, scale; execution, mask_strategy, method) -> SetupReportReport what a filter/flux call on this (grid, kernel, scale) will do and what it supports, without building a plan: it evaluates the dispatch predicates the plan builders use. It reports
- which real-space engine will run, and which execution backend the request resolves to;
- whether
ℓis meaningful on this grid at all (ℓ > 2Δx), and how many cells it spans; - whether this kernel can carry
Π(is it non-negative?) and a filtering spectrum (is|Ĝ|²monotone?), and whethermethod = Spectral()exists for it; - how wide the contaminated band along a coast or domain edge is.
Examples
julia> CGEF.check_setup(grid, CGEF.TopHatKernel(), 5000.0)CoarseGrainingEnergyFluxes.Pipeline.coarse_grain! — Method
coarse_grain!(result, u, v, w, grid; scales, kernel, workspace, filter_plans, deriv_plan, execution, mask_strategy,
method, vector_filter, transform, L, spectrum, derivative, scale_derivative)
coarse_grain!(result, u, v, grid; scales, ...) # no vertical componentIn-place coarse_grain: refills every buffer of an existing CoarseGrainResult. Supplying workspace, filter_plans and deriv_plan reuses the scratch and the per-scale plans as well, for a sweep repeated across timesteps. The workspace and result.Π live in the memory of the plans' backend, and the sweep's own loops run under the workspace's. A given workspace carries its own vector filter; vector_filter and transform build one when it is not given.
result must already be sized for length(scales) scales over grid's shape; a mismatch throws DimensionMismatch.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain — Method
coarse_grain(u, v, w, grid; scales, kernel=TopHatKernel(), execution=AutoBackend(), mask_strategy=ZeroFill(),
method=nothing, vector_filter=nothing, transform=AutoSpectralBackend(), L=1, spectrum=AutoSpectrum(),
derivative=AutoDerivative(), scale_derivative=AutoScaleDerivative(), slopes=NoSlopes(),
spectrum_maps=NoSpectrumMaps(), pass=LowPass())
coarse_grain(u, v, grid; scales, ...) # no vertical componentCoarse-graining analysis across scales, returning a new CoarseGrainResult. Allocating form of coarse_grain!, which reuses a result and workspace across calls. A one-component field on a 1-D grid takes coarse_grain(u, grid; …).
Arguments
u,v: the velocity components along the grid's first two directions (m/s), arrays of the grid's shape: one value per cell, a vector on a node setw: the vertical velocity, ornothing: on a 2-D grid a thin-layer third component, on a 3-D grid the third componentgrid: anyFlowGeometriesgrid: geometry, cells and active-cell mask
Keyword Arguments
scales::AbstractVector: Vector of filter scales ℓ in meters (e.g.,10e3:10e3:100e3)kernel::AbstractFilterKernel=TopHatKernel(): Filter kernelexecution::AbstractExecutionBackend=AutoBackend(): Execution backend of the filter and of the flux's own loops; the fields and the result'sΠlive in its memorymask_strategy::AbstractMaskStrategy=ZeroFill(): Masking strategy (ZeroFill()orDeformable()). UnderZeroFillthe kernel is position-independent, so filtering commutes with spatial derivatives. SeeFiltering.filter_field!for the boundary artifacts of both choices.method::Union{Nothing,AbstractFilterMethod}=nothing: filtering engine;nothingtakesplan_filter's per-grid default (real space where a grid has that engine)vector_filter::Union{Nothing,AbstractVectorFilter}=nothing: how the velocity and the stress are filtered on the surface of a sphere (Filtering.resolve_vector_filter).nothingtakes the generalized convolution of Aluie (2019) underZeroFill, whose spin transforms are NUFSHT's where it is loaded, FastSphericalHarmonics' on its own grids, and an in-core direct sum otherwise, and which reads no scalar filter plan, so none is built; underDeformableit takesFiltering.CartesianComponents().transform::AbstractSpectralBackend=AutoSpectralBackend(): the transform library ofmethod = Spectral()and of the generalized convolutionL::Real=1: reference length in the wavenumberk_ℓ = L/ℓ; it rescales the spectral density by1/L(seeDiagnostics.filtering_spectrum).spectrum::AbstractSpectrumPolicy=Diagnostics.AutoSpectrum(): how to fillfiltering_spectrum. The density is guaranteed non-negative only for a kernel whose|Ĝ|²is monotone decreasing (Kernels.transfer_monotone). The default computes it for such a kernel and fillsNaNfor any other, the defaultTopHatKernelincluded.Diagnostics.ForceSpectrum()computes it anyway (warning once),Diagnostics.StrictSpectrum()throws for a non-monotone kernel, andDiagnostics.NoSpectrum()always fillsNaN.Πandcumulative_energydo not depend on it.derivative::AbstractDerivative=Derivatives.AutoDerivative(): how the strain differentiates the filtered velocity: the filter's own derivative where its output is a series (method = Spectral()and the generalized convolution), a 5-node stencil or the least-squares gradient elsewhere (Derivatives.AbstractDerivative).scale_derivative::AbstractScaleDerivative=Diagnostics.AutoScaleDerivative(): how the density differentiatesE(ℓ)inℓ, exactly through the filter where its kernel allows, by differences across the scales otherwise.slopes::AbstractSlopes=Diagnostics.NoSlopes():Diagnostics.Slopes()fillsspectral_slope.spectrum_maps::AbstractSpectrumMaps=Diagnostics.NoSpectrumMaps():Diagnostics.SpectrumMaps()fillsspectrum_map, and withSlopes()slope_map.pass::AbstractFilterPass=Diagnostics.LowPass():Diagnostics.HighPass()takes the cumulative energy, spectrum, slopes and maps of the residualu − ū_ℓ(Zhao & Aluie 2025), which recover spectra tok⁻⁵with a top-hat or a Gaussian;Πdoes not depend on it.
Returns
CoarseGrainResult: Container with scales, Π maps, and spectrum
Examples
geom = SphericalGeometry(6371000.0)
grid = StructuredGrid(geom, lon_rad, lat_rad, mask)
scales = collect(10e3:10e3:100e3)
res = coarse_grain(u, v, grid; scales=scales, kernel=TopHatKernel())
plot(res.wavenumber, res.filtering_spectrum, xscale=:log10, yscale=:log10)
heatmap(res.Π[:, :, 3]) # 3rd scale is 30 kmCoarseGrainingEnergyFluxes.Pipeline.coarse_grain_batch! — Method
coarse_grain_batch!(batch, u, v, w, grid; scales, kernel, workspaces, filter_plans, deriv_plans, execution, mask_strategy, method, vector_filter, transform, L, spectrum) -> batch
coarse_grain_batch!(batch, u, v, grid; scales, ...) # no vertical componentRun a full coarse_grain! sweep per slice over a batch that shares one grid.
The grid fixes the spatial rank; every trailing dimension of u, v and w beyond it is a batch axis. Against a 2D grid, (x, y, t) is a time batch and (x, y, z, t) is Nlevels·Nt slices; against a true-3D grid an (x, y, z) array is a single slice.
On a host backend execution parallelizes over slices and each slice's sweep runs serially, as in Filtering.filter_slices!; a GPU backend computes the whole batch per scale, with u, v, w and batch in its memory (CoarseGrainBatchResult(…; execution)).
workspaces, filter_plans and deriv_plans are scratch pools indexed by worker: vectors of equal length, at least the concurrency used (Threads.nthreads() suffices), make a repeated batch allocation-free; Filtering.worker_copy of one family makes a pool sharing its tables. A pool left nothing is built once and each further worker takes a worker copy of it.
coarse_grain_slices! takes slices on different grids. vector_filter, transform, the spectrum policy and pass behave as in coarse_grain.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain_batch_slice! — Method
coarse_grain_batch_slice!(batch, u, v, w, grid, Val(R), ctx, t, scratch, rate[, held]) -> analysisSlice t's sweep into batch.slices[t] on one worker's scratch (see _worker_scratch) and rate route, with the slice's execution backend ctx.inner; held is the analysis an earlier slice of the worker returned, whose spectra this one refills. Every host batch driver runs its slices through this.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain_profile! — Method
coarse_grain_profile!(batch, u, v, w, grid; scales, kernel, workspaces, filter_plans, deriv_plans, execution, mask_strategy, method, vector_filter, transform, L, spectrum) -> batch
coarse_grain_profile!(batch, u, v, grid; scales, ...) # no vertical componentVertical-profile sweep, in place: each vertical level is its own 2D/2.5D problem on the shared horizontal grid, filtered horizontally (see Diagnostics.compute_Π! on the thin-layer regime). Runs coarse_grain_batch! with the level axis as the batch axis.
batch is a CoarseGrainBatchResult with batch size (Nlevels,): Π is (Nx, Ny, Nscales, Nlevels) and cumulative_energy/filtering_spectrum are (Nscales, Nlevels). Energies are per level; a vertical sum needs thickness weights, which this function does not take.
The spectrum policy behaves as in coarse_grain.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain_profile — Method
coarse_grain_profile(u, v, w, grid; scales, kernel=TopHatKernel(), execution=AutoBackend(), mask_strategy=ZeroFill(), method=nothing, vector_filter=nothing, transform=AutoSpectralBackend(), L=1, spectrum=AutoSpectrum())Allocating coarse_grain_profile!: sizes a CoarseGrainBatchResult for size(u, 3) levels and fills it.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain_slice_serial! — Method
coarse_grain_slice_serial!(results, us, vs, ws, grids, ctx, t) -> results[t]Slice t's sweep with the slice's execution backend ctx.inner. The serial loop and every parallel slices driver run each slice through this.
CoarseGrainingEnergyFluxes.Pipeline.coarse_grain_slices! — Method
coarse_grain_slices!(results, us, vs, ws, grids; scales, kernel, workspaces, filter_plans, deriv_plans, execution, mask_strategy, method, vector_filter, transform, L, spectrum) -> results
coarse_grain_slices!(results, us, vs, grids; scales, ...) # no vertical componentRun a full coarse_grain! sweep per slice over a batch whose slices each carry their own grid: different regions, point counts or node sets. results is a vector of independent CoarseGrainResults; coarse_grain_batch! serves slices on one shared grid.
Slices are dispatched longest-first under a dynamic scheduler (see slice_pipeline_costs). Scratch is per slice: workspaces, filter_plans and deriv_plans, when given, hold one entry per slice, each built for that slice's grid. Each slice's sweep runs serially on a host backend, as in coarse_grain_batch!.
vector_filter, transform, the spectrum policy and pass behave as in coarse_grain.
CoarseGrainingEnergyFluxes.Pipeline.slice_pipeline_costs — Method
slice_pipeline_costs(grids, Nscales) -> Vector{Int}Relative per-slice sweep cost, points × scales, for longest-first scheduling of a ragged batch. It orders the slices and is not a time.
Visualization
CoarseGrainingEnergyFluxes.Visualization.plot_spectrum — Function
plot_spectrum(res; which=:density) -> FigurePlot the filtering spectrum from a CoarseGrainResult. which = :density plots the filtering spectral density Ẽ(k_ℓ) against filtering wavenumber k_ℓ (log x); which = :cumulative plots the cumulative coarse KE against scale ℓ (log–log). Provided by the CairoMakie package extension — run using CairoMakie to enable it.
CoarseGrainingEnergyFluxes.Visualization.plot_Π_map — Function
plot_Π_map(res, scale_idx, grid; colormap=:balance, title=nothing) -> FigureHeatmap of the cross-scale energy-flux map Π from a CoarseGrainResult at scale index scale_idx. Provided by the CairoMakie package extension — run using CairoMakie to enable it.