Discretization

The geometric inputs a numerical method needs from a grid: where a point falls, the weights that interpolate to it, where a cell's faces are, the metric factors of the coordinate system, and the finite-difference weights of any stencil.

All of it is a function of coordinates alone. The operators that apply it to a field — apply_stencil!, derivative!, the least-squares gradient and interpolate — live in Operators, and this page shows them alongside the inputs they read.

Centres and faces

using FlowGeometries: FlowGeometries as FG
D = FG.Discretization
O = FG.Operators
A = FG.Axes

x = [0.0, 1.0, 3.0, 6.0]
D.faces(x)
5-element Vector{Float64}:
 -0.5
  0.5
  2.0
  4.5
  7.5

N centres give N+1 faces, at the midpoints, with the outermost two extrapolated a half-cell beyond the end centres. Note that centres do not determine faces — the system is underdetermined by one — so that midpoint rule is a stated convention, the same one the curvilinear corner reconstruction uses.

A uniform axis keeps its uniformity, so nothing is lost by asking for its faces:

u = A.UniformAxis(0.0, 0.5, 6)
A.isuniform(D.faces(u)), A.spacing(D.faces(u)), length(D.faces(u))
(true, 0.5, 7)
length(D.nodes(u, D.Center())), length(D.nodes(u, D.Face()))
(6, 7)

Gaps and cell widths

local_spacing is the gap either side of one sample, and cell_width the width of one cell. Both are a scalar subtraction of two stored numbers — no array is built — so they are the forms to call per grid point. faces materializes the whole axis, which suits a sweep over all of it.

xs = cumsum([0.0, 1.0, 0.3, 2.5, 0.7, 4.0])
D.local_spacing(xs, 3), D.cell_width(xs, 3)
((0.30000000000000004, 2.5), 1.4)

cell_width is the distance between the cell's two faces.

The gaps are signed and the width is not. A derivative needs the sign, since it distinguishes an axis stored increasing from one stored decreasing; a width is a length and cannot be negative. Reverse the axis and cell i moves to n+1-i, where the gaps come back negated and swapped — the same two neighbours, now on the other side — while the width is unchanged:

xr = reverse(xs)                              # cell 3 of xs is cell 4 of xr
D.local_spacing(xr, 4), D.cell_width(xr, 4)
((-2.5, -0.30000000000000004), 1.4)

At a bounded end the outward gap is 0 and the caller falls back to a one-sided stencil. Given a period it wraps, so a seam behaves like the interior:

λ = collect(range(0, 2π * (1 - 1/8); length = 8))
D.local_spacing(λ, 8), D.local_spacing(λ, 8, 2π)
((0.7853981633974483, 0.0), (0.7853981633974483, 0.7853981633974483))

cell_widths is the whole axis at once. A uniform axis returns an Axes.ConstantVector — one number and a length — so nothing is materialized for it either:

D.cell_widths(u), D.cell_widths(xs)
(ConstantVector{Float64}(0.5, 6), [1.0, 0.65, 1.4, 1.6, 2.35, 4.0])

On a grid, Grids.local_spacing, Grids.cell_width and Grids.cell_widths take the direction's axis and its wrap period from the grid, so a periodic seam is right without being asked for — see the Grids page.

Point location

D.locate(u, 0.2), D.locate(u, 0.4), D.locate(u, -5.0)
(1, 2, 0)

locate returns the cell containing a coordinate, or 0 outside it. Cells are the intervals between faces, so cell 1 of u spans [-0.25, 0.25). It is O(1) on a uniform axis — a direct payoff of the spacing living in the type — and O(log n) by bisection on a stretched one. Both storage orders work.

D.locate(xs, 2.0), D.nearest_index(xs, 2.0)
(3, 3)

nearest_index always returns a valid index, clamping a coordinate outside the axis to the nearer end; exact ties go to the lower index. It brackets and compares, so it is O(log n) on a stretched axis and O(1) on a uniform one, and both paths compare the same two samples: a uniform axis and its collect hold the same numbers and agree about which is nearest.

