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.

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.

Keywords:kindsfunctionModuleOperatorplain arraynamed arraycarrierGeoArrayDimArraylayerstiersvocabulary

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.

ProblemWhat goes wrong, silentlyWhat fixes it
Axes by positionEMIT’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 georeferenceThe 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 gridsThe 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)
NodataA 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 containerThe 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 tracedThe 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 scriptsThe 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, y=f(x,u;θ)\vect{y} = f(\vect{x}, \vect{u}; \gvect{\theta}), and an Operator that lifts that function onto geographic data, S[f;θ](xgeo;cfg)\mathcal{S}[f; \gvect{\theta}](\vect{x}_\text{geo}; \mathrm{cfg}). 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:

Two axes follow from those ideas: what the data knows (x\vect{x} or xgeo\vect{x}_\text{geo}), and how the code is packaged (ff, a Module, or S[f;θ]\mathcal{S}[f; \gvect{\theta}]).

The data axis: what x\vect{x} knows

▦ Plain array

A block of numbers with a shape and nothing else:

x∈RN1×…×NNax\vect{x} \in \mathbb{R}^{N_1 \times \ldots \times N_{N_\text{ax}}}

where:

Example. The scene is x∈RNband×Nrow×Ncol\vect{x} \in \mathbb{R}^{N_\text{band} \times N_\text{row} \times N_\text{col}}, so Nax=3N_\text{ax} = 3. 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 dqd_q and a coordinate vector sq\vect{s}_q for each axis:

xnamed=(x,d,C)\vect{x}_\text{named} = (\vect{x}, \vect{d}, \mathcal{C})
d=(d1,…,dNax)\vect{d} = (d_1, \ldots, d_{N_\text{ax}})
C=(s1,…,sNax)\mathcal{C} = (\vect{s}_1, \ldots, \vect{s}_{N_\text{ax}})

where:

An operation addresses an axis by name, and the array finds its position. Take a reduction rqr_q (a mean, a sum, a maximum) over axis qq of a plain array: it maps RN1×…×NNax\mathbb{R}^{N_1 \times \ldots \times N_{N_\text{ax}}} to the same space with the factor NqN_q left out. On a named array the same reduction is asked for by a name dd. The array looks up its position, q=posd(d)q = \op{pos}_{\vect{d}}(d), reduces there, and removes that axis’s name and coordinates, since the output no longer has that axis:

rd(xnamed)=(rq(x),d−q,C−q)r_d(\vect{x}_\text{named}) = (r_q(\vect{x}), \vect{d}_{-q}, \mathcal{C}_{-q})
d−q=(d1,…,dq−1,dq+1,…,dNax)\vect{d}_{-q} = (d_1, \ldots, d_{q-1}, d_{q+1}, \ldots, d_{N_\text{ax}})
C−q=(s1,…,sq−1,sq+1,…,sNax)\mathcal{C}_{-q} = (\vect{s}_1, \ldots, \vect{s}_{q-1}, \vect{s}_{q+1}, \ldots, \vect{s}_{N_\text{ax}})

where:

Example. d=(band,y,x)\vect{d} = (\texttt{band}, \texttt{y}, \texttt{x}), with s1\vect{s}_1 the band wavelengths. The mean spectrum reduces by name twice, over y\texttt{y} at posd(y)=2\op{pos}_{\vect{d}}(\texttt{y}) = 2 and then over x\texttt{x}, and returns names (band)(\texttt{band}) 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 Γ\Gamma:

xgeo=(xnamed,Γ)\vect{x}_\text{geo} = (\vect{x}_\text{named}, \Gamma)
Γ=(crs,A,xfill,M)\Gamma = (\op{crs}, \mat{A}, x_\text{fill}, \mathcal{M})

where:

The transform says where each pixel is. The top-left corner of the pixel in row ii and column jj sits at map coordinates sij∈R2\vect{s}_{ij} \in \mathbb{R}^2, and its centre at (j+1/2,i+1/2)(j + 1/2, i + 1/2) in pixel units:

