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.

One trace-gas source, from a scene to how often it leaks, rung by rung

GeoStack · background · the role ladder · worked example: trace gas

Abstract

The role ladder climbed on one trace-gas source, in the four stages of the sources application: retrieve the gas in one scene, segment the plume, quantify the emission rate, and then, from many scenes, estimate how often the facility emits. Methane is the instance; for NO₂ or CO₂ only the absorption spectrum, the conversion to mass and the detection curves change, and every rung keeps its piece. The first three stages come from one notebook that runs in a second on a synthetic scene whose answer is known; persistency comes from plumax.population. The ocean example climbs the same ladder on a different science, with the same sections in the same order.

Keywords:role laddertrace gasmethanematched filterplume segmentationemission ratepersistencypoint processrecipe

The running example

The problem: a cell with no address

One notebook cell, radiance in, emission rate out

read the scenefit mean and covariancebuild the methane signaturefilter every pixelthreshold at 3σα^3\sigma_{\hat\alpha}drop small blobspixel area ×\times mass ×\times wind

Reuseanother script needs σα^\sigma_{\hat\alpha}, the noiseCopy the cell.

Swaptry a different covariance estimatorEdit the middle of the cell.

Savererun last month’s settings exactlyWhich version of the cell?

The job is right and the code works. What is missing is any answer to “where does each piece belong?”, so every piece belongs to this one cell.

# Shapes: B = 40 bands; R × C = 96 × 96 pixels; P = R C pixels
spectra = radiance.reshape(40, -1).T
mean = spectra.mean(axis=0)
covariance = sklearn.covariance.LedoitWolf().fit(spectra).covariance_
target = -air_mass * absorption * mean
direction = np.linalg.solve(covariance, target)
enhancement = np.tensordot(direction, radiance - mean[:, None, None], axes=1)
enhancement /= target @ direction
noise = (target @ direction) ** -0.5
labels, count = scipy.ndimage.label(enhancement > 3 * noise)
...
emission = 3.5 * 6.56e-7 * 3600 * enhancement[plume].sum() / length

Every line is fine. The trouble is structural: the covariance estimator, the filter, the threshold rule and the settings are fused, so none can be used, replaced or recorded alone.

And the cell stops at one scene. The next question, how often does this facility emit and how much does the satellite miss, needs every scene, including the overpasses where nothing was seen. It cannot live in the cell at all. The rest of the page gives every piece of all four stages a rung.

The ladder at a glance

Each rung with its grammar, one piece from the scene, and how it scales. The dashed line is the jit boundary.

rung · grammar · running example

how it scales

orchestration · not a rungevery new scene; every facility when its catalogue grows

Airflow, daskscenes, facilities

⑥ recipe · paragraphplume_recipe (per scene), persistency_recipe

two units of work

⑤ step · sentence + settingsMethaneRetrieval(…), …, Persistency(…)

one carrier per call

carriers above · arrays belowjit boundary: unwrap πcfg\pi_\mathrm{cfg}, compute, rewrap ιcfg\iota_\mathrm{cfg}

④ algorithm · sentencematched_filter, …, fit_poisson_rate

vectorised over pixels

③ model · noun phraseBackground (μy,Σy)(\gvect{\mu}_y, \gmat{\Sigma}_y), InstrumentPOD

state built once

② strategy · adverbLedoitWolf, SigmaThreshold, LognormalMark

settings only: swappable

① primitive · verbtarget_signature, pixel_area, compute_E_Pd

NumPy, SciPy

⓪ structure · nounradiance (band, y, x), Σy\gmat{\Sigma}_y, EmissionCatalog

the band axis

apply context

setup · beside the ladderBackground.fit (spectra), load_pod_calibrations(…)builds ③’s state once: per scene, per campaign

outside the trace

Colour is the execution context: blue outside the trace, teal inside, amber built once. The dashed arrow is setup building the model’s state.

The code below is NumPy, SciPy and scikit-learn, so that the notebook runs without JAX; its strategies and model are plain dataclasses where the stack uses equinox Modules, and Scene stands in for GeoArray. The jit boundary is where it would fall: everything below it takes arrays and numbers only.

The persistency pieces are from plumax.population at 290f31f, the commit the persistency explainer uses, which is newer than the submodule pin. They are sketched with the same markers: today for a name that ships, today* where its arguments are sketched, proposed for a name that does not exist yet.

⓪ Structure: the noun