Interpolation weights

i, w = D.interpolation_weights(xs, 2.0)
(3, (0.72, 0.27999999999999997))

Weights only — applying them is w[1]*f[i] + w[2]*f[i+1] at the call site. For higher order on an arbitrarily spaced axis, lagrange_weights is exact for polynomials up to nodes-1:

idx, wl = D.lagrange_weights(xs, 2.0, 4)
(2:5, [-1.0714285714285712, 1.8749999999999998, 0.35714285714285704, -0.16071428571428564])

Finite-difference weights

fd_weights is the recursion of Fornberg (1988), Math. Comp. 51, 699–706. One recursion covers every case: any derivative order, any node count (hence any order of accuracy), any evaluation point, and arbitrarily spaced nodes.

D.fd_weights([-1.0, 0.0, 1.0], 0.0, 1)      # centred first difference
3-element Vector{Float64}:
 -0.5
  0.0
  0.5
D.fd_weights([-1.0, 0.0, 1.0], 0.0, 2)      # centred second difference
3-element Vector{Float64}:
  1.0
 -2.0
  1.0
D.fd_weights([-2.0, -1.0, 0.0, 1.0, 2.0], 0.0, 1)   # fourth-order first derivative
5-element Vector{Float64}:
  0.08333333333333333
 -0.6666666666666666
  0.0
  0.6666666666666666
 -0.08333333333333333

With m nodes the weights are exact for polynomials of degree m-1, so the accuracy order is m - order. Nothing about that requires equal spacing:

D.fd_weights([-1.7, -0.4, 0.9], 0.0, 1)     # same order, unequal nodes
3-element Vector{Float64}:
 -0.14792899408284027
 -0.4733727810650888
  0.621301775147929

The axis form centres the stencil on a sample and shifts it inward at a boundary, so the node count — and therefore the accuracy order — holds at the two ends as well as the interior:

xg = collect(range(0.0, 1.0; length = 11))
idx1, w1 = D.fd_weights(xg, 1, 1, 5)        # at the first sample
idxm, wm = D.fd_weights(xg, 6, 1, 5)        # in the interior
idx1, idxm
(1:5, 4:8)

FG.Geometry.nonuniform_first_derivative is the three-node, first-derivative case of the same thing. Fed the gaps above it is a complete derivative at a point, exact for a quadratic on any spacing:

g(x) = 3x^2 - 2x + 5
FG.Geometry.nonuniform_first_derivative(g(xs[2]), g(xs[3]), g(xs[4]), D.local_spacing(xs, 3)...)
5.800000000000003

The gaps being signed, the same expression on a descending axis differentiates with respect to the coordinate, with no correction at the call site.

Applying a weight set

apply_stencil! applies a weight set along a single direction, the result left where the input was. Every convention that needs is already fixed: nothing to stagger, fd_weights' inward shift at a bounded end, wrapping on a periodic one — so no halo either.

x = collect(range(0.0, 2.0; length = 11))
f = @. 3x^2 - 2x + 5
out = similar(f)
O.apply_stencil!(out, f, x, 1; order = 1, nodes = 3)    # 6x - 2: exact for a quadratic, ends included
11-element Vector{Float64}:
 -2.0000000000000018
 -0.8000000000000025
  0.40000000000000213
  1.6000000000000014
  2.799999999999999
  4.000000000000002
  5.199999999999999
  6.400000000000002
  7.600000000000001
  8.800000000000008
 10.0

A stretched axis is equally exact, the weights being built per sample:

xs = [0.0, 0.11, 0.37, 0.9, 1.05, 1.6, 1.62, 2.0]
outs = similar(xs)
O.apply_stencil!(outs, (@. 3xs^2 - 2xs + 5), xs, 1; order = 1, nodes = 3)
8-element Vector{Float64}:
 -2.0000000000000044
 -1.339999999999999
  0.22000000000000064
  3.3999999999999986
  4.300000000000001
  7.60000000000008
  7.720000000000137
  9.9999999999999