sij=A(ji1)\vect{s}_{ij} = \mat{A} \begin{pmatrix} j \\ i \\ 1 \end{pmatrix}

where sij\vect{s}_{ij} 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 m∈{0,1}Nrow×Ncol\vect{m} \in \{0, 1\}^{N_\text{row} \times N_\text{col}}, with cc indexing bands:

[m]ij=∏c=1Nband1[xc,i,j≠xfill]1[xc,i,j is finite][\vect{m}]_{ij} = \prod_{c=1}^{N_\text{band}} \mathbf{1}[x_{c,i,j} \neq x_\text{fill}] \mathbf{1}[x_{c,i,j} \text{ is finite}]

where xc,i,jx_{c,i,j} is the value of band cc at pixel (i,j)(i, j) and 1[⋅]\mathbf{1}[\cdot] is one when its condition holds and zero otherwise.

For a swath or a curvilinear grid, as EMIT’s radiance is before orthorectification, A\mat{A} is replaced by per-pixel coordinates Slon,Slat∈RNrow×Ncol\mat{S}_\text{lon}, \mat{S}_\text{lat} \in \mathbb{R}^{N_\text{row} \times N_\text{col}}; the rest is the same.

Example. The scene is a carrier on a 60 m grid in UTM zone 13N with xfill=−9999x_\text{fill} = -9999, the band names and centre wavelengths in C\mathcal{C}, and the sun and view zenith angles in M\mathcal{M}. The well pad at map coordinates s\vect{s} is found at pixel (i,j)(i, j) by solving s=A(j,i,1)⊤\vect{s} = \mat{A} (j, i, 1)^\top for (i,j)(i, j), which is to_pixel. Slice the bare array instead, np.asarray(scene)[..., 100:164, 100:164], and A\mat{A} 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 ff is packaged

ƒ Function

A pure function of arrays, with its parameters passed in on every call:

y=f(x,u;θ)\vect{y} = f(\vect{x}, \vect{u}; \gvect{\theta})

where:

ff 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 n=1,…,NrowNcoln = 1, \ldots, N_\text{row} N_\text{col} indexing pixels and xn∈RNband\vect{x}_n \in \mathbb{R}^{N_\text{band}} the spectrum at pixel nn, it estimates the methane enhancement yny_n, in ppm m, that best explains how xn\vect{x}_n departs from the background. Here the background is given, as the parameters θ=(μx,Σx)\gvect{\theta} = (\gvect{\mu}_x, \gmat{\Sigma}_x):

yn=t⊤Σx−1(xn−μx)t⊤Σx−1ty_n = \frac{\vect{t}^\top \gmat{\Sigma}_x^{-1} (\vect{x}_n - \gvect{\mu}_x)}{\vect{t}^\top \gmat{\Sigma}_x^{-1} \vect{t}}

The target signature t\vect{t} is the radiance change for one ppm m of methane. Linearising the Beer–Lambert law, xn,c≈μx,c(1−AMFkcyn)x_{n,c} \approx \mu_{x,c} (1 - \mathrm{AMF} k_c y_n) for band cc, gives

t=−AMF(k⊙μx)\vect{t} = -\mathrm{AMF} (\vect{k} \odot \gvect{\mu}_x)

where:

With the background given, the estimate is the generalised least-squares fit of a simple model, a pixel’s spectrum as the background plus yny_n ppm m of methane along t\vect{t}, with Gaussian clutter εn\gvect{\varepsilon}_n; it is also the maximum-likelihood estimate:

xn=μx+ynt+εn\vect{x}_n = \gvect{\mu}_x + y_n \vect{t} + \gvect{\varepsilon}_n
εn∼N(0,Σx)\gvect{\varepsilon}_n \sim \mathcal{N}(\vect{0}, \gmat{\Sigma}_x)
yn=argminy(xn−μx−yt)⊤Σx−1(xn−μx−yt)y_n = \op{argmin}_{y} (\vect{x}_n - \gvect{\mu}_x - y \vect{t})^\top \gmat{\Sigma}_x^{-1} (\vect{x}_n - \gvect{\mu}_x - y \vect{t})