What the verbs act on. It does nothing on its own; it records what something is. Here the nouns are the radiance cube, the covariance, and the scene that carries the cube with its pixel size and attributes.

radiance(band, y, x)μW cm−2 sr−1 nm−1\mathrm{\mu W\ cm^{-2}\ sr^{-1}\ nm^{-1}}

Σy\gmat{\Sigma}_yremembers: symmetric, positive definite

60 m60\ \mathrm{m}attrs

Sceneremembers: pixel size and what was measured

Three nouns of the scene, each with the one fact it remembers.

Kinda Module, or a third-party array
How to tellit is passed to things and does nothing on its own
In the jobthe radiance cube (band, y, x); Σ_y (band, band); the Scene with its pixel size and attributes; for persistency, the event catalogue and the overpass windows
Goes wrong whenthe scene computes its own enhancement on construction (a model in disguise)
# Shapes: B = 40 bands; R × C = 96 × 96 pixels; P = R C pixels

# user
@dataclasses.dataclass(frozen=True)
class Scene:
    """A small carrier: the numbers, the pixel size and the attributes."""

    data: np.ndarray
    pixel_m: float
    attrs: dict

Persistency. Its nouns are the catalogue of detected events, each with a time, a place and a posterior on its rate, and the list of overpass windows, which records the times the instrument looked and saw nothing.

import plumax.population as pop

# Shapes: N_det detections; N_window overpass windows

# today (plumax)
# one event per detection: time, place, rate and its spread
catalog = pop.EmissionCatalog.from_events(events)              # → N_det events
# user
# the start of every overpass window, detection or not
window_starts = np.asarray(overpass_times)                      # (N_window,)

① Primitive: the verb

One call on a noun, a plain function of arrays and numbers. It knows nothing of methane plumes or satellites: the radiance change per unit of methane, the area of a pixel, the connected pieces of a mask.

μy,k\gvect{\mu}_y, \vect{k}(band,) each

target_signature(μy,k,AMF)(\gvect{\mu}_y, \vect{k}, \mathrm{AMF})t=−AMF(k⊙μy)\vect{t} = -\mathrm{AMF} (\vect{k} \odot \gvect{\mu}_y)

t\vect{t}(band,)

no state · O(band)\mathcal{O}(\text{band}) · knows radiance and absorption, nothing about plumes

target_signature turns the mean spectrum and the absorption into the radiance change per ppm m of methane.

Kinda function: pure, arrays in and out, parameters on every call
How to tellit acts on a noun and takes no model
In the jobtarget_signature, pixel_area, large_components (with scipy.ndimage.label inside); for persistency, compute_E_Pd
Goes wrong whena flag switches between two ways of computing it: that flag is an adverb waiting to be named
# user
def target_signature(
    mean: Float[np.ndarray, " band"],
    absorption: Float[np.ndarray, " band"],
    air_mass: float,
) -> Float[np.ndarray, " band"]:
    """Radiance change per ppm m of methane: t = −AMF (k ⊙ μ_y)."""
    # t = −AMF (k ⊙ μ_y)
    target = -air_mass * absorption * mean                    # (B,), (B,) → (B,)
    return target

# user
def pixel_area(pixel_m: float) -> float:
    """Area of one square pixel in m²: a = Δs²."""
    # a = Δs²
    area = pixel_m * pixel_m                                  # → ()
    return area

# user
def large_components(
    mask: Bool[np.ndarray, "y x"], min_pixels: int
) -> Bool[np.ndarray, "y x"]:
    """Keep connected pieces of at least N_min pixels: b_n = c_n 1[|K(n)| ≥ N_min]."""
    # K(n): the connected piece that holds pixel n
    labels, count = scipy.ndimage.label(mask)                 # (R, C) → (R, C)
    sizes = np.bincount(labels.ravel(), minlength=count + 1)  # (R, C) → (K + 1,)
    keep = sizes >= min_pixels                                # (K + 1,) → (K + 1,)
    # label 0 is the background, never a plume
    keep[0] = False
    # b_n = c_n 1[|K(n)| ≥ N_min]
    plume = keep[labels]                                      # (R, C) → (R, C)
    return plume

Persistency. Its verb is the mean probability of detection: how likely the instrument is to see an event, averaged over the event sizes Q∈R≥0Q \in \mathbb{R}_{\ge 0} with density p(Q)p(Q), where Pd(Q)∈[0,1]P_d(Q) \in [0, 1],