Given a period the stencil stays centred and wraps, carrying the wrapped samples' coordinates across the seam so the spacing there is the true one, and the seam is no worse than the interior:

λ = collect(range(0, 2π; length = 65)[1:64])
o = similar(λ)
O.apply_stencil!(o, sin.(λ), λ, 1; order = 1, nodes = 5, period = 2π);
64-element Vector{Float64}:
 0.9999969069994239
 0.9951816485652625
 0.9807822468337912
 0.9569373759151976
 0.9238766749513591
 0.8819185365653742
 0.8314670405665537
 0.7730080624409581
 0.7071045941048641
 0.6343913219848526
 ⋮
 0.6343913219848523
 0.7071045941048647
 0.7730080624409568
 0.8314670405665545
 0.8819185365653743
 0.923876674951358
 0.9569373759151987
 0.9807822468337918
 0.9951816485652637

The grid form takes the axis, the wrap period and the mask from the grid, so a periodic direction wraps without being told. Where a mask bites, a cell whose stencil reads an inactive sample is written as masked:

geo = FG.Geometry.CartesianGeometry()
X = collect(range(0.0, 1.0; length = 9)); Y = collect(range(0.0, 2.0; length = 7))
F = [xi^2 + 3yi for xi in X, yi in Y]
mk = trues(9, 7); mk[5, 3] = false
gm = FG.Grids.StructuredGrid(geo, X, Y, mk)
Om = similar(F)
O.apply_stencil!(Om, F, gm, 1; order = 1, nodes = 3, masked = NaN)
Om[3:7, 3]                               # the masked cell and the two that read it
5-element Vector{Float64}:
   0.5
 NaN
 NaN
 NaN
   1.5

What a mask edge does to the stencil

Blanking is the default, and it is not free: a cell is blanked when any sample its window reads is inactive, so a single masked cell takes out up to nodes - 1 cells either side of it. A five-point derivative on a short axis can be annihilated outright by one hole.

The window already shifts inward at the end of an axis, precisely so the node count — and the accuracy order — survives a boundary. The end of an active run is the same situation, and ShiftWithinRun treats it that way:

xr = collect(0.0:1.0:6.0)
mr = trues(7, 1); mr[4, 1] = false
gr = FG.Grids.StructuredGrid(geo, xr, [0.0], mr)
fr = reshape(collect(0.0:6.0), 7, 1)         # f = x, so df/dx is exactly 1

blanked  = zeros(7, 1); shifted = zeros(7, 1)
O.apply_stencil!(blanked, fr, gr, 1; order = 1, nodes = 5, masked = NaN)
O.apply_stencil!(shifted, fr, gr, 1; order = 1, nodes = 5, masked = NaN,
                 policy = O.ShiftWithinRun())
vec(blanked), vec(shifted)
([NaN, NaN, NaN, NaN, NaN, NaN, NaN], [NaN, NaN, NaN, NaN, NaN, NaN, NaN])

Every cell is blanked in the first, and every active cell is exact in the second. The policies are:

policyat a run edge
BlankMaskedthe default — write masked wherever the window reads an inactive sample
ShiftWithinRunshift the window to fit inside the run, keeping nodes and the accuracy order; masked only where the run is shorter than nodes
ReduceInRunas above, and where the run cannot hold nodes, use the largest window it can, down to order + 1

ReduceInRun is the one policy that lowers the accuracy order without saying so, hence its own name: a narrow strait wants an answer at reduced order, and elsewhere ShiftWithinRun reports a run too short by writing masked.

A cell whose window already lies inside its run reuses the precomputed row, so a run's interior is bit-for-bit what BlankMasked gives, and only the cells within nodes - 1 of an edge cost anything extra. A run that wraps a periodic seam is a single run.

Build the weights once with axis_stencils to reuse them across many fields; applying a precomputed set allocates nothing.