where εn∈RNband\gvect{\varepsilon}_n \in \mathbb{R}^{N_\text{band}} is the clutter at pixel nn, in radiance units.

Setting the derivative in yy to zero gives the closed form (13); its standard error is σy=(t⊤Σx−1t)−1/2\sigma_y = (\vect{t}^\top \gmat{\Sigma}_x^{-1} \vect{t})^{-1/2}, the same at every pixel.

The output keeps a singleton band axis, y∈R1×Nrow×Ncol\vect{y} \in \mathbb{R}^{1 \times N_\text{row} \times N_\text{col}}.

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 ψ\gvect{\psi} once, from data X\mat{X} and what it needs to know about them, u\vect{u}, 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:

ψ=setup(X,u;θ)\gvect{\psi} = \op{setup}(\mat{X}, \vect{u}; \gvect{\theta})
y=f(x,u;θ,ψ)\vect{y} = f(\vect{x}, \vect{u}; \gvect{\theta}, \gvect{\psi})

where:

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 μx\gvect{\mu}_x and a shrunk Σx\gmat{\Sigma}_x from X\mat{X} (Ledoit–Wolf, in scikit-learn), forms t\vect{t}, and solves once for the filter direction w=Σx−1t\vect{w} = \gmat{\Sigma}_x^{-1} \vect{t}; the state is ψ=(μx,w,t⊤w)\gvect{\psi} = (\gvect{\mu}_x, \vect{w}, \vect{t}^\top \vect{w}). Each call is then two contractions:

yn=w⊤(xn−μx)t⊤wy_n = \frac{\vect{w}^\top (\vect{x}_n - \gvect{\mu}_x)}{\vect{t}^\top \vect{w}}

where w∈RNband\vect{w} \in \mathbb{R}^{N_\text{band}} 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 yny_n ppm m of methane along t\vect{t}:

xn=μx+ynt+εn\vect{x}_n = \gvect{\mu}_x + y_n \vect{t} + \gvect{\varepsilon}_n
εn∼N(0,Σx)\gvect{\varepsilon}_n \sim \mathcal{N}(\vect{0}, \gmat{\Sigma}_x)

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,

Σ^x=(1−ρ)Σˉx+ρνI\hat{\gmat{\Sigma}}_x = (1 - \rho) \bar{\gmat{\Sigma}}_x + \rho \nu \mat{I}
w=argmaxw(w⊤t)2w⊤Σ^xw∝Σ^x−1t\vect{w} = \op{argmax}_{\vect{w}} \frac{(\vect{w}^\top \vect{t})^2}{\vect{w}^\top \hat{\gmat{\Sigma}}_x \vect{w}} \propto \hat{\gmat{\Sigma}}_x^{-1} \vect{t}

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:

yn=argminy(xn−μx−yt)⊤Σx−1(xn−μx−yt)y_n = \op{argmin}_{y} (\vect{x}_n - \gvect{\mu}_x - y \vect{t})^\top \gmat{\Sigma}_x^{-1} (\vect{x}_n - \gvect{\mu}_x - y \vect{t})

where:

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 ff onto carriers. The Operator S[f;θ]\mathcal{S}[f; \gvect{\theta}] is built from the function and its parameters; it is called on a carrier with its config cfg\mathrm{cfg}, a JSON record (which bands, which dimension, the fill policy). It unwraps the carrier with πcfg\pi_\mathrm{cfg}, calls ff on plain arrays, and rewraps with ιcfg\iota_\mathrm{cfg}:

S[f;θ](xgeo;cfg)=ιcfg(f(πcfg(xgeo);θ),xgeo)\mathcal{S}[f; \gvect{\theta}](\vect{x}_\text{geo}; \mathrm{cfg}) = \iota_\mathrm{cfg}(f(\pi_\mathrm{cfg}(\vect{x}_\text{geo}); \gvect{\theta}), \vect{x}_\text{geo})
πcfg(xgeo)=(x,u)\pi_\mathrm{cfg}(\vect{x}_\text{geo}) = (\vect{x}, \vect{u})