Peff=Ep(Q)[Pd(Q)]=∫0∞Pd(Q)p(Q)dQP_\text{eff} = \mathbb{E}_{p(Q)}[P_d(Q)] = \int_0^\infty P_d(Q) p(Q) \mathrm{d}Q
# today* (plumax)
# P_eff = 𝔼_p(Q)[P_d(Q)] = ∫₀^∞ P_d(Q) p(Q) dQ, by quadrature in log Q
mean_detection = pop.compute_E_Pd(                               # → ()
    mu=np.log(1500.0), sigma=1.1, Q_50=500.0, k=3.0
)

compute_E_Pd uses a logistic curve in QQ; with the log-logistic curve of the running example, Pd(Q)=1/(1+(Q50/Q)γdet)P_d(Q) = 1 / (1 + (Q_{50} / Q)^{\gamma_\text{det}}), the same integral gives PeffP_\text{eff} = 0.811.

② Strategy: the adverb

How something is done: settings only, never data. Two strategies that answer the same question are interchangeable, which is the point. Here the families are the covariance estimator and the threshold rule.

Background.fit (…, estimator=?)Σ^y=\hat{\gmat{\Sigma}}_y = estimator(spectra)

LedoitWolfshrink towards σˉ2I\bar{\sigma}^2 \mat{I}Q^=5.683 kg s−1\hat{Q} = 5.683\ \mathrm{kg\ s^{-1}}

SampleCovariancethe plain sample Σy\gmat{\Sigma}_yQ^=5.678 kg s−1\hat{Q} = 5.678\ \mathrm{kg\ s^{-1}}

Same algorithm, same statement of the filter; the estimator changes how Σ_y is estimated, and the rate moves in the third decimal.

Kinda Module whose fields are settings
How to tellit holds no data from the scene, and a sibling can replace it
In the jobLedoitWolf and SampleCovariance for Σ_y; SigmaThreshold(k=3) for candidate pixels; for persistency, the size distribution (LognormalMark or a sibling) and the intensity family ("constant", diurnal, …)
Goes wrong whenit keeps the fitted Σ_y (now it is a model), or the estimator is a string switch inside the filter, so nobody knows it is swappable
# user
@dataclasses.dataclass(frozen=True)
class LedoitWolf:
    """How to estimate Σ_y: shrink the sample covariance towards a scaled identity."""

    def __call__(
        self, spectra: Float[np.ndarray, "pixel band"]
    ) -> Float[np.ndarray, "band band"]:
        estimator = sklearn.covariance.LedoitWolf()
        fitted = estimator.fit(spectra)
        return fitted.covariance_                             # (P, B) → (B, B)

# user
@dataclasses.dataclass(frozen=True)
class SampleCovariance:
    """How to estimate Σ_y: the plain sample covariance."""

    def __call__(
        self, spectra: Float[np.ndarray, "pixel band"]
    ) -> Float[np.ndarray, "band band"]:
        return np.cov(spectra, rowvar=False)                  # (P, B) → (B, B)

# user
@dataclasses.dataclass(frozen=True)
class SigmaThreshold:
    """How to pick candidate pixels: above k noise levels."""

    k: float = 3.0

    def __call__(
        self, values: Float[np.ndarray, "y x"], noise: float
    ) -> Bool[np.ndarray, "y x"]:
        # c_n = 1[α̂_n > k σ_α̂]
        return values > self.k * noise                        # (R, C) → (R, C)

Persistency. Its adverbs say which family the event sizes follow and how the event rate varies in time. A mark holds only the scales of its priors; its parameters θ are passed at each call, so LognormalMark and LognormalParetoMark are siblings in the same slot.

# today (plumax)
# p(Q; θ): lognormal event sizes; θ = {μ_Q, σ_Q} is passed at the call
mark = pop.LognormalMark()
# today (plumax)
# a sibling with a Pareto tail, for a few very large events
heavy_tail = pop.LognormalParetoMark()

③ Model: the noun phrase

A noun with meaning and fitted state: not “a matrix” but “this scene’s background”, with its mean and covariance and the things only it can answer (solve with Σ_y, the noise of a filter built on it). It exists so that two algorithms can share the state.

setupBackground.fit

Backgroundθ\gvect{\theta}: estimator = LWψ\gvect{\psi}: μy\gvect{\mu}_y (band,)ψ\gvect{\psi}: Σy\gmat{\Sigma}_y (band, band)

