A band integral with a Bayesian-quadrature error bar¶
A band-averaged radiance is , the spectral radiance weighted by the band’s response . radtrax computes it on a fine grid, which is cheap when is cheap. When every is an expensive run, only a few wavelengths can be afforded, and the error from using few nodes goes unreported. Bayesian quadrature (BQ, integrix.expect.bayes_quad) puts a Gaussian-process prior on and returns the integral with a posterior standard deviation. This pilot (radtrax#340) asks whether that standard deviation is honest on one real band before anyone relies on it.
Answer: not for line-resolved radiances on this band. The spectrum here is a smooth continuum under thousands of methane lines narrower than the node spacing. Those lines set the error: with 32 nodes every rule is still about 0.7–0.9 % off, and BQ is no more accurate than the trapezoid rule at the same nodes. Plain BQ’s 95 % interval is far too narrow (it covers the truth 6–60 % of the time). With a nugget fitted to absorb the unresolved lines, the interval is close to honest from 16 nodes upward (inside the binomial band in four of the six cases with 16 or more nodes), but BQ then adds an error bar, not accuracy. On the same atmospheres without the lines, BQ is 18 to 1,600 times more accurate than the trapezoid rule and its interval is conservative. Section 7 gives the recommendation.
To rerun. integrix and kernellib are not radtrax dependencies, and integrix’s pins (gaussx 0.8.5, functax 0.0.15) conflict with radtrax’s lock, so install them without their dependencies into radtrax’s own environment and run the notebook with that environment’s Python (integrix’s Bayesian-quadrature tests pass on radtrax’s pins: gaussx 0.6.12, functax 0.0.6):
uv sync --all-groups
uv pip install --no-deps "integrix @ git+https://github.com/jejjohnson/integrix@v0.0.14" "kernellib @ git+https://github.com/jejjohnson/kernellib@v0.0.23"
uv run --no-sync jupyter nbconvert --to notebook --execute --inplace docs/notebooks/band_integral_bq_pilot.ipynb --ExecutePreprocessor.timeout=3600import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
# radtrax's gaussx, radiomax and other dependencies resolve from the git
# sources in its pyproject, which uv reads and plain pip ignores.
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"], check=True)
uv = ["uv", "pip", "install", "--system", "-q"]
subprocess.run(
[*uv, "radtrax @ git+https://github.com/jejjohnson/radtrax@main"], check=True
)
# integrix and kernellib without their dependencies, as in the rerun steps above
subprocess.run(
[
*uv,
"--no-deps",
"integrix @ git+https://github.com/jejjohnson/integrix@v0.0.14",
"kernellib @ git+https://github.com/jejjohnson/kernellib@v0.0.23",
],
check=True,
)import time
import warnings
warnings.filterwarnings("ignore")
import equinox as eqx
import gaussx_linalg
import jax
import jax.numpy as jnp
import kernellib as kl
import lineax as lx
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from functax.quad import gauss_legendre
from integrix.expect import Empirical, WeightedBox, bayes_quad, kernel_mean
from scipy import stats
jax.config.update("jax_enable_x64", True)
from radiomax.geometry import air_mass_factor
from radiomax.thermal import planck_radiance, to_per_um
from radtrax.geo import landsat_srf
from radtrax.spectroscopy.synthetic import WL_NM, band_mean, methane_cross_section1. The band and its dense reference¶
The band is Landsat 8 OLI’s SWIR2 (B7, about 2050–2350 nm), which overlaps the 2.3 µm methane band. Its response comes from radtrax’s bundled USGS table, projected onto the synthetic spectrum’s 0.01 nm grid. The dense reference is radtrax’s own band integration on that grid, , over about 31,800 wavelengths: that is the line-by-line cost that a handful of nodes would replace.
in_band = (WL_NM >= 2037.0) & (WL_NM <= 2355.0)
wl = WL_NM[in_band]
srf = landsat_srf("L8", bands=("B7",), wavelengths_hr_nm=wl)
weights = np.asarray(srf.matrix[0]) # R_g Δλ, the hat-projected response
support = wl[weights > 1e-4 * weights.max()]
lo, hi = float(support[0]), float(support[-1])
print(f"B7 support: {lo:.1f}–{hi:.1f} nm, {wl.size} grid wavelengths")
def dense_average(radiance):
"""The reference band average on the fine grid."""
return float(band_mean(radiance, weights))B7 support: 2039.4–2349.2 nm, 31800 grid wavelengths
For Bayesian quadrature the band is a measure, , and BQ needs its kernel means and its initial error . Two forms of the measure were tried:
an
integrix.expect.WeightedBoxwhose density interpolates , with kernel means computed by a 128-point Gauss–Legendre rule split at each node;an
integrix.expect.Empiricalmeasure on 0.5 nm bins of the response: 622 atoms at the bins’ response-weighted centres, carrying the bins’ summed weights, so every kernel mean and the initial error are exact finite sums over the same atoms.
The cell below compares both with the dense sum over the fine grid. The weighted box is off by about 10-4 of the kernel means’ scale, because the published response has a kink every nanometre. That error is too large for BQ on a smooth spectrum: the weights amplify it, and because the kernel means and the initial error come from different rules, the small posterior variance cancels to a negative number. In a first run of this notebook with the weighted box, the control below had larger errors than the piecewise-linear rule at 16 and 32 nodes, and a standard deviation of exactly zero (clipped). The binned measure is far closer to the dense sum for every lengthscale above a few nanometres, so the rest of the notebook uses it.
edges = np.arange(lo, hi + 0.5, 0.5)
bin_index = np.digitize(wl, edges)
bin_weight = np.bincount(bin_index, weights)
bin_centre = np.bincount(bin_index, weights * wl)
occupied = bin_weight > 0
band = Empirical(
jnp.asarray((bin_centre[occupied] / bin_weight[occupied])[:, None]),
jnp.asarray(bin_weight[occupied]),
)
density = jnp.asarray(weights / np.gradient(wl))
wl_j = jnp.asarray(wl)
weighted_box = WeightedBox(
lambda x: jnp.interp(x[..., 0], wl_j, density), jnp.array([lo]), jnp.array([hi])
)
print(f"{int(occupied.sum())} atoms")
check_nodes = jnp.asarray(np.linspace(lo, hi, 8)[:, None])
for ell in (5.0, 20.0, 80.0):
kernel = kl.Matern(nu=2.5, lengthscale=ell, variance=1.0)
dense_z = band_mean(np.asarray(kernel(check_nodes, wl_j[:, None])), weights)
rule = gauss_legendre(128)
box_z = np.asarray(kernel_mean(kernel, weighted_box, check_nodes, rule=rule))
binned_z = np.asarray(kernel_mean(kernel, band, check_nodes))
box_error = np.max(np.abs(box_z - dense_z)) / dense_z.max()
binned_error = np.max(np.abs(binned_z - dense_z)) / dense_z.max()
print(
f"ℓ = {ell:4.0f} nm: kernel-mean error {box_error:.1e} (weighted box), "
f"{binned_error:.1e} (binned) of max z"
)622 atoms
ℓ = 5 nm: kernel-mean error 6.3e-05 (weighted box), 2.3e-05 (binned) of max z
ℓ = 20 nm: kernel-mean error 6.0e-05 (weighted box), 4.7e-06 (binned) of max z
ℓ = 80 nm: kernel-mean error 7.8e-05 (weighted box), 9.3e-07 (binned) of max z
2. Atmospheres¶
Each atmosphere is a top-of-atmosphere radiance on the fine grid,
with a smooth solar shape (a 5778 K Planck curve per wavelength from radiomax.thermal, in relative units), a linear surface albedo with a random slope of up to ±30 % across the band, the two-way air-mass factor of a nadir view (radiomax.geometry.air_mass_factor) for a solar zenith angle uniform on 0–60°, a methane column uniform between 1 and 10 times a background of 0.0105 kg/m² (about 1.9 ppm), and a methane cross-section drawn by radtrax.spectroscopy.synthetic.methane_cross_section (3,000 Lorentz lines of 0.1 nm half-width in the 2.3 µm band, new line positions for every atmosphere). The spectrum holds methane only: water vapour and CO₂, which absorb more strongly in B7, are left out, so the lines here are fewer and weaker than in a real B7 spectrum. The control repeats every atmosphere with , a smooth integrand.
N_ATMOSPHERES = 100
OMEGA_BACKGROUND = 0.0105 # kg/m²
f11 = ((WL_NM >= 1569) & (WL_NM <= 1658)).astype(float)
f12 = ((WL_NM >= 2113) & (WL_NM <= 2286)).astype(float)
nu_cm = 1e7 / wl
solar = np.asarray(to_per_um(planck_radiance(nu_cm, 5778.0), nu_cm))
solar = solar / solar.mean()
def atmosphere(rng):
"""One radiance spectrum with methane lines, and the same without them."""
sigma = methane_cross_section(rng, f11, f12)[in_band]
omega = OMEGA_BACKGROUND * rng.uniform(1.0, 10.0)
air_mass = air_mass_factor(rng.uniform(0.0, 60.0), 0.0) # nadir view
slope = rng.uniform(-0.3, 0.3)
albedo = 0.3 * (1.0 + slope * (wl - wl.mean()) / (hi - lo))
continuum = solar * albedo
return continuum * np.exp(-air_mass * sigma * omega), continuum
rng = np.random.default_rng(0)
spectra = [atmosphere(rng) for _ in range(N_ATMOSPHERES)]
radiance, continuum = spectra[0]
fig, ax = plt.subplots(figsize=(9, 3))
ax.plot(wl, radiance, lw=0.4, label="with methane lines")
ax.plot(wl, continuum, lw=1.0, label="continuum (control)")
ax.plot(
wl, weights / weights.max() * radiance.max(), "k--", lw=0.8, label="B7 response"
)
ax.set(xlabel="wavelength [nm]", ylabel="radiance [relative]", xlim=(lo, hi))
ax.legend(loc="lower left")
plt.show()
3. Three rules at the same nodes¶
Every rule sees the same radiances , at nodes placed either evenly over the band’s support (both ends included) or one at random in each of equal cells (stratified).
Piecewise-linear (trapezoid). Interpolate linearly between the nodes (constant beyond the end nodes) and integrate that against on the fine grid; this is the trapezoid rule weighted by the response, the rule radtrax’s hat projection applies.
BQ. A Matérn-5/2 prior from kernellib on , with the nodes’ mean as a constant prior mean; the lengthscale (a grid of 40 values from 1 to 400 nm) and the amplitude (in closed form) are fitted by marginal likelihood.
bayes_quadreturns and .BQ with a nugget. The same, with a white-noise variance on the diagonal, fitted jointly (0 or 16 values from 10-4 to 10). The nugget treats the unresolved lines as noise, which widens the interval; it enters through
bayes_quad’sjitter, which addsjittertimes the mean prior variance to the diagonal.
LENGTHSCALES = np.geomspace(1.0, 400.0, 40)
NUGGETS = np.concatenate([[1e-10], np.geomspace(1e-4, 10.0, 16)])
@eqx.filter_jit
def profile(gram, etas, centred):
"""Amplitude σ̂² = yᵀ C⁻¹ y / n and the profiled −log likelihood, per nugget."""
n = centred.size
def one(eta):
covariance = lx.MatrixLinearOperator(
gram + eta * jnp.eye(n), lx.positive_semidefinite_tag
)
amplitude = gaussx_linalg.quadratic_form(covariance, centred) / n
nll = 0.5 * n * jnp.log(amplitude) + 0.5 * gaussx_linalg.logdet(covariance)
return nll, amplitude
return jax.vmap(one)(etas)
def fit(nodes, centred, nugget):
"""Lengthscale, amplitude and nugget by marginal likelihood on a grid."""
best = None
points = jnp.asarray(nodes[:, None])
etas = jnp.asarray(NUGGETS if nugget else NUGGETS[:1])
for ell in LENGTHSCALES:
gram = kl.Matern(nu=2.5, lengthscale=ell, variance=1.0)(points, points)
nll, amplitude = map(np.asarray, profile(gram, etas, jnp.asarray(centred)))
k = int(np.argmin(nll))
if best is None or nll[k] < best[0]:
best = (nll[k], ell, float(amplitude[k]), float(etas[k]))
return best[1:]
@eqx.filter_jit
def quadrature(ell, amplitude, eta, nodes, centred):
kernel = kl.Matern(nu=2.5, lengthscale=ell, variance=amplitude)
return bayes_quad(kernel, band, nodes[:, None], centred, jitter=eta)
def place(n_nodes, placement, rng):
if placement == "even":
return np.linspace(lo, hi, n_nodes)
edges = np.linspace(lo, hi, n_nodes + 1)
return rng.uniform(edges[:-1], edges[1:])
def estimates(nodes, radiance):
"""Each rule's estimate and, for BQ, its standard deviation."""
values = np.interp(nodes, wl, radiance)
linear = float(band_mean(np.interp(wl, nodes, values), weights))
out = {"linear": (linear, np.nan)}
offset = values.mean()
for name, nugget in (("bq", False), ("bq_nugget", True)):
ell, amplitude, eta = fit(nodes, values - offset, nugget)
args = map(jnp.asarray, (ell, amplitude, eta, nodes, values - offset))
result = quadrature(*args)
out[name] = (float(result.value) + offset, float(result.standard_error))
return out4. The sweep¶
For from 4 to 32, both placements and all 100 atmospheres, record each rule’s relative error and, for BQ, the standard deviation and whether the 95 % interval covers . The stratified nodes are redrawn for every atmosphere, so their coverage is also over node placements. The control runs the even placement on the continua.
NODE_COUNTS = (4, 8, 12, 16, 24, 32)
cases = [("lines", p) for p in ("even", "stratified")] + [("control", "even")]
records = []
start = time.time()
node_rng = np.random.default_rng(1)
for spectrum, placement in cases:
for n_nodes in NODE_COUNTS:
for radiance, continuum in spectra:
truth_spectrum = radiance if spectrum == "lines" else continuum
truth = dense_average(truth_spectrum)
nodes = place(n_nodes, placement, node_rng)
for rule, (value, sd) in estimates(nodes, truth_spectrum).items():
records.append(
{
"spectrum": spectrum,
"placement": placement,
"N": n_nodes,
"rule": rule,
"error": (value - truth) / truth,
"sd": sd / truth,
}
)
print(f"{len(records)} estimates in {time.time() - start:.0f} s")
results = pd.DataFrame(records)5400 estimates in 545 s
5. Error against ¶
Root-mean-square relative error over the 100 atmospheres, for each rule at the same nodes.
rms = (
results.assign(squared=results["error"] ** 2)
.groupby(["spectrum", "placement", "N", "rule"])["squared"]
.mean()
.pow(0.5)
.unstack("rule")[["linear", "bq", "bq_nugget"]]
)
rms.style.format("{:.1e}")fig, axes = plt.subplots(1, 3, figsize=(12, 3.4), sharey=True)
for ax, (spectrum, placement) in zip(axes, cases, strict=True):
table = rms.loc[(spectrum, placement)]
for rule, marker in (("linear", "s"), ("bq", "o"), ("bq_nugget", "^")):
ax.loglog(table.index, table[rule], marker=marker, label=rule)
ax.set(title=f"{spectrum}, {placement} nodes", xlabel="N nodes")
axes[0].set_ylabel("RMS relative error")
axes[0].legend()
plt.show()
6. Is the error bar honest?¶
For each BQ variant: the mean of , the RMS of the actual error, and the coverage of the 95 % interval over the 100 atmospheres. With 100 trials, a calibrated interval’s observed coverage falls in the binomial band printed below 95 % of the time (the 2.5 % and 97.5 % quantiles of Binomial(100, 0.95), divided by 100). The Clopper–Pearson column is the 95 % interval of the observed coverage itself. The verdict is too narrow below the band, too wide above it and calibrated inside it.
band_lo, band_hi = stats.binom.interval(0.95, N_ATMOSPHERES, 0.95)
print(f"binomial band for a calibrated 95 % interval: {band_lo:.0f}–{band_hi:.0f} %")
bq = results[results["rule"] != "linear"].assign(
covered=lambda d: np.abs(d["error"]) <= 1.96 * d["sd"]
)
rows = []
for key, group in bq.groupby(["spectrum", "placement", "rule", "N"]):
hits = int(group["covered"].sum())
interval = stats.binomtest(hits, len(group)).proportion_ci(confidence_level=0.95)
rows.append(
{
**dict(zip(("spectrum", "placement", "rule", "N"), key, strict=True)),
"mean sd": group["sd"].mean(),
"RMS error": np.sqrt((group["error"] ** 2).mean()),
"coverage": hits / len(group),
"Clopper–Pearson": f"{interval.low:.2f}–{interval.high:.2f}",
"verdict": "too narrow"
if hits < band_lo
else "too wide"
if hits > band_hi
else "calibrated",
}
)
calibration = pd.DataFrame(rows).set_index(["spectrum", "placement", "rule", "N"])
calibration.style.format(
{"mean sd": "{:.1e}", "RMS error": "{:.1e}", "coverage": "{:.2f}"}
)binomial band for a calibrated 95 % interval: 90–99 %
7. Recommendation¶
Do not adopt BQ for B7 band integrals of line-resolved radiance. Four results from the tables above support this.
No accuracy gain. With methane lines in the spectrum, BQ’s error stays within about 25 % of the piecewise-linear rule’s at every , in either direction: 2.3–2.6 % at 4 nodes and 0.7–0.9 % at 32. The lines are narrower than any affordable node spacing, so the integrand is rough at the scale of the nodes, and no rule using these nodes resolves it.
A plain Matérn prior gives a misleading bar. Fitted by marginal likelihood, the prior reads the line structure as smooth variation, and its 95 % interval covers the truth only 6–18 % of the time on even nodes and 35–60 % on stratified ones.
A nugget makes the bar nearly honest, but only with enough nodes. Treating unresolved lines as white noise brings coverage into the binomial band at 16 and 32 even nodes and at 24 and 32 stratified ones, and leaves it just below the band (0.87–0.88) at 24 even and 16 stratified nodes. With 12 or fewer nodes it stays clearly too narrow. An error bar is then the whole benefit, and a sample standard error at the same nodes would be a cheaper way to get one; that alternative was not tested here.
The method is sound where its prior fits. On the smooth continuum, BQ is 18–1,600 times more accurate than the trapezoid rule, and its interval is conservative (coverage 100 %, with 6–90 times the actual error). That makes it worth revisiting for band integrals of quantities that are smooth at the node scale. This pilot measured that only on the control.
Two implementation findings carry over to any adoption. First, a tabulated response needs exact kernel means: the numerical WeightedBox kernel means were too inaccurate for a smooth integrand (section 1), and the binned Empirical measure fixed that. Second, the spectrum here holds methane only; water vapour and CO₂ lines in a real B7 spectrum would make it rougher still, which would not change the conclusion.