How is the code packaged, and what does its data know?
GeoStack · background · code organisation · the two axes
Abstract¶
How code in the stack is packaged (function, Module, Operator) and what data it sees (array, named array, carrier) are two separate axes. This page holds the problem they solve, the objects in symbols, each axis with a worked example on one methane plume in an EMIT scene, one vocabulary per axis, and the rules that follow from them. The role each name plays in its library’s API, from structures up to recipes, is on the role ladder, and the trace-gas example climbs that ladder on the same plume.
The running example¶
The problem: why geo code is hard to write well¶
Take one running example: a methane plume in an EMIT hyperspectral scene over an oil and gas field. A matched filter turns the radiance into a methane enhancement, the plume is masked, and its emission rate comes from the mass of methane in the plume and the wind. Every step of it can go wrong in a way that raises no error.
Table 2:Seven ways the running example goes wrong without an error, and what fixes each.
| Problem | What goes wrong, silently | What fixes it |
|---|---|---|
| Axes by position | EMIT’s radiance file stores (downtrack, crosstrack, band), which is (y, x, band); geoarray and most operators expect (band, y, x). mean(axis=0), meant as the scene’s mean spectrum, averages down the rows instead and returns an array of a plausible size. | named array: dims by name, mean(("y", "x")) |
| Lost georeference | The radiance comes in sensor geometry, with its geolocation in a separate lookup table. Orthorectify it by hand, or crop the bare array, np.asarray(scene)[..., 100:164, 100:164], and the transform no longer matches the pixels: the crop claims to start at the scene’s corner, and the plume is attributed to a facility kilometres away. | carrier: slicing and cropping move the transform with the data |
| Mismatched grids | The wind for the emission rate comes from ERA5 on a 0.25° grid, the enhancement on a 60 m UTM grid. Index the wind array with the plume’s pixel indices and you read the wind somewhere else on Earth, with no error as long as the indices fit. | carrier: require_grid_match refuses; values on another grid are read at coordinates (interp_at) |
| Nodata | A radiance fill of -9999 enters the background mean and covariance as if it were data, and biases the filter over the whole scene, not only where it sits. | carrier: fill_value and valid_mask |
| Maths locked in a container | The matched filter written against xarray can’t run on a GeoArray, and neither can be jitted: a CRS is not something JAX can trace. Each container gets its own copy of the algorithm. | function and Module on plain arrays; the container is unwrapped outside them |
| Setup that can’t be traced | The background statistics (a mean, a shrunk covariance from scikit-learn, a solve with it) are refitted on every call, or forced under jit where they fail. | Module: fit once at fit, call jittably after |
| Pipelines held together by scripts | The chain from radiance to emission rate lives in one notebook; its settings (spectral window, threshold, wind source) can’t be saved, swept or rerun exactly. | Operator: config round-trip, |, Graph |
The fixes split cleanly. The first four problems are about the data; the last three are about how the code is packaged. That is why the stack has two axes.
The objects, in symbols¶
The whole stack rests on two ideas: a function of arrays, , and an Operator that lifts that function onto geographic data, . Everything else is bookkeeping about what the data knows and where the settings live. The symbols, each defined in full with its shape in the sections below:
: the data as a plain array of numbers; : the array the function returns.
: what the function needs to know about where the data sits, as plain arrays or numbers: pixel areas, a transform, the air-mass factor of the sun and view angles, the methane absorption at each band’s wavelength. It is read off the data, never fitted.
: the function’s parameters, set when the Operator is built and constant over a call (a matched filter’s background statistics when they are given, the wind speed of an emission estimate).
: the function itself, which sees only , and .
: the same data as a carrier, the array together with its axis names, coordinates and georeference.
: the Operator’s config, names and settings only (which bands, which spectral window, the units, the fill policy), so it round-trips through JSON.
: the Operator built from and ; called on a carrier with config , it unwraps, calls , and rewraps. Written when is empty.
Two axes follow from those ideas: what the data knows ( or ), and how the code is packaged (, a Module, or ).
The data axis: what knows¶
▦ Plain array¶
A block of numbers with a shape and nothing else:
where:
: the number of axes; indexes them.
: the length of axis .
Example. The scene is , so . Which axis is the band is a convention the code has to remember. EMIT’s radiance file stores (y, x, band) and geoarray (band, y, x); a mean over axis 0 meant as the mean spectrum averages down the rows instead, and runs without an error.
In code, a NumPy or JAX array. Its axis order lives in a jaxtyping annotation and in each einx pattern, so the convention is written down at every call, but nothing checks it against the data: a scene read as (y, x, band) passes the same call and averages over the wrong axes.
import einx
import jax.numpy as jnp
import numpy as np
from jaxtyping import Array, Float
# Shapes: B = N_band = 285 bands; R × C = N_row × N_col = 256 × 256 pixels
def mean_spectrum(radiance: Float[Array, "band y x"]) -> Float[Array, " band"]:
"""Mean radiance spectrum of a scene, averaged over its pixels.
x̄_c = (1 / R C) ∑_ij x_cij
Algorithm:
1. Average over the axes the pattern names y and x.
Args:
radiance: x, the scene, with the band axis first.
Returns:
x̄, one value per band. Nothing checks that the band axis really is
first: a (y, x, band) array gives a wrong answer and no error.
"""
# x̄_c = (1 / R C) ∑_ij x_cij; the axis names live in this pattern only
spectrum = einx.mean("band [y x]", radiance) # (B, R, C) → (B,)
return spectrum
# x ∈ ℝ^(B × R × C): a crop of an EMIT scene, on the host
radiance = np.zeros((285, 256, 256), dtype=np.float32) # → (B, R, C)
# the same numbers on the device
scene = jnp.asarray(radiance) # (B, R, C) → (B, R, C)
# user
# x̄
spectrum = mean_spectrum(scene) # (B, R, C) → (B,)Program 1:The mean spectrum of a plain array: the axis names live only in the einx pattern, and nothing checks them against the data.
▤ Named array¶
The same numbers with a name and a coordinate vector for each axis:
where:
: one name per axis, all distinct.
: the coordinates along axis (wavelengths, positions, dates).
An operation addresses an axis by name, and the array finds its position. Take a reduction (a mean, a sum, a maximum) over axis of a plain array: it maps to the same space with the factor left out. On a named array the same reduction is asked for by a name . The array looks up its position, , reduces there, and removes that axis’s name and coordinates, since the output no longer has that axis:
where:
: the position of the name in ; an error if is not there.
, : the names and coordinates with entry taken out.
Example. , with the band wavelengths. The mean spectrum reduces by name twice, over at and then over , and returns names with the wavelengths still attached, whatever order the reader used.
In code, pipekit-array’s DimArray: the data, one name per axis, and static labels on the dims that have them (here the wavelengths), with no other coordinates. It is a JAX pytree whose only leaf is the data, so new values never recompile. An xarray DataArray is the same object with full coordinates, and pipekit’s dim functions (reduce, sel, isel, transpose) run on both through their adapters.
import einx
import numpy as np
import pipekit_array as pa
# Shapes: B = N_band = 285 bands; R × C = N_row × N_col = 256 × 256 pixels
radiance = np.zeros((285, 256, 256), dtype=np.float32) # → (B, R, C)
# c_1: the centre wavelength of each band, nm
wavelengths = np.linspace(381.0, 2493.0, 285) # → (B,)
rounded = np.round(wavelengths, 1) # (B,) → (B,)
WAVELENGTHS_NM = tuple(rounded.tolist()) # (B,) → B labels
# today (pipekit-array)
# x_named = (x, d, 𝒞): one name per axis, the band dim labelled by wavelength
scene = pa.DimArray(radiance, ("band", "y", "x"), {"band": WAVELENGTHS_NM})
# today (pipekit-array)
# r_y, then r_x: the mean spectrum, found by name
spectrum = pa.reduce(scene, "mean", ("y", "x")) # (B, R, C) → (B,)
# the file's own order, (y, x, band)
as_stored = einx.id("band y x -> y x band", radiance) # (B, R, C) → (R, C, B)
# today (pipekit-array)
# the same numbers, named in that order
stored = pa.DimArray(as_stored, ("y", "x", "band"), {"band": WAVELENGTHS_NM})
# today (pipekit-array)
# r_y, then r_x: the same call gives the same answer
same_spectrum = pa.reduce(stored, "mean", ("y", "x")) # (R, C, B) → (B,)Program 2:The mean spectrum of a named array: the same call gives the same answer whichever order the file stored the axes in.
◆ Carrier¶
A named array plus its georeference :
where:
: the coordinate reference system (an EPSG code or WKT).
: the affine transform from pixel to map coordinates.
: the fill value, NaN allowed.
: the attributes (units, sensor, the sun and view zenith angles, processing level). Band names and wavelengths are coordinates of the band axis, in .
The transform says where each pixel is. The top-left corner of the pixel in row and column sits at map coordinates , and its centre at in pixel units:
where is in map units (m on a projected grid).
The fill value says which pixels are missing. A pixel is valid when every band there is finite and differs from the fill, which gives the valid mask , with indexing bands:
where is the value of band at pixel and is one when its condition holds and zero otherwise.
For a swath or a curvilinear grid, as EMIT’s radiance is before orthorectification, is replaced by per-pixel coordinates ; the rest is the same.
Example. The scene is a carrier on a 60 m grid in UTM zone 13N with , the band names and centre wavelengths in , and the sun and view zenith angles in . The well pad at map coordinates is found at pixel by solving for , which is to_pixel. Slice the bare array instead, np.asarray(scene)[..., 100:164, 100:164], and still describes the full scene: the window claims to start at the scene’s corner, and the plume is attributed to a facility several kilometres away.
In code, geotoolz-array’s GeoArray: the data (NumPy or JAX), its dims ending in ("y", "x"), coordinates for the other dims (SpectralAxis, TimeAxis), the transform, CRS, fill value and frozen attrs. Slicing, crop and read_window move the transform with the pixels; a reduction over y and x leaves no grid, so it returns a named array. GeoSwath carries per-pixel latitude and longitude instead of a transform, and GeoPoints a set of points; xrops plays the same role for a DataArray whose coordinates and CRS mean geography. The carrier-arrays page gives each of these carriers in full.
import numpy as np
import pipekit_array as pa
from geoarray import GeoArray, crop, to_pixel
from geoarray.coords import SpectralAxis
# Shapes: B = N_band = 285 bands; R × C = N_row × N_col = 256 × 256 pixels
radiance = np.zeros((285, 256, 256), dtype=np.float32) # → (B, R, C)
# the centre wavelength of each band, nm, and a name for each
wavelengths = np.linspace(381.0, 2493.0, 285) # → (B,)
rounded = np.round(wavelengths, 1) # (B,) → (B,)
WAVELENGTHS_NM = tuple(rounded.tolist()) # (B,) → B labels
BAND_NAMES = tuple(f"{wavelength:.1f}nm" for wavelength in WAVELENGTHS_NM)
# today (geoarray)
# 𝒞: the band names with their centre wavelengths
bands = SpectralAxis(names=BAND_NAMES, wavelength_nm=WAVELENGTHS_NM)
# today (geoarray)
# x_geo = (x_named, Γ), Γ = (crs, A, x_fill, 𝓜): 60 m in UTM zone 13N
scene: GeoArray["band y x"] = GeoArray( # (B, R, C) → (B, R, C)
radiance,
(60.0, 0.0, 630000.0, 0.0, -60.0, 3550000.0),
"EPSG:32613",
fill_value=-9999.0,
dims="band y x",
coords=(bands,),
attrs={"solar_zenith_deg": 28.4, "view_zenith_deg": 6.1},
)
# today (geoarray)
# m_ij = ∏_c 1[x_cij ≠ x_fill] 1[x_cij is finite]
valid = scene.valid_mask() # (B, R, C) → (R, C)
# s: the well pad in map coordinates, m
well_pad_xy = np.array([[637530.0, 3542210.0]]) # → (1, 2)
# today (geoarray)
# s = A (j + ½, i + ½, 1)ᵀ, solved for the fractional (i, j)
well_pad_pixel = to_pixel(scene.transform, well_pad_xy) # (1, 2) → (1, 2)
# today (geoarray)
# a 64 × 64 window from row 100, column 100; A moves with the pixels
window = crop(scene, (100, 100), (64, 64)) # (B, R, C) → (B, 64, 64)
# today (pipekit-array)
# r_y, then r_x: no grid is left, so a named array comes back
spectrum = pa.reduce(scene, "mean", ("y", "x")) # (B, R, C) → (B,)Program 3:The scene as a carrier: its valid mask, a well pad found by its map coordinates, a crop that moves the transform, and a reduction that leaves a named array.
The kind axis: how is packaged¶
ƒ Function¶
A pure function of arrays, with its parameters passed in on every call:
where:
: the input array; : the output array.
: what needs to know about where the data sits, as plain arrays or numbers (pixel areas, a transform, an air-mass factor, absorption at the band wavelengths).
: parameters, constant over the call.
never sees a name, a CRS or a fill value. That is what lets it run under jit, on any carrier, in any library below GeoStack.
Example. The matched filter, the first step of the running example. With indexing pixels and the spectrum at pixel , it estimates the methane enhancement , in ppm m, that best explains how departs from the background. Here the background is given, as the parameters :
The target signature is the radiance change for one ppm m of methane. Linearising the Beer–Lambert law, for band , gives
where:
, : the background mean and covariance.
: the methane absorption at each band’s wavelength, per ppm m along a vertical path.
: the geometric air-mass factor, one over the cosine of the solar zenith angle plus one over the cosine of the view zenith angle.
: both read off the data, the angles from the attributes and the absorption at the band coordinate’s wavelengths.
: the target signature; multiplies element by element.
With the background given, the estimate is the generalised least-squares fit of a simple model, a pixel’s spectrum as the background plus ppm m of methane along , with Gaussian clutter ; it is also the maximum-likelihood estimate:
where is the clutter at pixel , in radiance units.
Setting the derivative in to zero gives the closed form (13); its standard error is , the same at every pixel.
The output keeps a singleton band axis, .
import einx
import lineax as lx
from jaxtyping import Array, Float
# Shapes: B = N_band bands; R × C = N_row × N_col pixels
def matched_filter(
radiance: Float[Array, "band y x"],
unit_absorption: Float[Array, " band"],
air_mass: float,
*,
mean: Float[Array, " band"],
covariance: lx.AbstractLinearOperator,
) -> Float[Array, "1 y x"]:
"""Methane enhancement of every pixel by a matched filter, background given.
Model: x_n = μ_x + y_n t + ε_n, ε_n ~ 𝒩(0, Σ_x), with θ = (μ_x, Σ_x) known. The
estimate is the generalised least-squares fit of y_n, which is also its
maximum-likelihood estimate:
y_n = argmin_y (x_n − μ_x − y t)ᵀ Σ_x⁻¹ (x_n − μ_x − y t)
= tᵀ Σ_x⁻¹ (x_n − μ_x) / (tᵀ Σ_x⁻¹ t), t = −AMF (k ⊙ μ_x)
Algorithm:
1. t = −AMF (k ⊙ μ_x): the linearised Beer–Lambert response to 1 ppm m.
2. w = Σ_x⁻¹ t, by a solve; a function repeats it on every call.
3. y_n = wᵀ (x_n − μ_x) / (tᵀ w) at every pixel.
Args:
radiance: x, the scene's spectra.
unit_absorption: k, methane absorption per ppm m at each band; part of u.
air_mass: AMF, the geometric air-mass factor; part of u.
mean: μ_x, the background mean; part of θ.
covariance: Σ_x, the background covariance as a PSD operator; part of θ.
Returns:
y in ppm m, with a singleton band axis; its standard error is
(tᵀ Σ_x⁻¹ t)^(−1/2) at every pixel.
"""
# k ⊙ μ_x
absorbed = unit_absorption * mean # (B,), (B,) → (B,)
# t = −AMF (k ⊙ μ_x): the radiance change for 1 ppm m of methane
target = -air_mass * absorbed # (B,) → (B,)
# w = Σ_x⁻¹ t
solution = lx.linear_solve(covariance, target) # (B, B) PSD op, (B,)
filter_direction = solution.value # → (B,)
# tᵀ w
normalisation = einx.dot("band, band ->", target, filter_direction) # → ()
# r_n = x_n − μ_x
residual = einx.subtract( # (B, R, C), (B,) → (B, R, C)
"band y x, band -> band y x", radiance, mean
)
# wᵀ r_n
projection = einx.dot( # (B, R, C), (B,) → (R, C)
"band y x, band -> y x", residual, filter_direction
)
# y_n = wᵀ r_n / (tᵀ w)
enhancement = projection / normalisation # (R, C) → (R, C)
# a singleton band axis
return einx.id("y x -> 1 y x", enhancement) # (R, C) → (1, R, C)Program 4:The matched filter as a function: the background comes in as parameters on every call, and the solve is repeated each time.
▣ Module¶
A function with state. A setup step builds the state once, from data and what it needs to know about them, , and may do work that cannot be traced (a scikit-learn estimator, a k-NN graph, a factorisation). The call is then pure and jittable:
where:
: the data setup sees, one row per sample; for the matched filter, the spectra of the valid pixels, .
: the state, a pytree of arrays held as the Module’s fields next to .
Example. The matched filter as it is used: the plume covers a small fraction of the pixels, so the scene is its own background. Setup estimates and a shrunk from (Ledoit–Wolf, in scikit-learn), forms , and solves once for the filter direction ; the state is . Each call is then two contractions:
where is the filter direction, in inverse radiance units.
What each method solves. Both rest on one model of a pixel’s spectrum, the background plus ppm m of methane along :
fit solves for the background and the filter, once per scene and off the trace: a covariance shrunk towards a scaled identity by the amount that minimises its expected error, and the direction that maximises the signal-to-clutter ratio,
The call solves for each pixel’s enhancement with that state fixed. It is the generalised least-squares fit of the model, which is also the maximum-likelihood estimate under the Gaussian background:
where:
: the background’s departure at pixel , the clutter the filter suppresses.
: the sample covariance of ; ; : the Ledoit–Wolf shrinkage, the value that minimises .
The argmin has the closed form (20), , with standard error at every pixel.
The docstrings below carry the same split: each method states its objective, its steps and its arguments.
import einx
import equinox as eqx
import jax.numpy as jnp
import numpy as np
import scipy.linalg
import sklearn.covariance
from jaxtyping import Array, Float
# Shapes: B = N_band bands; R × C = N_row × N_col pixels; P = N_valid valid pixels
class MatchedFilter(eqx.Module):
"""Matched filter whose background is fitted once, from the scene's own pixels.
Model: a pixel's spectrum is the background plus y ppm m of methane along t,
x_n = μ_x + y_n t + ε_n, ε_n ~ 𝒩(0, Σ_x)
`fit` estimates the background and the filter that model implies; the call
estimates y_n at every pixel with them. The state is ψ = (μ_x, w, tᵀ w).
"""
mean: Float[Array, " band"]
filter_direction: Float[Array, " band"]
normalisation: Float[Array, ""]
@classmethod
def fit(
cls,
spectra: Float[np.ndarray, "pixel band"],
unit_absorption: Float[np.ndarray, " band"],
air_mass: float,
) -> "MatchedFilter":
"""Fit the background and the filter direction, once per scene.
Two objectives, solved in turn. The background covariance is shrunk
towards a scaled identity by the amount that minimises its expected
squared error,
Σ̂_x = (1 − ρ) Σ̄_x + ρ ν I, ρ = argmin_ρ 𝔼 ‖Σ̂_x − Σ_x‖²_F
and the filter direction maximises the signal-to-clutter ratio,
w = argmax_w (wᵀ t)² / (wᵀ Σ̂_x w) ∝ Σ̂_x⁻¹ t, t = −AMF (k ⊙ μ̂_x)
Algorithm:
1. μ̂_x, Σ̂_x: the sample mean and the Ledoit–Wolf shrunk covariance of X.
2. t = −AMF (k ⊙ μ̂_x): the radiance change for 1 ppm m of methane.
3. w = Σ̂_x⁻¹ t, one solve, and the normalisation tᵀ w.
Args:
spectra: X, the spectra of the valid pixels, one row each; the plume
is a small fraction of them, so the scene is its own background.
unit_absorption: k, methane absorption per ppm m at each band.
air_mass: AMF, the geometric air-mass factor.
Returns:
The filter with its state ψ = (μ̂_x, w, tᵀ w); Σ̄_x is the sample
covariance, ν = tr(Σ̄_x) / B and ρ ∈ [0, 1] the shrinkage.
"""
# --- setup: host-side NumPy, SciPy and scikit-learn, runs once ---
# μ̂_x, Σ̂_x = (1 − ρ) Σ̄_x + ρ ν I
background = sklearn.covariance.LedoitWolf().fit(spectra) # (P, B) → fitted
mean = background.location_ # → (B,)
covariance = background.covariance_ # → (B, B)
# k ⊙ μ̂_x
absorbed = unit_absorption * mean # (B,), (B,) → (B,)
# t = −AMF (k ⊙ μ̂_x)
target = -air_mass * absorbed # (B,) → (B,)
# w = Σ̂_x⁻¹ t, solved once
filter_direction = scipy.linalg.solve( # (B, B), (B,) → (B,)
covariance, target, assume_a="pos"
)
# tᵀ w
normalisation = einx.dot("band, band ->", target, filter_direction) # → ()
# ψ = (μ̂_x, w, tᵀ w), as device arrays
return cls(
mean=jnp.asarray(mean),
filter_direction=jnp.asarray(filter_direction),
normalisation=jnp.asarray(normalisation),
)
def __call__(self, radiance: Float[Array, "band y x"]) -> Float[Array, "1 y x"]:
"""Estimate the methane enhancement at every pixel, with ψ fixed.
The generalised least-squares fit of the model to each pixel, which is
the maximum-likelihood estimate under the Gaussian background:
y_n = argmin_y (x_n − μ_x − y t)ᵀ Σ_x⁻¹ (x_n − μ_x − y t)
= wᵀ (x_n − μ_x) / (tᵀ w)
with standard error σ_y = (tᵀ w)^(−1/2), the same at every pixel.
Algorithm:
1. r_n = x_n − μ_x: the departure from the background.
2. wᵀ r_n: its projection on the filter direction.
3. y_n = wᵀ r_n / (tᵀ w): scaled to ppm m.
Args:
radiance: x, the scene's spectra, any number of pixels.
Returns:
y in ppm m, with a singleton band axis. Pure and jittable: no fit.
"""
# --- every call: two contractions, pure and jittable ---
# r_n = x_n − μ_x
residual = einx.subtract( # (B, R, C), (B,) → (B, R, C)
"band y x, band -> band y x", radiance, self.mean
)
# wᵀ r_n
projection = einx.dot( # (B, R, C), (B,) → (R, C)
"band y x, band -> y x", residual, self.filter_direction
)
# y_n = wᵀ r_n / (tᵀ w)
enhancement = projection / self.normalisation # (R, C) → (R, C)
# a singleton band axis
return einx.id("y x -> 1 y x", enhancement) # (R, C) → (1, R, C)Program 5:The matched filter as a Module: fit estimates the background and solves once, off the trace; the call is two contractions, pure and jittable.
→ Operator¶
A pipeline step that lifts onto carriers. The Operator is built from the function and its parameters; it is called on a carrier with its config , a JSON record (which bands, which dimension, the fill policy). It unwraps the carrier with , calls on plain arrays, and rewraps with :
where is the unwrap and the rewrap, both defined below.
Read (26) from the inside out: unwraps, computes, rewraps. The unwrap hands down the array and what needs to know about it, , with every name in already resolved against the carrier’s names and coordinates. passes through untouched; never reaches . The rewrap builds the output carrier:
where:
: the config, names and settings only, so it round-trips through JSON.
, : the unwrap and the rewrap, both read ; also takes the input carrier, whose georeference the output inherits or regrids.
, , : the output’s names, coordinates and georeference.
: the input grid to the output grid, for a reprojection or a resampling.
Operators compose: is what pipekit writes step1 | step2, each step holding its own and .
Example. The settings are the band dim and a spectral window, . resolves them against the carrier: it keeps the bands whose wavelengths in fall in the window, computes from the angles in and those wavelengths, and stacks from the pixels where . The Module’s setup runs on , its call on the window. returns a carrier on the same grid, , with one band named ch4 and NaN where . geoops ships this step as geoops.matched_filter.MatchedFilter, which fits its background on the first call.
import einx
import numpy as np
import pipekit
from geoarray import GeoArray
from geoops.carrier import wrap_like
from radtrax.atmosphere import air_mass_factor
# Shapes: B = N_band bands; W window bands; R × C = N_row × N_col pixels; P valid
# MatchedFilter is the Module above; ch4_unit_absorption is proposed for radtrax
class MethaneEnhancement(pipekit.Operator):
"""CH₄ enhancement on a carrier: the MatchedFilter Module lifted onto GeoArrays.
𝒮[f; ψ](x_geo; cfg) = ι_cfg(f(π_cfg(x_geo); ψ), x_geo)
cfg = (dim, window_nm) says what to read; π_cfg resolves it against the
carrier's coordinates 𝒞 and attrs 𝓜, f is the Module, ι_cfg rewraps.
"""
def __init__(
self, *, dim: str = "band", window_nm: tuple[float, float] = (2122.0, 2488.0)
) -> None:
"""Hold cfg: names and settings only, so the config round-trips through JSON.
Args:
dim: the name of the band dimension.
window_nm: the spectral window, nm, where methane absorbs strongly.
"""
self.dim = dim
self.window_nm = window_nm
def _apply(self, scene: GeoArray["band y x"]) -> GeoArray["1 y x"]:
"""Unwrap, fit the filter, filter, rewrap.
π_cfg(x_geo) = (x_W, u, X), u = (AMF, k)
ψ = setup(X, u), y = f(x_W; ψ)
y_geo = ι_cfg(y, x_geo), Γ_y = Γ
Algorithm:
1. x_W: the bands whose centre wavelengths fall inside the window.
2. u = (AMF, k): AMF from the sun and view angles in 𝓜, k at the
window's wavelengths.
3. X: the spectra of the pixels where the valid mask m is 1.
4. Fit the Module on X and u, then call it on x_W.
5. Rewrap on the same grid: one band named ch4, NaN where m = 0.
Args:
scene: x_geo, the radiance, with band wavelengths in 𝒞 and
solar_zenith_deg, view_zenith_deg in 𝓜.
Returns:
y_geo, the enhancement in ppm m on the scene's grid.
"""
# --- π_cfg: the names in cfg, resolved against 𝒞 and 𝓜 ---
# today (geoarray)
# the band coordinate: names and centre wavelengths
bands = scene.coord(self.dim)
lower, upper = self.window_nm
# the bands whose wavelengths fall inside the window
window = [
name
for name, wavelength in zip(bands.names, bands.wavelength_nm)
if lower <= wavelength <= upper
]
# today (geoarray)
swir = scene.sel({self.dim: window}) # (B, R, C) → (W, R, C)
# today (radtrax)
# AMF = 1 / cos ϑ_sun + 1 / cos ϑ_view, from the angles in the attrs 𝓜
air_mass = air_mass_factor( # → ()
swir.attrs["solar_zenith_deg"], swir.attrs["view_zenith_deg"]
)
# today (geoarray)
wavelengths = swir.coord(self.dim).wavelength_nm # → W labels
# proposed (radtrax)
# k: methane absorption per ppm m at each band's wavelength
unit_absorption = ch4_unit_absorption(wavelengths) # → (W,)
# today (geoarray)
# m: valid where every band is finite and differs from the fill
valid = swir.valid_mask() # (W, R, C) → (R, C)
# X: the spectra of the valid pixels, one row each
swir_values = np.asarray(swir) # (W, R, C) → (W, R, C)
pixels = einx.id("band y x -> (y x) band", swir_values) # → (R C, W)
is_valid = einx.id("y x -> (y x)", valid) # (R, C) → (R C,)
spectra = pixels[is_valid] # (R C, W) → (P, W)
# --- the Module: setup once, then a pure call on plain arrays ---
# user
# ψ = setup(X, u)
matched_filter = MatchedFilter.fit(spectra, unit_absorption, air_mass)
# user
# y = f(x; ψ)
enhancement = matched_filter(swir.data) # (W, R, C) → (1, R, C)
# --- ι_cfg: same grid, one band in ppm m, NaN where m = 0 ---
# y_n = NaN where m_n = 0
masked = np.where(valid, enhancement, np.nan) # (1, R, C) → (1, R, C)
# today (geoops)
return wrap_like(swir, masked, band_names=("ch4",), fill_value=np.nan)Program 6:The Module lifted onto carriers: the unwrap resolves the config against the coordinates and attributes, the Module fits and filters on plain arrays, and the rewrap returns a carrier on the same grid.
The sketches follow the house style: shapes as jaxtyping types, the equation above each line, einx for reshapes and contractions. All six run as written (checked on 6 Nov 2026): the data-axis examples against geotoolz-array and pipekit-array, and the function, the Module and the Operator on a synthetic scene with lineax and scikit-learn. In the Operator, air_mass_factor is radtrax’s (radtrax.atmosphere) and ch4_unit_absorption stands for a lookup table of methane absorption (radtrax, or plumax’s hapi_lut); geoops ships the matching Operators, matched_filter.MatchedFilter, plume.PlumeMask, plume.ColumnToMass and plume.IMEEstimate.
Parallels: operator learning, Lift & Learn and Koopman
The shape of an Operator, down, compute, up, is not new: neural operators and lifted reduced models use it too. Here is how they line up, and where they differ.
Operator learning. A neural operator learns a map between function spaces, from an input field to an output field , with the coordinates of the domain. Every architecture in the family factors into an encoder, an approximator and a reconstructor (Lanthaler, Mishra and Karniadakis, 2022; Kovachki, Lanthaler and Stuart, 2024):
where:
: the encoder, from a field to a vector, its values at sensors or on a grid.
: the approximator, from vector to vector: the network.
: the reconstructor, from the output vector back to a field.
DeepONet’s sensor values are , its branch net and its trunk net the basis of (Lu et al., 2021). The Fourier neural operator raises the channels with a map , applies its kernel layers, and lowers them with (Li et al., 2021; Kovachki et al., 2023). A carrier is a discretised field, and its georeference says which discretisation, so plays , plays and plays . Discretisation invariance, one operator for any grid, is the counterpart of an Operator that runs on any carrier whose names resolve.
Lift & Learn and Koopman. These change the state’s variables to ones in which the dynamics are simpler, learn the simple model there, and map back. Take the state as a vector . Lift & Learn (Qian, Kramer, Peherstorfer and Willcox, 2020) picks a lifting in which the dynamics are quadratic, and fits the two operators by least squares from snapshots, which is operator inference (Peherstorfer and Willcox, 2016):
where is time and the Kronecker product, so .
Koopman’s view (Koopman, 1931) lifts into a dictionary of observables in which the dynamics are linear; extended dynamic mode decomposition fits the finite Koopman matrix from snapshot pairs (Williams, Kevrekidis and Rowley, 2015):
where:
: the lifting; , the lifted state.
, : the linear and quadratic operators.
: the observables; , the Koopman matrix.
What carries over, and what does not.
The same shape. A map down, a computation on plain vectors, a map up. In both literatures, and here, the point is that the middle is written once and reused under any encoder.
The opposite direction. There, lifting goes up: into more channels, or into coordinates where the model is linear or quadratic. Here goes down: it strips the names and the georeference and keeps the values as they are. That clash is one reason this page writes rather than “lift”.
A different job. Their lift changes the variables, so it is part of the model, designed or learned with it. Ours changes only the container: it is bookkeeping, and sees the same numbers either way.
They nest. A Lift & Learn or Koopman model is a Module: its setup fits or from snapshots , and its call applies the lifting, the learned map and the map back. A trained neural operator is a Module too. Wrapping either in puts it on carriers, with the unwrap and the rewrap of the carrier handled by and .
The running example, end to end¶
Four steps in one recipe, each a lifted function, in three stages: retrieval (the first line), segmentation (the second) and quantification (the last two).
Here is the methane enhancement in ppm m and the plume mask, both on the scene’s grid; is ERA5’s 10 m wind speed on its own 0.25° grid, read at the source’s coordinates to give the wind in m s⁻¹; and is the emission rate in kg s⁻¹. is the Module above, with fitted on the scene; thresholds and keeps connected components; is the integrated mass enhancement method:
with the mask at pixel , its area and the plume length, both from , and the mass of methane per square metre in one ppm m. The last step takes as its parameter , and it is terminal: returns a table ( with its uncertainty), not a carrier. Only the four configs mention band names, windows, units, thresholds or the source’s coordinates. In geoops the steps are MatchedFilter, PlumeMask, interp_at on the wind, and ColumnToMass followed by IMEEstimate.
Each line here owns everything it needs. The same job, refactored into pieces that are written once and reused, is worked through on the trace-gas example, which climbs the role ladder on this plume.
Table 3:Each symbol, what it is, and the lowest layer it lives in.
| Symbol | Is | Lives in |
|---|---|---|
| , | plain array; function | Core, GeoNumerics and up |
| , | Module: setup runs once; and are its fields | Core, GeoNumerics and up |
| , | named array; operations by name | Core (pipekit-array) and up |
| , , | carrier: CRS, transform, fill and attributes; valid mask | GeoStack (geoarray; xarray on the states side) |
| , , | unwrap, rewrap, Operator on carriers; is its config | GeoStack; GeoModels in a geo extra |
| geometry as plain arrays, handed down | computed by the GeoStack; consumed by functax, gridax, geophysix |
The three invariants, as equations. Arrays go everywhere: every rung takes . Carriers stop at the GeoStack: nothing below sees , only . Configs stop at Operators: is consumed by and and never reaches , which takes only , and .
Two axes, side by side¶
Code in the stack is packaged as one of three kinds: a function, a Module or an Operator. Each kind can work on one of three kinds of data: plain arrays, named arrays, or carriers. These are two separate axes. geoarray is not a fourth kind; it sits on the data axis. Names in italics are proposed.
The two axes. The kind says how a name is packaged and how it is named; the data says what flows through it. Any kind can sit with any data, within the cells that rule 1 allows. Names in italics are proposed.
“Kicking a Module up a notch” is two separate steps. Wrapping it in an Operator adds composition: a config, |, graph mode. Moving it to carriers adds georeference: the CRS, the fill, the attrs. The steps are independent. JaxModelOp and a DA cycle take the first step without the second; geoarray’s crop and read_window take the second without the first. geoops Operators take both.
The role ladder, across the kinds¶
The third axis is the role each name plays in its library’s API, from ⓪ structures up to ⑥ recipes, with orchestration above. It sits across the three kinds rather than beside them: ① primitives and ④ algorithms are functions, ⓪ structures, ② strategies and ③ models are Modules, and ⑤ steps and ⑥ recipes are Operators. The role ladder gives the ladder read as grammar, its rules and who works where, and the trace-gas example climbs it on this page’s plume, piece by piece, up to the recipe and its orchestration. One point of the ladder belongs on this page: the data are nouns too. ▦ arrays, ▤ named arrays and ◆ carriers are the ⓪ structures of the data axis: DimArray is pipekit-array’s noun, GeoArray, GeoSwath and GeoPoints are geoarray’s, and geoarray’s own verbs (crop, to_pixel, read_window) are the ① primitives that act on them. The kind and data axes say how a noun is packaged and what it knows; the ladder says it is a noun.
One vocabulary per axis¶
Each axis gets its own words and its own mark, so no two axes share one. The letter L goes back to the axis that owns it in remote sensing: the processing levels of the data.
Table 4:The six axes, each with its question, its words and its mark.
| Axis | Asks | Vocabulary | Mark |
|---|---|---|---|
| role | what job does it do in its library’s API? | ⓪ structure (noun) · ① primitive (verb) · ② strategy (adverb) · ③ model (noun phrase) · ④ algorithm (sentence) · ⑤ step (sentence with its settings) · ⑥ recipe (paragraph); orchestration above, not a rung | circled digit |
| kind | how is it packaged? | ƒ function · ▣ Module · → Operator | glyph |
| data | what does it see? | ▦ array · ▤ named array · ◆ carrier | glyph |
| layer | where does it live? | Core · GeoNumerics · GeoStack (geotoolz + xrtoolz) · GeoModels · GeoBench · GeoApps | name |
| tier | what may it import? | T0 to T4, within a layer | T |
| level | how processed is the data? (data products, not code) | L0 raw · L1 calibrated · L2 geophysical · L3 gridded · L4 model output | L |
Two names on every axis. gaussx.CGSolver: ② strategy · ▣ Module · ▦ array · Core T0. geoops.matched_filter.MatchedFilter: ⑤ step · → Operator · ◆ carrier · GeoStack T3; it turns an L1B radiance scene into an L2 enhancement product.
How the axes constrain each other. The role fixes the kind: ① and ④ are functions, ⓪, ② and ③ are Modules (or, at ⓪, a third-party array), ⑤ and ⑥ are Operators (a recipe in code is a Sequential or Graph, itself an Operator; in data, the YAML that loads into one), so a library’s chips only need the digit. The kind and the data fix the lowest layer. Inside one library, imports follow the roles upward, nouns first; the one entanglement left is between verbs and adverbs (a primitive takes a strategy; some strategies call primitives), which gaussx documents as its dispatch core.
What this retires. The kind once called “primitive” is now “function”, so “primitive” names one role (①) only. geostack’s docs/design/stack_levels.md L1 to L3 (primitives and machinery, operators on carriers, pipelines) were a mix of kind and data; the glyph pairs say the same without a number (ƒ ▣ on ▦; → on ◆; ⑤ steps composed into ⑥ recipes). Two words stay where the field uses them on purpose: “linear operator” (lineax’s AbstractLinearOperator, a ⓪ structure) and “observation operator” (). Capital-O Operator means pipekit’s kind only.
Rule 1: the cell decides the layer¶
Every public name sits in one cell of this grid, and each cell has a lowest layer it may live in.
Table 5:The nine cells of kind by data, each with its names and the lowest layer it may live in.
| ▦ plain array | ▤ named array | ◆ carrier | |
|---|---|---|---|
| ƒ function | einx.dot, a functax stencil’s apply, geoarray.to_pixel(transform, xy), geophysix.coriolis(lat). Lowest: Core, GeoNumerics and up | pipekit_array.run_kernel. Lowest: Core (pipekit-array) and up | geoarray’s own verbs: crop, pad, read_window, stack. They move data and georeference together and never compute a new field. Lowest: GeoStack and up |
| ▣ Module | functax plans, gridax grids, gaussx and kernellib operators, finitevolX operators, the models. Lowest: Core, GeoNumerics and up | empty by design: a Module works on plain arrays, and an Operator puts the names on | never: a Module never holds or takes a carrier |
| → Operator | JaxModelOp, DACycle, TrainingLoop, rollouts. Lowest: Core, GeoModels; never GeoNumerics | ISel, Reduce, ArgReduce, MapOver, KernelOp (pipekit-array). Lowest: Core (pipekit-array) and up | geoops, xrops; each model’s geo extra. Lowest: GeoStack; GeoModels in the geo extra |
GeoNumerics fills only the plain-array column, and only its first two rows. Core adds Operators on plain arrays and, through pipekit-array, the named-array column. The carrier column starts at GeoStack. This also settles the xarray adapter in pipekit-array without an exception: there a DataArray is a named array, which Core may hold. As a carrier, with a CRS, it belongs to xrops.
Which cell is it?¶
Kind. Does it subclass
pipekit.Operator? Then it is an Operator, whatever else it inherits;JaxOperatoris also aneqx.Moduleand is still an Operator. Else, is it a class whose setup does work before a pure call? A Module. Else it is a function.Data. Does it take or return a CRS, a fill or attrs? Carrier. Dims with names and coordinates, but no CRS? Named array. Neither? Plain array.
Do we need a name change?¶
Not in code; in prose, yes. In code the namespaces already separate the two kinds of operator (lineax calls its own AbstractLinearOperator), and renaming pipekit.Operator would touch pipekit, every geoops and xrops class, vardax, plumax and sesmax, all for a prose problem. “Observation operator” is the field’s own word for and stays. In prose: function for the kind (not “kernel”, which kernellib uses for covariance functions, nor “primitive”, which now names the ① role), Module, Operator with a capital O for pipekit’s, and carrier for the data. The full vocabulary, one per axis, is in the table above. The suffix rules on the library cards of the layer map keep the class names apart as well.
Rule 2: the tier decides what a library may import¶
Unchanged: a library imports any lower layer, and lower tiers of its own layer. A tier never changes which kinds a library may define. pipekit and gaussx are both Core tier 0, yet one defines Operators and the other Modules; the cells come from the layer.
Rule 3: the kind and the data decide what a name may take and call¶
What flows down and back up through the four kinds, for one Operator that samples a carrier at points. Blue is outside the trace, amber is built once by setup, teal runs inside jit. Names in italics are proposed.
Rule 4: each library declares its cells¶
Every row of the boundaries table on the layer map carries the kinds and data that library exports. Each must be allowed in the library’s layer (rule 1), and a public name sits in exactly one cell. “geo” marks Operators on carriers that live in a model’s geo extra.
What enforces it, and where it breaks today¶
tests/test_dependency_graph.py gets a list of forbidden imports per layer, counted in src/ only (scripts and notebooks are exempt), with a KNOWN list that only shrinks:
Table 6:What each lower layer never imports, where that breaks today, and the fix.
| Layer | Never imports | Breaks today | Fix |
|---|---|---|---|
| GeoNumerics | pipekit*, pyproj, rasterio, xarray, geoarray, geoops, xrops, every GeoStack package | nothing in src/; xarray only in the scripts and notebooks of finitevolX and spectraldiffx | none needed |
| Core | pyproj, rasterio, xarray, geoarray, geoops, xrops, every GeoStack package | xtremax.extraction and xtremax.simulations (7 modules); vardax _src/utils/patches.py and masks.py; pyrox-lgm’s lazy to_xarray in _result.py; pipekit_array.xarray | one per package, below |
The fixes for Core, one per package:
xtremax: extraction and simulations on xarray move to xrtoolz; the extremes modelling stays.
vardax:
extract_patchesand the three masks take Datasets, so their xarray halves move to xrtoolz; the array halves (masks from a shape and a key, window starts) stay in vardax as primitives;trajectory_to_xr_datasetstays as an export at the edge.pyrox-lgm:
to_xarraystays as an export at the edge.pipekit_array.xarray: not a break. It adapts
DataArrayas a named array, which Core may hold; Dataset and DataTree dispatch is already in xrops (PK-P5).
The Operator contract itself is already enforced: test_operator_contract.py in geotoolz walks every geoops Operator, and geoops.testing.check_operator runs the same checks on Operators outside geotoolz, such as the models’ geo extras.
geoarray, gridax and functax: geometry has no CRS below GeoStack¶
geoarray stays a package of the geotoolz workspace and keeps every carrier. What moves out is the geometry maths it does today. Each geoarray grid becomes a CRS-free grid from below, with a pyproj.CRS attached. Affine raster grids are the CRS-free geometry functax already owns for interpolation; the grids that physics needs (curvilinear, swath, staggered, vertical) are gridax’s; anything that knows the Earth’s shape comes from geophysix.
Table 7:Each piece of geometry, and what functax, gridax and geoarray each hold of it.
| Concept | functax (Core) | gridax (GeoNumerics) | geoarray (GeoStack) |
|---|---|---|---|
| Affine raster grid | AffineGrid(transform, shape): res, bounds, shift, crop(window), window(bounds), pixel centres | none | Grid = an AffineGrid + a CRS; stays hashable, keeps isclose and get_config / from_config |
| World to pixel | to_pixel(grid, xy): fractional indices, the “find” step of a plan | none | reprojects the points with pyproj, then calls functax |
| Pixel coordinates | pixel centres and corners of an AffineGrid | none | pixel_coords(g) reads the grid and calls functax |
| Pixel windows | none | none | PixelWindow stays: it is the read contract of RasterSource. read_window, write_window, crop, pad move the data and call AffineGrid.shift |
| Curvilinear and swath grids | none | CurvilinearGrid(lat, lon), swath geometry: cell corners and areas, neighbours, nearest cell | CurvilinearGrid and SwathGrid add the CRS of lat/lon; GeoSwath keeps per-scene lat/lon as leaves |
| Physical grid structure | none | Arakawa staggering, metric arrays (dx, dy, areas), masks, vertical coordinates and remapping | Vertical, VerticalAxis: labels only |
| Areas on the Earth | none | cell areas of any grid, on the ellipsoid from geophysix | pixel_area (designed): reads the CRS, picks planar or ellipsoidal, calls gridax |
| Footprint in another CRS | bounds in grid coordinates | none | footprint: a Shapely polygon, densified and reprojected with pyproj |
| CRS, fill, attrs, dims, readers, georeader interop | never | never | only here |
A condition for the move: geoarray installs and runs on NumPy alone, so the kernels it calls must too. functax and gridax take the array namespace (xp) in those kernels and import JAX only when a JAX array arrives. If that costs more than it saves, geoarray keeps its four affine helpers, and a test pins them equal to functax’s.
Sources and status
From the artifact “Three kinds of function, three kinds of data” (GeoStack kinds and roles, a working page of 6 November 2026, split from the GeoStack layer map), which is also linked in full from the kinds and roles design page. Its role ladder, who works where and the running example climbed up the ladder are not repeated here: they are on the role ladder and the trace-gas example. The six sketches were run by the artifact as written on 6 November 2026, the data-axis ones against geotoolz-array and pipekit-array and the function, Module and Operator on a synthetic scene with lineax and scikit-learn; they were not run again for this page, and no name was checked again against the pins. today and proposed follow the artifact’s markers; names in italics are proposed. The page cites one internal marker, PK-P5, and no issue or PR numbers. The page has no notebook behind it.
- Peherstorfer, B., & Willcox, K. (2016). Data-driven operator inference for nonintrusive projection-based model reduction. Computer Methods in Applied Mechanics and Engineering, 306, 196–215. 10.1016/j.cma.2016.03.025
- Koopman, B. O. (1931). Hamiltonian Systems and Transformation in Hilbert Space. Proceedings of the National Academy of Sciences, 17(5), 315–318. 10.1073/pnas.17.5.315