solve: Σy−1t\gmat{\Sigma}_y^{-1}\vect{t}matched_filter

noise: σα^\sigma_{\hat\alpha}segment

fitted once per scene, read by the filter and by the threshold

Fitted once per scene, read by the filter and by the threshold.

Kinda Module: the fit may do untraceable work; the calls afterwards are pure
How to tellit means something (“this scene’s background”) and remembers something between calls
In the jobBackground with μ_y (band,) and Σ_y (band, band); for persistency, one InstrumentPOD per instrument
Goes wrong whenthe filter refits its own background on every call: then the segmentation cannot read the same σα^\sigma_{\hat\alpha}, and the two stages drift apart
# user
@dataclasses.dataclass(frozen=True)
class Background:
    """What was fitted: the scene's mean spectrum μ_y and covariance Σ_y."""

    mean: np.ndarray
    covariance: np.ndarray

    @classmethod
    def fit(
        cls,
        spectra: Float[np.ndarray, "pixel band"],
        estimator: LedoitWolf | SampleCovariance = LedoitWolf(),
    ) -> Background:
        # μ_y,b = (1 / P) ∑_n y_nb
        mean = einx.mean("[pixel] band", spectra)             # (P, B) → (B,)
        # Σ_y, by the chosen strategy
        covariance = estimator(spectra)                       # (P, B) → (B, B)
        return cls(mean, covariance)

    def solve(self, vector: Float[np.ndarray, " band"]) -> Float[np.ndarray, " band"]:
        # s = Σ_y⁻¹ t
        return np.linalg.solve(self.covariance, vector)       # (B,) → (B,)

    def noise(self, target: Float[np.ndarray, " band"]) -> float:
        # σ_α̂ = (tᵀ Σ_y⁻¹ t)^(−1/2)
        direction = self.solve(target)                        # (B,) → (B,)
        precision = einx.dot("band, band ->", target, direction)  # → ()
        return float(precision) ** -0.5

Persistency. Its noun phrase is each instrument’s detection curve: not “a sigmoid” but “this instrument’s probability of seeing an event of size QQ”, with the midpoint and slope from its published calibration and how far to trust them. Setup reads it from a table once; the rate fit and the missed-mass estimate both use it.

# today (plumax)
# P_d(Q) = 1 / (1 + (Q₅₀ / Q)^γ_det), with a prior on Q₅₀ of 0.2 on the log scale
pod = pop.InstrumentPOD(
    name="hyperspectral", model="log_logistic", q50=500.0, q50_std=0.2, slope=3.0
)

④ Algorithm: the sentence

A method over models, written as a function: do this, to that, in this way. It takes the model as an argument, so it never refits anything. The matched filter, with background mean μy\gvect{\mu}_y, covariance Σy\gmat{\Sigma}_y, target signature t\vect{t} and the radiance yn\vect{y}_n of pixel nn:

s=Σy−1t\vect{s} = \gmat{\Sigma}_y^{-1} \vect{t}
α^n=s⊤(yn−μy)t⊤s\hat{\alpha}_n = \frac{\vect{s}^\top (\vect{y}_n - \gvect{\mu}_y)}{\vect{t}^\top \vect{s}}
σα^=(t⊤s)−1/2\sigma_{\hat\alpha} = (\vect{t}^\top \vect{s})^{-1/2}

Where

SymbolMeaningShapeUnit
yn,μy\vect{y}_n, \gvect{\mu}_yradiance of pixel nn; background mean(band,)µW cm⁻² sr⁻¹ nm⁻¹
Σy\gmat{\Sigma}_ybackground covariance(band, band)(µW cm⁻² sr⁻¹ nm⁻¹)²
t,s\vect{t}, \vect{s}target signature; filter direction(band,)radiance per ppm m; its inverse-weighted form
α^n,σα^\hat{\alpha}_n, \sigma_{\hat\alpha}methane enhancement of pixel nn; its noise level()ppm m

⓪ radiance Y\mat{Y}

① target t\vect{t}

③ Background μy,Σy\gvect{\mu}_y, \gmat{\Sigma}_y

matched_filter④ holds nothing

α^\hat{\gvect{\alpha}}(y, x) ppm m\mathrm{ppm\ m}

② enters through ③: the estimator chose Σy\gmat{\Sigma}_y, the filter only uses it

Every input of matched_filter sits on a lower rung; the algorithm itself holds nothing.

