Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Rules

A global mean on a latitude–longitude grid

Every climate report has a global mean surface temperature in it, and it is easy to get it wrong by a few kelvin. The field comes on a regular latitude–longitude grid, and a plain average of the grid values counts a cell next to the pole as much as a cell on the equator, even though the polar cell is a tiny sliver of the sphere. The fix is the area element of (1.4): each value is weighted by the area of its cell, which falls like cos⁡ϕ\cos \phi toward the poles. So the global mean is a rule, with weights that come from the geometry of the grid, and it is the first operation integrix offers.

In this chapter we look at rules over one axis and several, at the two ways a grid on the sphere can be weighted (global and local), at weighted means, and at one detail that matters for long sums in single precision.

Rules over several axes

A rule over one axis is (2.2). A field on a grid has several axes, and when the domain is a product Ω=Ω1×Ω2\Omega = \Omega_1 \times \Omega_2 and the measure is a product too, dμ=dμ1dμ2\mathrm{d}\mu = \mathrm{d}\mu_1 \mathrm{d}\mu_2, a rule on each axis gives a rule on the grid,

I^[f]=∑i=1N1∑j=1N2wi(1)wj(2)f(si(1),sj(2))\hat{I}[f] = \sum_{i=1}^{N_1} \sum_{j=1}^{N_2} w^{(1)}_i w^{(2)}_j f(s^{(1)}_i, s^{(2)}_j)

where wi(1)w^{(1)}_i and wj(2)w^{(2)}_j are the weights of the two rules, with N1N_1 and N2N_2 nodes. This is a tensor-product rule, and its weights are the outer product of the two weight vectors. The sphere in latitude and longitude is such a product: the measure cos⁡ϕdϕdϑ\cos \phi \mathrm{d}\phi \mathrm{d}\vartheta splits into a latitude factor cos⁡ϕdϕ\cos \phi \mathrm{d}\phi and a longitude factor dϑ\mathrm{d}\vartheta.

There are a few ways to weight each factor, and they put the sphere on either side of chapter 3.

We check all three on a toy temperature field with a pole-to-equator gradient and a wave in longitude, T(ϕ,ϑ)=288−30sin⁡2ϕ+5cos⁡ϕcos⁡ϑT(\phi, \vartheta) = 288 - 30 \sin^2 \phi + 5 \cos \phi \cos \vartheta (in K). The wave averages to zero around every latitude circle, and sin⁡2ϕ\sin^2 \phi averages to 1/31/3 over the sphere, so the exact global mean is Tˉ=278\bar{T} = 278 K. integrix takes a tuple of rules as a tensor rule, one per axis. The Gauss–Legendre rule comes from functax.quad, and the longitude and band-area rules are built by hand as a functax.quad.Rule, which is just nodes and weights.

import jax

jax.config.update("jax_enable_x64", True)

import einx
import jax.numpy as jnp
import numpy as np
from functax import quad
from integrix import rule
from jaxtyping import Array, Float

# Shapes: N_φ latitudes; N_ϑ = 2 N_φ longitudes


# user
def temperature(
    latitude: Float[Array, "lat"], longitude: Float[Array, "lon"]
) -> Float[Array, "lat lon"]:
    """T(φ, ϑ) = 288 − 30 sin²φ + 5 cos φ cos ϑ, in K."""
    # s = sin φ
    sine = jnp.sin(latitude)                                    # (N_φ,) → (N_φ,)
    # T_z(φ) = 288 − 30 s²
    zonal = 288.0 - 30.0 * sine**2                              # → (N_φ,)
    # c_φ = cos φ
    cos_lat = jnp.cos(latitude)                                 # → (N_φ,)
    # c_ϑ = cos ϑ
    cos_lon = jnp.cos(longitude)                                # (N_ϑ,) → (N_ϑ,)
    # wave(φ, ϑ) = cos φ cos ϑ
    wave = einx.multiply("lat, lon -> lat lon", cos_lat, cos_lon)  # → (N_φ, N_ϑ)
    # a = 5 wave
    amplitude = 5.0 * wave                                      # → (N_φ, N_ϑ)
    # T = T_z + a
    field = einx.add("lat, lat lon -> lat lon", zonal, amplitude)  # → (N_φ, N_ϑ)
    return field