where πcfg\pi_\mathrm{cfg} is the unwrap and ιcfg\iota_\mathrm{cfg} the rewrap, both defined below.

Read (26) from the inside out: πcfg\pi_\mathrm{cfg} unwraps, ff computes, ιcfg\iota_\mathrm{cfg} rewraps. The unwrap hands down the array and what ff needs to know about it, u\vect{u}, with every name in cfg\mathrm{cfg} already resolved against the carrier’s names and coordinates. θ\gvect{\theta} passes through untouched; cfg\mathrm{cfg} never reaches ff. The rewrap builds the output carrier:

ιcfg(y,xgeo)=ygeo=((y,dy,Cy),Γy)\iota_\mathrm{cfg}(\vect{y}, \vect{x}_\text{geo}) = \vect{y}_\text{geo} = ((\vect{y}, \vect{d}_y, \mathcal{C}_y), \Gamma_y)
Γy={Γsame gridregridcfg(Γ)new grid\Gamma_y = \begin{cases} \Gamma & \text{same grid} \\ \op{regrid}_\mathrm{cfg}(\Gamma) & \text{new grid} \end{cases}

where:

Operators compose: S[f2;θ2](S[f1;θ1](xgeo;cfg1);cfg2)\mathcal{S}[f_2; \gvect{\theta}_2](\mathcal{S}[f_1; \gvect{\theta}_1](\vect{x}_\text{geo}; \mathrm{cfg}_1); \mathrm{cfg}_2) is what pipekit writes step1 | step2, each step holding its own θ\gvect{\theta} and cfg\mathrm{cfg}.

Example. The settings are the band dim and a spectral window, cfg={dim:band,window:[2122,2488] nm}\mathrm{cfg} = \{\text{dim}: \texttt{band}, \text{window}: [2122, 2488] \ \mathrm{nm}\}. πcfg\pi_\mathrm{cfg} resolves them against the carrier: it keeps the bands whose wavelengths in C\mathcal{C} fall in the window, computes u=(AMF,k)\vect{u} = (\mathrm{AMF}, \vect{k}) from the angles in M\mathcal{M} and those wavelengths, and stacks X\mat{X} from the pixels where [m]ij=1[\vect{m}]_{ij} = 1. The Module’s setup runs on X\mat{X}, its call on the window. ιcfg\iota_\mathrm{cfg} returns a carrier on the same grid, Γy=Γ\Gamma_y = \Gamma, with one band named ch4 and NaN where [m]ij=0[\vect{m}]_{ij} = 0. 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.

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).

ygeo=S[fmf;ψ](xgeo;cfg1)\vect{y}_\text{geo} = \mathcal{S}[f_\text{mf}; \gvect{\psi}](\vect{x}_\text{geo}; \mathrm{cfg}_1)
bgeo=S[fmask](ygeo;cfg2)\vect{b}_\text{geo} = \mathcal{S}[f_\text{mask}](\vect{y}_\text{geo}; \mathrm{cfg}_2)
U=S[fwind](vgeo;cfg3)U = \mathcal{S}[f_\text{wind}](\vect{v}_\text{geo}; \mathrm{cfg}_3)
Q=S[fime;U](ygeo,bgeo;cfg4)Q = \mathcal{S}[f_\text{ime}; U](\vect{y}_\text{geo}, \vect{b}_\text{geo}; \mathrm{cfg}_4)

Here ygeo\vect{y}_\text{geo} is the methane enhancement in ppm m and bgeo\vect{b}_\text{geo} the plume mask, both on the scene’s grid; vgeo\vect{v}_\text{geo} is ERA5’s 10 m wind speed on its own 0.25° grid, read at the source’s coordinates to give the wind UU in m s⁻¹; and QQ is the emission rate in kg s⁻¹. fmff_\text{mf} is the Module above, with ψ\gvect{\psi} fitted on the scene; fmaskf_\text{mask} thresholds and keeps connected components; fimef_\text{ime} is the integrated mass enhancement method:

Q=UL∑n=1NrowNcolbnκynanQ = \frac{U}{L} \sum_{n=1}^{N_\text{row} N_\text{col}} b_n \kappa y_n a_n

with bnb_n the mask at pixel nn, ana_n its area and LL the plume length, both from A\mat{A}, and κ\kappa the mass of methane per square metre in one ppm m. The last step takes UU as its parameter θ\gvect{\theta}, and it is terminal: ιcfg\iota_\mathrm{cfg} returns a table (QQ with its uncertainty), not a carrier. Only the four configs cfg1,…,cfg4\mathrm{cfg}_1, \ldots, \mathrm{cfg}_4 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.

SymbolIsLives in
x\vect{x}, f(x,u;θ)f(\vect{x}, \vect{u}; \gvect{\theta})plain array; functionCore, GeoNumerics and up
setup\op{setup}, ψ\gvect{\psi}Module: setup runs once; θ\gvect{\theta} and ψ\gvect{\psi} are its fieldsCore, GeoNumerics and up
xnamed=(x,d,C)\vect{x}_\text{named} = (\vect{x}, \vect{d}, \mathcal{C}), rdr_dnamed array; operations by nameCore (pipekit-array) and up
xgeo=(xnamed,Γ)\vect{x}_\text{geo} = (\vect{x}_\text{named}, \Gamma), m\vect{m}, A\mat{A}carrier: CRS, transform, fill and attributes; valid maskGeoStack (geoarray; xarray on the states side)
πcfg\pi_\mathrm{cfg}, ιcfg\iota_\mathrm{cfg}, S[f;θ]\mathcal{S}[f; \gvect{\theta}]unwrap, rewrap, Operator on carriers; cfg\mathrm{cfg} is its configGeoStack; GeoModels in a geo extra
u\vect{u}geometry as plain arrays, handed downcomputed by the GeoStack; consumed by functax, gridax, geophysix

The three invariants, as equations. Arrays go everywhere: every rung takes x\vect{x}. Carriers stop at the GeoStack: nothing below sees xgeo\vect{x}_\text{geo}, only πcfg(xgeo)=(x,u)\pi_\mathrm{cfg}(\vect{x}_\text{geo}) = (\vect{x}, \vect{u}). Configs stop at Operators: cfg\mathrm{cfg} is consumed by πcfg\pi_\mathrm{cfg} and ιcfg\iota_\mathrm{cfg} and never reaches ff, which takes only x\vect{x}, u\vect{u} and θ\gvect{\theta}.

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.

Axis 1 · kind: how the code is packaged
ƒfunction
A function. No state, no setup: inputs in, outputs out.
Named
for what it computes: to_pixel, cell_area
▣Module
An eqx.Module with state. The expensive, untraceable setup runs once at construction or fit (a k-NN graph, a Delaunay triangulation, a factorisation); the call is then pure and jittable.
Named
for the object: AffineGrid, BilinearPlan, Matern52. *Operator only for a linear map or an observation operator H
→Operator
A pipekit.Operator: composes with |, runs in a Graph, round-trips its config through JSON. Any Module can become one by wrapping.
Named
for the action, no suffix: Reproject, PlumeMask. *Op only for an Operator that wraps a Module: JaxModelOp, SomaxModelOp
Axis 2 · data: what flows through it
▦plain array
A NumPy or JAX array. Shapes live in jaxtyping annotations; geometry arrives as separate arguments.
Examples
Float[Array, "y x"], a transform passed alongside it
▤named array
An array whose dims have names and coordinates, but no georeference: no CRS, no fill semantics.
Examples
pipekit-array's DimArray; an xarray.DataArray used as a labelled array
◆carrier
A named array plus its georeference: a grid with a CRS, a fill value, attrs; or a lazy reader of one.
Examples
GeoArray, GeoSwath, GeoPoints, RasterSource; a DataArray in xrops, where its coords and CRS mean geography

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.