idx, w = D.axis_stencils(X, 1, 3)
size(idx), size(w)
((9, 3), (9, 3))

The physical derivative

apply_stencil! differentiates with respect to a coordinate. On any curved geometry that is not the derivative a physical law is written in — that one is per unit distance, ∂f/∂sᵈ = (1/hᵈ)·∂f/∂ξᵈ. derivative! is the two together:

R   = 6.371e6
sph = FG.Geometry.SphericalGeometry(R)
lon = collect(range(0, 2π * (1 - 1/48); length = 48))
lat = collect(range(-π/2, π/2; length = 25))          # both poles are rows of this grid
gs  = FG.Grids.StructuredGrid(sph, lon, lat; topology = FG.Grids.Periodic())
fs  = [sin(φ) for _ in lon, φ in lat]
dn  = zeros(48, 25)
O.derivative!(dn, fs, gs, 2; order = 1, nodes = 5, masked = NaN)
dn[1, 12]                                             # ∂/∂north of sin φ, cos(φ)/R
1.5561688561297248e-7

Where the metric degenerates the derivative does not exist, and masked is written. Longitude at a pole is that case — h_λ = R cos φ → 0:

de = zeros(48, 25)
O.derivative!(de, [sin(λ) * cos(φ) for λ in lon, φ in lat], gs, 1;
              order = 1, nodes = 5, masked = NaN)
de[1, 1], de[1, 2]                                    # the pole row, and the row beside it
(NaN, 1.5695969758453316e-7)

A pole is a latitude stored as ±π/2 in the grid's element type, and there the scale factor is exactly zero, cos being taken as zero at that value. The test for a degenerate metric is then iszero, whatever the radius, the units or the element type.

The factor 1/hᵈ multiplies each value as it is written, so every cell written masked — inactive, blanked by the mask policy, or at a degenerate metric — holds exactly the masked you passed, -1.0 as much as NaN.

A divergence on a curved geometry is the flux form, on a sphere

\[\nabla\cdot\mathbf{u} = \frac{1}{R\cos\varphi}\left[\frac{\partial u_\lambda}{\partial\lambda} + \frac{\partial (u_\varphi\cos\varphi)}{\partial\varphi}\right]\]

whose second term differentiates the product u_φ·cos φ. On staggered faces the divergence is that flux form through each cell's own faces; see below.

Staggered operators

A scalar sits at cell centres, the velocity component along each direction on the faces normal to it, and each component of a rotation potential on the corners of its pair of directions, one array each, shaped by Grids.face_dims and Grids.corner_dims. One gradient defines the family:

\[D = -G^*, \qquad L = D\,G,\]

the adjoint under each cell's volume, the region its faces bound, and the face weight A·g, area times the distance between the centres a face separates. L is then symmetric and negative semidefinite, and curl ∘ G = 0 and D ∘ rot = 0 hold on every grid. A FaceMetrics holds every area, gap, edge length and corner area, built once:

sph = FG.Geometry.SphericalGeometry(6.371e6)
gs  = FG.Grids.StructuredGrid(sph, FG.Axes.PeriodicAxis(0.0, 2π, 48), collect(range(-1.3, 1.3; length = 24)))
fm  = O.face_metrics(gs, O.Dirichlet())
χ   = [sin(2λ) * cos(φ)^2 for λ in FG.Grids.coordinates(gs, 1), φ in FG.Grids.coordinates(gs, 2)]
gχ  = O.gradient!(O.allocate_faces(Float64, gs), χ, fm)
W   = O.curl!(O.allocate_corners(Float64, gs), gχ, fm);   # curl ∘ G: zero to round-off
([0.0 0.0 … 0.0 0.0; 0.0 0.0 … 0.0 0.0; … ; 0.0 -2.710251822968277e-29 … 2.710251822968277e-29 0.0; 0.0 0.0 … 0.0 0.0],)