labels = ("unweighted", "cell areas", "Gauss")
print("N_φ  " + "  ".join(f"{label:>11}" for label in labels))
for n_lat in (4, 8, 16, 32):
    # N_ϑ = 2 N_φ
    n_lon = 2 * n_lat
    # 2π, one full turn
    full_turn = 2.0 * jnp.pi
    # k = 0, …, N_ϑ − 1
    ordinal = jnp.arange(n_lon)                                 # → (N_ϑ,)
    # ϑₖ = 2π k / N_ϑ
    longitude = full_turn * ordinal / n_lon                     # → (N_ϑ,)
    # wₖ = 2π / N_ϑ
    width = full_turn / n_lon
    # wₖ for every longitude
    longitude_weights = jnp.full(n_lon, width)                  # → (N_ϑ,)
    # today (functax)
    # the periodic trapezoid rule in longitude, as data
    longitude_rule = quad.Rule(longitude, longitude_weights)
    # local: π/2, half of the latitude range
    half_pi = jnp.pi / 2
    # φⱼ₊½ = −π/2 + j π/N_φ, the band edges
    edges = jnp.linspace(-half_pi, half_pi, n_lat + 1)          # → (N_φ + 1,)
    # φⱼ₊½ for j = 1, …, N_φ
    upper_edges = edges[1:]                                     # → (N_φ,)
    # φⱼ₋½ for j = 1, …, N_φ
    lower_edges = edges[:-1]                                    # → (N_φ,)
    # φⱼ = (φⱼ₊½ + φⱼ₋½)/2
    centres = 0.5 * (upper_edges + lower_edges)                 # → (N_φ,)
    # sⱼ₊½ = sin φⱼ₊½
    sine_edges = jnp.sin(edges)                                 # → (N_φ + 1,)
    # wⱼ = sin φⱼ₊½ − sin φⱼ₋½
    band_areas = jnp.diff(sine_edges)                           # → (N_φ,)
    # today (functax)
    # the exact band areas at the band centres, as a rule
    cell_rule = quad.Rule(centres, band_areas)
    # today (functax)
    # global: Gauss–Legendre in μ = sin φ, Pₙ(μⱼ) = 0
    mu_nodes, mu_weights = quad.gauss_legendre(n_lat)          # → (N_φ,) ×2
    # φⱼ = arcsin μⱼ
    gauss_latitude = jnp.arcsin(mu_nodes)                       # → (N_φ,)
    # today (functax)
    # the Gauss weights at the latitudes φⱼ
    gauss_rule = quad.Rule(gauss_latitude, jnp.asarray(mu_weights))
    # a plain average of the grid values, for comparison
    grid = temperature(centres, longitude)                      # → (N_φ, N_ϑ)
    # T̄_plain = mean over the grid
    unweighted = jnp.mean(grid)                                 # → ()
    # e = T̄ − 278
    errors = [float(unweighted) - 278.0]
    for latitude_rule in (cell_rule, gauss_rule):
        field = temperature(latitude_rule.nodes, longitude)     # → (N_φ, N_ϑ)
        # today (integrix)
        # T̄ = (1/4π) ∑ⱼ ∑ₖ wⱼ wₖ T(φⱼ, ϑₖ)
        total = rule.integrate(                                 # → ()
            (latitude_rule, longitude_rule), field, axis=(0, 1)
        )
        errors.append(float(total.value) / (4.0 * np.pi) - 278.0)
    print(f"{n_lat:3d}  " + "  ".join(f"{error:+11.2e}" for error in errors))
N_φ   unweighted   cell areas        Gauss
  4    -5.00e+00    -6.07e-01    +0.00e+00
  8    -5.00e+00    -1.34e-01    +0.00e+00
 16    -5.00e+00    -3.24e-02    +0.00e+00
 32    -5.00e+00    -8.05e-03    -5.68e-14

The plain average is 5 K too cold at every resolution, because it counts the cold polar bands as much as the tropics, and refining the grid does nothing for it. The cell-area rule converges like h2h^2, losing about a factor of four per doubling, as a local rule should. The Gauss rule is exact from the start, up to round-off. That is not luck: the field is a polynomial of degree 2 in μ\mu times a wave in longitude, and a Gaussian grid with NϕN_\phi latitudes integrates every such product up to degree 2Nϕ−12 N_\phi - 1 exactly, which is why spectral models compute their transforms on it.

Batching

The axes that a rule does not integrate are batch axes, and integrix keeps them. A field with a time axis, T(t,ϕ,ϑ)T(t, \phi, \vartheta), integrated over axis=(1, 2) returns one global mean per time step, and an ensemble axis gives one per member. In the same way, the tensor rule above never builds the outer product of the weights explicitly in user code: integrix forms wi(1)wj(2)w^{(1)}_i w^{(2)}_j once and contracts it with the samples over the integrated axes.

Weighted means

The band radiance of (1.2) is the other common rule in Earth observation. A multispectral sensor has a handful of bands, each with its own response Rb(λ)R_b(\lambda), and each band radiance is the mean of the spectrum under that response,

fˉ=∑n=1NwnRnfn∑n=1NwnRn\bar{f} = \frac{\sum_{n=1}^{N} w_n R_n f_n}{\sum_{n=1}^{N} w_n R_n}