Kinda function
How to tellit takes a model and holds nothing; a primitive acts on a noun, an algorithm takes a model (pixel_area is ①, matched_filter is ④)
In the jobmatched_filter, segment, emission_rate; for persistency, fit_poisson_rate, or the full thinned marked Poisson process (tmtpp_iw_model)
Goes wrong whenit fits its own background inside, or grows a keyword flag for the estimator
# user
def matched_filter(
    radiance: Float[np.ndarray, "band y x"],
    background: Background,
    target: Float[np.ndarray, " band"],
) -> Float[np.ndarray, "y x"]:
    """Methane enhancement per pixel: α̂_n = sᵀ (y_n − μ_y) / (tᵀ s), s = Σ_y⁻¹ t."""
    # s = Σ_y⁻¹ t
    direction = background.solve(target)                      # (B,) → (B,)
    # tᵀ s
    normalisation = einx.dot("band, band ->", target, direction)  # → ()
    # r_n = y_n − μ_y
    residual = einx.subtract(                                 # (B, R, C) → (B, R, C)
        "band y x, band -> band y x", radiance, background.mean
    )
    # sᵀ r_n
    projection = einx.dot("band, band y x -> y x", direction, residual)  # → (R, C)
    # α̂_n = sᵀ r_n / (tᵀ s)
    enhancement = projection / normalisation                  # (R, C) → (R, C)
    return enhancement

# user
def segment(
    values: Float[np.ndarray, "y x"],
    noise: float,
    rule: SigmaThreshold,
    min_pixels: int,
) -> Bool[np.ndarray, "y x"]:
    """Plume mask: candidates by the rule, then only the large pieces."""
    # c_n = 1[α̂_n > k σ_α̂]
    candidates = rule(values, noise)                          # (R, C) → (R, C)
    # b_n = c_n 1[|K(n)| ≥ N_min]
    plume = large_components(candidates, min_pixels)          # (R, C) → (R, C)
    return plume

# user
def emission_rate(
    values: Float[np.ndarray, "y x"],
    plume: Bool[np.ndarray, "y x"],
    area: float,
    wind: float,
    kappa: float,
) -> float:
    """Emission rate from the plume's mass and the wind: Q = U κ a ∑ b α̂ / L."""
    # L = (a ∑_n b_n)^(1/2)
    length = (area * np.count_nonzero(plume)) ** 0.5          # → ()
    # ∑_n b_n α̂_n
    total = float(np.sum(values, where=plume))                # (R, C) → ()
    # Q = U κ a ∑_n b_n α̂_n / L
    rate = wind * kappa * area * total / length               # → ()
    return rate

Persistency. Its sentence counts the detections against the time the instrument looked, discounted by how likely it was to see an event. With a constant rate, sizes from the mark and a Gamma(a0,b0)\mathrm{Gamma}(a_0, b_0) with a0,b0∈R>0a_0, b_0 \in \mathbb{R}_{>0} prior, the posterior on the rate is conjugate (persistency explainer):

ρ∣Ndet∼Gamma(a0+Ndet,b0+Nwindow∣w∣Peff)\rho \mid N_\text{det} \sim \mathrm{Gamma}(a_0 + N_\text{det}, b_0 + N_\text{window} \vert w \vert P_\text{eff})
# today* (plumax)
# ρ | N_det ~ Gamma(a₀ + N_det, b₀ + N_window |w| P_eff): the effective exposure is the time looked × P_eff
rate = pop.fit_poisson_rate(                                     # Gamma(25, 12.26)
    catalog,
    area=1.0,
    # N_window |w| P_eff, with the log-logistic P_eff = 0.811 of the running example
    duration=120 * 0.125 * 0.811,
    prior_shape=1.0,
    prior_rate=0.1,
)

With 24 detections this gives ρ = 2.04 ± 0.41 events per day, around a true 2. When the rate varies through the day, or the sizes have to be learned with it, the same sentence is the full thinned marked Poisson process, sampled with NUTS (tmtpp_iw_model); the persistency explainer derives both.

⑤ Step: a sentence with its own settings

One transformation of real data, ready to chain. It has three parts: unwrap the carrier into arrays, call down the ladder, wrap the result as a carrier again. Its constructor arguments are its settings, and they are plain values, so they can be written to JSON.

⑤ MethaneRetrieval

cfg\mathrm{cfg} ={“estimator”: “ledoit_wolf”}

Sceneradiance