A boundary condition is a face area: under Neumann the faces past the end of a bounded direction carry none in the operators, under Dirichlet they couple to a zero ghost, and a face against an inactive cell carries none under either. laplacian_coefficients assembles L with its null space, one constant per closed component, for a solver; coarsen builds the next grid of a multigrid hierarchy, and coarse_coefficients the operator rediscretized on it from the fine coupling areas, galerkin_coefficients the product R L P.

On a rectilinear grid the gap and the corner area are read at the face and the corner, so the operators are exact for a linear field on a Cartesian grid and second order on a sphere, and a value along a direction is taken along increasing coordinate whichever way the axis is stored.

Strain rate, vorticity and divergence

On a collocated grid strain_rate!, curl! and divergence! take a vector field along the local frame — east, north and up on a sphere — and add the frame's own turning to its derivatives, from Geometry.log_scale_gradients:

plans = O.stencil_plans(gs; nodes = 3)
uλ = [cos(φ) for _ in FG.Grids.coordinates(gs, 1), φ in FG.Grids.coordinates(gs, 2)]   # solid-body rotation
S  = O.strain_rate((uλ, zero(uλ)), gs, plans)
keys(S)
(:λλ, :φφ, :λφ)

Off a rectilinear grid: the least-squares gradient

apply_stencil! needs a separable axis to difference along. A CurvilinearGrid has none, and a node set's neighbours come from connectivity, so neither has a stencil. Operators.gradient_plan builds a least-squares gradient for them, and gradient! applies it:

cart = FG.Geometry.CartesianGeometry{Float64}()
nn   = 14
xg   = [t + 0.35u for t in range(0, 10; length = nn), u in range(0, 6; length = nn)]   # sheared
yg   = [u - 0.2t  for t in range(0, 10; length = nn), u in range(0, 6; length = nn)]
cgrid = FG.Grids.CurvilinearGrid(cart, xg, yg, trues(nn, nn); measure = fill(1.0, nn, nn))
plan  = FG.Operators.gradient_plan(cgrid)

fld = 2.0 .* xg .- 3.0 .* yg .+ 7
g1, g2 = zeros(nn, nn), zeros(nn, nn)
O.gradient!(g1, g2, fld, plan);          # g1 = 2 and g2 = -3 everywhere
([2.0000000000000004 2.0 … 1.9999999999999944 1.9999999999999993; 2.0 2.0 … 1.9999999999999978 2.000000000000001; … ; 1.9999999999999998 2.0000000000000004 … 1.9999999999999993 1.9999999999999996; 1.9999999999999982 2.0000000000000027 … 2.000000000000001 1.9999999999999998], [-2.9999999999999996 -2.999999999999999 … -2.9999999999999982 -3.0000000000000053; -2.999999999999999 -3.0 … -2.999999999999999 -2.9999999999999947; … ; -3.000000000000005 -3.000000000000001 … -3.0 -3.0000000000000036; -2.9999999999999956 -3.000000000000001 … -3.000000000000001 -3.0000000000000036])

Exact for a linear field on any stencil, however skewed, the least-squares combination cancelling the leading truncation term. It is second order on locally symmetric stencils and degrades toward first on strongly skewed cells, and where the stencil is separable and orthogonal it is the centred difference, so it agrees with apply_stencil! where both apply.

A depends only on the geometry, so the plan holds the per-neighbour coefficients and each apply is one dot product per cell, allocating nothing. Where A is rank deficient — every neighbour on one line, at a boundary or beside a mask — that component is zeroed, under the rule apply_stencil! states for a mask.

A node set built from positions and areas alone has no adjacency, and gradient_plan refuses it with an ArgumentError. Give the grid one (k or radius on the UnstructuredGrid constructor), or pass the neighbour set as conn.

Evaluating a field at a coordinate

Observational data arrives with a coordinate. interpolate evaluates a field there:

xa = collect(range(0, 2; length = 11)); ya = collect(range(-1, 3; length = 9))
ga = FG.Grids.StructuredGrid(cart, xa, ya)
fa = [2xi - 3yj + 0.5xi * yj + 7 for xi in xa, yj in ya]
O.interpolate(fa, ga, (0.7, 1.1))
5.484999999999999