AxisAsksVocabularyMark
rolewhat 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 rungcircled digit
kindhow is it packaged?ƒ function · ▣ Module · → Operatorglyph
datawhat does it see?▦ array · ▤ named array · ◆ carrierglyph
layerwhere does it live?Core · GeoNumerics · GeoStack (geotoolz + xrtoolz) · GeoModels · GeoBench · GeoAppsname
tierwhat may it import?T0 to T4, within a layerT
levelhow processed is the data? (data products, not code)L0 raw · L1 calibrated · L2 geophysical · L3 gridded · L4 model outputL

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” (H\mat{H}). 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
ƒ functioneinx.dot, a functax stencil’s apply, geoarray.to_pixel(transform, xy), geophysix.coriolis(lat). Lowest: Core, GeoNumerics and uppipekit_array.run_kernel. Lowest: Core (pipekit-array) and upgeoarray’s own verbs: crop, pad, read_window, stack. They move data and georeference together and never compute a new field. Lowest: GeoStack and up
▣ Modulefunctax plans, gridax grids, gaussx and kernellib operators, finitevolX operators, the models. Lowest: Core, GeoNumerics and upempty by design: a Module works on plain arrays, and an Operator puts the names onnever: a Module never holds or takes a carrier
→ OperatorJaxModelOp, DACycle, TrainingLoop, rollouts. Lowest: Core, GeoModels; never GeoNumericsISel, Reduce, ArgReduce, MapOver, KernelOp (pipekit-array). Lowest: Core (pipekit-array) and upgeoops, 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?

  1. Kind. Does it subclass pipekit.Operator? Then it is an Operator, whatever else it inherits; JaxOperator is also an eqx.Module and is still an Operator. Else, is it a class whose setup does work before a pure call? A Module. Else it is a function.

  2. 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 H\mat{H} 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

appa Sequential or Graph from a Hydra config
carrier down
→ Operator on carriersgeoops.SampleAt: _apply reads np.asarray(g) and g.grid
arrays and a CRS-free grid down
▣ Modulefunctax.BilinearPlan, fitted on the grid and the points
arrays down
ƒ functiongather and einx.dot with the stencil weights
arrays up
→ Operator on carrierswrap_like(result, g): a carrier again

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.

LayerNever importsBreaks todayFix
GeoNumericspipekit*, pyproj, rasterio, xarray, geoarray, geoops, xrops, every GeoStack packagenothing in src/; xarray only in the scripts and notebooks of finitevolX and spectraldiffxnone needed
Corepyproj, rasterio, xarray, geoarray, geoops, xrops, every GeoStack packagextremax.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.xarrayone per package, below

The fixes for Core, one per package:

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.

Conceptfunctax (Core)gridax (GeoNumerics)geoarray (GeoStack)
Affine raster gridAffineGrid(transform, shape): res, bounds, shift, crop(window), window(bounds), pixel centresnoneGrid = an AffineGrid + a CRS; stays hashable, keeps isclose and get_config / from_config
World to pixelto_pixel(grid, xy): fractional indices, the “find” step of a plannonereprojects the points with pyproj, then calls functax
Pixel coordinatespixel centres and corners of an AffineGridnonepixel_coords(g) reads the grid and calls functax
Pixel windowsnonenonePixelWindow stays: it is the read contract of RasterSource. read_window, write_window, crop, pad move the data and call AffineGrid.shift
Curvilinear and swath gridsnoneCurvilinearGrid(lat, lon), swath geometry: cell corners and areas, neighbours, nearest cellCurvilinearGrid and SwathGrid add the CRS of lat/lon; GeoSwath keeps per-scene lat/lon as leaves
Physical grid structurenoneArakawa staggering, metric arrays (dx, dy, areas), masks, vertical coordinates and remappingVertical, VerticalAxis: labels only
Areas on the Earthnonecell areas of any grid, on the ellipsoid from geophysixpixel_area (designed): reads the CRS, picks planar or ellipsoidal, calls gridax
Footprint in another CRSbounds in grid coordinatesnonefootprint: a Shapely polygon, densified and reprojected with pyproj
CRS, fill, attrs, dims, readers, georeader interopneverneveronly 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.

References
  1. 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
  2. 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