πcfg\pi_\mathrm{cfg}

arrays onlyfit · signature · filterrungs ⓪ to ④

ιcfg\iota_\mathrm{cfg}

Sceneα^\hat{\gvect{\alpha}}, with σα^\sigma_{\hat\alpha}

absorption and air mass come from the scene’s attrs, not from cfg\mathrm{cfg}

The config never reaches the algorithm: cfg→θ\mathrm{cfg} \to \gvect{\theta} happens in the step, as in (1).

Kindan Operator; its config round-trips through JSON
How to tellit carries its own settings and runs alone in a notebook or inside a recipe
In the jobMethaneRetrieval, PlumeSegmentation, EmissionRate; for persistency, Persistency (proposed)
Goes wrong whenthe second input of EmissionRate (the mask) is a constructor field: then a graph cannot wire it
ESTIMATORS = {"ledoit_wolf": LedoitWolf, "sample": SampleCovariance}

# user
class MethaneRetrieval(pipekit_ops.Operator):
    """Step: radiance scene → enhancement scene, with its noise in the attrs."""

    def __init__(self, *, estimator: str = "ledoit_wolf") -> None:
        self.estimator = estimator

    def _apply(self, scene: Scene) -> Scene:
        # --- unwrap: arrays and numbers out of the carrier ---
        spectra = einx.id("band y x -> (y x) band", scene.data)   # (B, R, C) → (P, B)
        absorption = scene.attrs["absorption"]
        air_mass = scene.attrs["air_mass"]
        # --- compute: ② strategy, ③ model, ① primitive, ④ algorithm ---
        strategy = ESTIMATORS[self.estimator]()
        background = Background.fit(spectra, strategy)
        target = target_signature(background.mean, absorption, air_mass)
        values = matched_filter(scene.data, background, target)   # → (R, C)
        # --- rewrap: a carrier again, σ_α̂ carried for the next step ---
        attrs = {"noise_ppm_m": background.noise(target)}
        return Scene(values, scene.pixel_m, attrs)

# user
class PlumeSegmentation(pipekit_ops.Operator):
    """Step: enhancement scene → plume mask."""

    def __init__(self, *, k: float = 3.0, min_pixels: int = 20) -> None:
        self.k = k
        self.min_pixels = min_pixels

    def _apply(self, enhancement: Scene) -> Scene:
        noise = enhancement.attrs["noise_ppm_m"]
        rule = SigmaThreshold(self.k)
        plume = segment(enhancement.data, noise, rule, self.min_pixels)
        return Scene(plume, enhancement.pixel_m, {})

# user
class EmissionRate(pipekit_ops.Operator):
    """Step: enhancement and mask → emission rate in kg s⁻¹."""

    def __init__(self, *, wind_m_s: float = 3.5, kappa: float = 6.56e-7) -> None:
        self.wind_m_s = wind_m_s
        self.kappa = kappa

    def _apply(self, enhancement: Scene, plume: Scene) -> float:
        area = pixel_area(enhancement.pixel_m)
        return emission_rate(
            enhancement.data, plume.data, area, self.wind_m_s, self.kappa
        )

Persistency. No step exists for it yet. Sketched, it unwraps the catalogue and the windows, calls the rate fit, and returns a record of the rate and the metrics built on it. The windows are a call argument, not a field, so a graph can wire them.

# proposed (plumax population step)
class Persistency(pipekit_ops.Operator):
    """Step: event catalogue and overpass windows → rate posterior and metrics."""

    def __init__(self, *, mark: str = "lognormal", window_days: float = 0.125) -> None:
        self.mark = mark
        self.window_days = window_days

    def _apply(self, catalog, window_starts, pods) -> dict:
        # --- unwrap: counts and exposure out of the carriers ---
        # --- compute: ① P_eff from ③ the pods and ② the mark, then ④ the rate fit ---
        # --- rewrap: ρ, its interval, the wait time and the missed mass ---
        ...

⑥ Recipe: the paragraph

Steps in order, making one job from source to product. It contains no computation of its own. Because it holds only steps and their settings, it exists in two forms: code, and data.

plume_recipe · per scene

scene (input)

MethaneRetrieval

α^\hat{\gvect{\alpha}}α^,σα^\hat{\gvect{\alpha}}, \sigma_{\hat\alpha}

PlumeSegmentation

mask

EmissionRate

QQ and its posterior

one event per detection; an empty overpass otherwise