where wnw_n are the quadrature weights in wavelength, Rn=Rb(λn)R_n = R_b(\lambda_n) the response and fn=L(λn)f_n = L(\lambda_n) the spectrum. The point of weighted_mean is that both sums use the same wnw_n and the same summation, so a rule that is a little off in the numerator is off in the same way in the denominator, and the two errors cancel for a flat spectrum. A response stacked per band, with the shape of the values, gives every band in one call.

# Shapes: N_λ = 601 wavelengths; N_b = 3 bands
# λₙ = 2200 + 200 (n − 1)/600, in nm
wavelength = jnp.linspace(2200.0, 2400.0, 601)                  # → (N_λ,)
# δ = λ − 2300
line_offset = wavelength - 2300.0                               # → (N_λ,)
# g = exp(−δ²/2)
dip = jnp.exp(-0.5 * line_offset**2)                            # → (N_λ,)
# L(λ) = 1 − 0.4 g: one line at 2300 nm
spectrum = 1.0 - 0.4 * dip                                      # → (N_λ,)
# the band centres λ_b, in nm
band_centres = jnp.array([2250.0, 2300.0, 2350.0])              # → (N_b,)
# δ_b(λ) = λ_b − λ
offset = einx.subtract("band, wl -> band wl", band_centres, wavelength)  # → (N_b, N_λ)
# z = δ_b/10
scaled = offset / 10.0                                          # → (N_b, N_λ)
# R_b(λ) = exp(−z²/2) = exp(−(λ − λ_b)²/(2 · 10²))
response = jnp.exp(-0.5 * scaled**2)                            # → (N_b, N_λ)
# L_b(λ) = L(λ) for every band
spectra = einx.id("wl -> band wl", spectrum, band=3)            # → (N_b, N_λ)
# Δλ = λ₂ − λ₁
spacing = wavelength[1] - wavelength[0]                         # → ()
# Δλ/2
half_spacing = spacing / 2                                      # → ()
# the two end nodes
ends = jnp.array([0, -1])
# wₙ = Δλ, with Δλ/2 at the ends
weights = jnp.full(601, spacing).at[ends].set(half_spacing)     # → (N_λ,)
# today (integrix)
# L_b = ∑ₙ wₙ R_b(λₙ) L(λₙ) / ∑ₙ wₙ R_b(λₙ)
bands = rule.weighted_mean(weights, spectra, weight=response)   # → (N_b,)
print("L_b =", [round(float(band), 4) for band in bands])
L_b = [1.0, 0.9602, 1.0]

Only the middle band sees the line, and it loses about 4 % of its light, half as much as the 5 nm channel of chapter 1, since this band is twice as wide.

Summing in single precision

The last detail of a rule is the sum itself. A left-to-right sum keeps a running total and adds each term to it, so the total is rounded NN times, and once the total is large the small terms lose most of their bits. The rounding error of such a sum can grow like O(εN)O(\varepsilon N), where ε\varepsilon is the unit round-off (ε≈6×10−8\varepsilon \approx 6 \times 10^{-8} in float32). A pairwise sum adds neighbours, then pairs of pairs, so each term is rounded only O(log⁡2N)O(\log_2 N) times and the error bound is O(εlog⁡2N)O(\varepsilon \log_2 N) (Higham, 2002). In float64 the difference rarely matters, but a float32 sum over a long time series, a fine spectral grid or a large image can be visibly wrong. integrix always sums pairwise.

We add 220 copies of 0.1 in float32, once with a left-to-right jax.lax.scan and once with integrate and unit weights. The exact answer, in float32’s nearest value of 0.1, is printed last.

# Shapes: N = 2²⁰ terms
# vₙ = float32(0.1)
values = jnp.full(2**20, 0.1, dtype=jnp.float32)                # → (N,)


# user
def add(
    total: Float[Array, ""], value: Float[Array, ""]
) -> tuple[Float[Array, ""], None]:
    """One step of a left-to-right sum."""
    # Sₙ = Sₙ₋₁ + vₙ
    running = total + value                                     # → ()
    return running, None


# S = ((v₁ + v₂) + v₃) + …
left_to_right, _ = jax.lax.scan(add, jnp.float32(0.0), values)  # → ()
# wₙ = 1
unit_weights = jnp.ones(2**20, dtype=jnp.float32)               # → (N,)
# today (integrix)
# S = ∑ₙ wₙ vₙ, summed pairwise
pairwise = rule.integrate(unit_weights, values).value           # → ()
# S = N v₀
exact = 2**20 * float(np.float32(0.1))
print(f"left to right: {float(left_to_right):.1f}")
print(f"pairwise:      {float(pairwise):.1f}")
print(f"exact:         {exact:.1f}")
left to right: 105891.8
pairwise:      104857.6
exact:         104857.6

The left-to-right sum is about 1 % too large, and the pairwise sum is exact to the last digit printed. Chapter 11 comes back to precision with a budget that has to close.