Multilinear on a rectilinear grid; a weighted least-squares plane on a curvilinear grid or a node set, which is exact for a linear field and reproduces a cell's own value at its centre. A periodic direction interpolates across its seam, so a coordinate past the last sample wraps to the first.

The mask policies mean here what they mean for a stencil: BlankMasked returns masked when a contributor is inactive, ReduceInRun renormalizes over the active ones, and ShiftWithinRun is refused, there being no window to shift.

A vector of coordinates is evaluated in one call, one value per point. Off a rectilinear grid every point's neighbour search runs on one cell list over the grid, built once for the call, and execution spreads the points over threads or processes:

pts = [(0.1 + 0.18t, -0.5 + 0.3t) for t in 0:10]
O.interpolate(fa, ga, pts)
11-element Vector{Float64}:
 8.675
 8.132
 7.642999999999999
 7.208
 6.826999999999999
 6.5
 6.227
 6.008
 5.843
 5.732
 5.674999999999999

A batch of fields on one grid

A field may carry trailing axes beyond the grid's own — many tracers, an ensemble, a time window — sharing one geometry. Those axes are batch: every entry point takes them, differencing only along dim, which indexes the grid's directions.

gb = FG.Grids.StructuredGrid(cart, xa, ya)
fb = cat((fa .+ 100k for k in 1:4)...; dims = 3)      # (11, 9, 4) against a 2-D grid
ob = similar(fb)
O.derivative!(ob, fb, gb, 1; order = 1, nodes = 3)
size(ob)
(11, 9, 4)

Nothing about the grid depends on the batch, so the grid-only work — the stencil table, the metric factors, the interpolation weights, a gradient plan's coefficients — is computed once and reused across it. One pass over the batch is therefore less work than a pass per slice.

It also matters for a device backend. apply_stencil! launches over the whole output, batch included, so a batched call is one launch over prod(spatial) · prod(batch) work items where a slice loop is one launch each over prod(spatial). A 64×64 slice is 4096 work items, well short of saturating a GPU; the batch is the axis with the parallelism to fill it.

Evaluating a batch at a coordinate gives one value per element, through the ! form or its allocating wrapper as elsewhere in the package:

out = Vector{Float64}(undef, 4)
O.interpolate!(out, fb, gb, (0.7, 1.1))
4-element Vector{Float64}:
 105.48499999999999
 205.48499999999999
 305.48499999999996
 405.485

An unbatched field still returns a scalar — the rank decides, so nothing is inferred from a length at run time. A mask stays the grid's own shape and applies to every element; a field whose spatial extent disagrees with the grid is still an error, and so is asking to difference along a batch axis.

Metric factors

G = FG.Geometry
sph = G.SphericalGeometry(2.0)
G.scale_factors(sph, (0.0, π/3)), G.scale_factors(sph, (0.0, π/3, 5.0))
((1.0000000000000002, 2.0), (2.5000000000000004, 5.0, 1.0))

scale_factors gives the physical length of a unit coordinate step in each direction — (R cosφ, R) on a sphere's surface, (r cosφ, r, 1) with a radius direction, and 1 throughout for a Cartesian metric. They turn a coordinate derivative into a physical one, ∂/∂sᵈ = (1/hᵈ)·∂/∂ξᵈ, and derivative! and the staggered operators are built from them.

G.jacobian(sph, (0.0, 0.5))           # 4 cos(0.5)
3.510330247561491

jacobian is their product: the volume element per unit coordinate volume, and the quantity the grid's own cell measure is built from.

An ellipsoidal metric supplies its own curvature radii, and nothing else in the stack changes:

wgs = G.SpheroidGeometry()
G.scale_factors(wgs, (0.0, 0.0)), G.meridional_radius(wgs, π/2)
((6.378137e6, 6.3354393272928195e6), 6.399593625758492e6)