EmissionCatalog of the facility

persistency_recipe · per facility

catalogue

overpass windows

pods (setup)

Persistency

ρ\rho, its interval, the wait time, the missed mass

two graphs: the first runs once per scene, the second once per facility

Two graphs. plume_recipe is a graph, not a chain, because the enhancement feeds two steps; persistency_recipe runs once per facility on what many scenes wrote.

Kindan Operator; as data, pipekit_ops.dumps / loads
How to tellit holds steps and settings only, and can be saved without any data
In the jobplume_recipe: retrieval, segmentation and quantification in one graph, per scene; persistency_recipe, per facility
Goes wrong whena threshold is computed between two steps in the notebook instead of inside a step, so the saved recipe cannot reproduce it
# user
def plume_recipe(
    *, k: float = 3.0, estimator: str = "ledoit_wolf"
) -> pipekit_ops.Graph:
    """Recipe: retrieval, segmentation and quantification, wired into one job."""
    # today (pipekit)
    scene_in = pipekit_ops.Input("scene")
    enhancement = MethaneRetrieval(estimator=estimator)(scene_in)
    plume = PlumeSegmentation(k=k)(enhancement)
    emission = EmissionRate()(enhancement, plume)
    # today (pipekit)
    return pipekit_ops.Graph(
        inputs={"scene": scene_in}, outputs={"emission": emission}
    )

Persistency. It is a second recipe, not a fourth step in the first, because its input is not a scene: it is the catalogue that many runs of plume_recipe have filled, and the list of every overpass.

# proposed (plumax population step)
def persistency_recipe(*, mark: str = "lognormal") -> pipekit_ops.Graph:
    """Recipe: how often one facility emits, from its catalogue and overpasses."""
    # today (pipekit)
    catalog_in = pipekit_ops.Input("catalog")
    windows_in = pipekit_ops.Input("windows")
    pods_in = pipekit_ops.Input("pods")
    summary = Persistency(mark=mark)(catalog_in, windows_in, pods_in)
    # today (pipekit)
    return pipekit_ops.Graph(
        inputs={"catalog": catalog_in, "windows": windows_in, "pods": pods_in},
        outputs={"persistency": summary},
    )

Setup: beside the ladder

Setup builds state before anything is computed, outside jit. For one scene that is the background fit, plus the two attributes the target signature needs. For persistency it is each instrument’s detection curve, read once from the campaign’s calibration table.

setup · per sceneNumPy, scikit-learnfloat64, concrete

③ Background μy,Σy\gvect{\mu}_y, \gmat{\Sigma}_y (LedoitWolf)

attrs: absorption k\vect{k}, per band

attrs: air mass AMF\mathrm{AMF}, from geometry

setup · per campaigna calibration table

③ InstrumentPOD per instrument (Q50,γdet)(Q_{50}, \gamma_\text{det})

built before anything runs · shared by two stages · never refit under a trace

Built before anything runs, shared by two stages, never refit under a trace.

In the notebook the fit runs inside MethaneRetrieval._apply, to keep the file short, and the step hands σα^\sigma_{\hat\alpha} to the next step through the scene’s attributes. In the stack the fit is setup: Background.fit runs once per scene, outside the trace, and the fitted Background is passed in, as the ocean example does with its observation plan. The roles do not change; only where the call sits does.

# today (plumax)
# each instrument's published (Q₅₀, γ_det), read once; the table is the campaign's record
pods = pop.load_pod_calibrations("pod_calibrations.yaml")       # → K instruments

Orchestration: above the ladder

Orchestration runs two units of work. Per scene, plume_recipe runs on every new EMIT scene; a failed scene is retried; each detection is written to the facility’s catalogue as an event, and every overpass, empty or not, to its list of windows. Per facility, persistency_recipe reruns whenever its catalogue changes.

per scene · plume_recipe

scene 1

scene 2

retry

scene 4

scene 5

each adds an event, or an empty overpass

the facility’s catalogue

when it changes

per facility · persistency_recipe

fit how often it emits

a failed scene is retried; every result is stored with the config that made it

Two recipes, two units of work: a scene, then a facility.

The catalogue is the hand-off between the two. Each quantified plume becomes one event:

# today* (plumax)
# one event per detection, from the quantification posterior
event = pop.event_from_posterior(
    posterior, x=source_x, y=source_y, time=overpass_time, tier="II", instrument="EMIT"
)

In the notebook EmissionRate returns a number, not a posterior; the quantification explainer builds the posterior this call takes.

Every piece of the scene on its rung

retrieval

segmentation

quantification

persistency

⑥ recipe

plume_recipe (per scene)

persistency_recipe

⑤ step

MethaneRetrieval

PlumeSegmentation

EmissionRate

Persistency

④ algorithm

matched_filter

segment

emission_rate

fit_poisson_rate

③ model

Background

σα^\sigma_{\hat\alpha}: fitted once, used twice

InstrumentPOD

② strategy

LedoitWolf

SigmaThreshold

LognormalMark

① primitive

target_signature

large_components

pixel_area

compute_E_Pd

⓪ structure

Scene(the carrier) · arrays

EmissionCatalog

setup

Background.fit

load_pod_calibrations

Blue outside the trace, teal inside, amber built once; the dashed line is the jit boundary.

Every piece of the four stages on its rung. Columns are the stages; rows are the rungs. The amber arrows are what the cell could not do: the background is fitted once and its noise level sets the segmentation threshold, and each instrument’s detection curve is loaded once and read by the rate fit.

# user
recipe = plume_recipe()
result = recipe(scene=scene)                    # → {"emission": Q}
# swap one strategy; nothing else changes
swapped = plume_recipe(estimator="sample")(scene=scene)
# today (pipekit)
# the recipe as data: class names and settings, never arrays
recipe_json = pipekit_ops.dumps(recipe)
# today (pipekit)
loaded = pipekit_ops.loads(recipe_json)
again = loaded(scene=scene)                     # the same Q

What the ladder bought, against the three requests of the problem and the question the cell could not hold:

RequestHowMeasured
ReuseBackground is fitted once; the filter uses its solve and segmentation uses its noisemask: 197 of 197 true pixels
Swapestimator="sample" picks another ② strategy; no other line changesQ^\hat{Q} 5.683 → 5.678 kg s⁻¹
Savedumps writes the recipe as JSON; loads rebuilds itQ^\hat{Q} 5.683 kg s⁻¹, identical
Checkthe truth is known for the synthetic sceneQ^\hat{Q} 5.68 against 5.80 kg s⁻¹
Ask how oftenpersistency_recipe reads the catalogue every scene adds toρ 2.04 ± 0.41 day⁻¹ against a true 2 (illustrative)

The recipe as data is short, because everything below ⑤ is code and only settings are saved. These are the three operators of the saved graph; the graph also records which output feeds which input:

[
  {"class": "MethaneRetrieval", "config": {"estimator": "ledoit_wolf"}},
  {"class": "PlumeSegmentation", "config": {"k": 3.0, "min_pixels": 20}},
  {"class": "EmissionRate", "config": {"kappa": 6.56e-07, "wind_m_s": 3.5}}
]

The matched filter in seven moves

The explaining recipe applied to the scene.

  1. Start from the sentence. Score each pixel by how much its radiance looks like the methane signature, measured against the scene’s own background.

  2. Name the nouns. The radiance cube (band, y, x) in µW cm⁻² sr⁻¹ nm⁻¹; the covariance Σ_y (band, band); the scene with its 60 m pixels.

  3. Name the verbs. target_signature gives t=−AMF(k⊙μy)\vect{t} = -\mathrm{AMF} (\vect{k} \odot \gvect{\mu}_y); np.linalg.solve gives Σy−1t\gmat{\Sigma}_y^{-1}\vect{t}.

  4. Name the adverbs. The covariance estimator (Ledoit–Wolf or the sample covariance); swapping it changes how Σ_y is estimated, not the statement of the filter.

  5. Name the noun phrases. The Background, whose state μ_y and Σ_y is fitted once per scene and read by the filter and the threshold.

  6. Return to the sentence. Write the three equations of the algorithm using only the pieces above. Nothing new appears, so nothing is missing.

  7. Go up only if the reader works there. For a geoscientist: MethaneRetrieval is the step that unwraps the scene, and plume_recipe the graph that retrieves, segments and quantifies. For an ML reader, stop at move 6.

The same seven moves explain the persistency fit. The sentence: count the detections against the time the instrument looked, discounted by how likely it was to see an event. The nouns: the catalogue and the overpass windows. The verb: PeffP_\text{eff}. The adverbs: the size distribution and the intensity family. The noun phrase: each instrument’s detection curve. Back to the sentence: eq. (5). Up: the Persistency step and its recipe.