Skip to content

Observations

Satellite L2 methane products as coupled.Instruments on a LocalFrame, with the observed column-mass enhancement fuse_observations takes: TROPOMI, EMIT and GHGSat, read through xrproducts. Tier 0. Needs pip install 'plumax[io]'.

obs

Satellite L2 observations for the coupled inversion (Tier 0 prerequisites).

Loaders that turn one L2 methane product into a :class:~plumax.coupled.Instrument (receptors on a :class:~plumax.met.LocalFrame, a scalar averaging kernel, the retrieval variance) plus the observed column-mass enhancement :func:~plumax.coupled.fuse_observations takes:

  • :func:load_tropomi_l2 — TROPOMI CH₄ (bias-corrected XCH₄, column averaging kernel, QA screening).
  • :func:load_emit_l2b — EMIT L2B CH₄ enhancement (ppm·m).
  • :func:load_ghgsat_l2 — GHGSat per-plume XCH₄.

For the image fit, one plume rather than a whole scene:

  • :func:load_emit_plume_complex — one catalogued plume of an EMIT scene as a :class:PlumeScene: the window around its outline with the sensitivity as the averaging kernel, a per-pixel noise, the quality mask, the pseudo-origin and a starting direction.
  • :func:matched_filter_scene — the same observation from radtrax's score, noise and sensitivity maps.

The files are read with xrproducts's openers; needs the io extra.

ColumnObservation

Bases: Module

One product's instrument and its observed enhancement.

Attributes:

Name Type Description
instrument Instrument

Receptors, scalar averaging kernel and retrieval variance, ready for CoupledForward.

enhancement Float[Array, ' pixel']

Observed column-mass enhancement ΔΩ [kg m⁻²], aligned with instrument.receptors.

time datetime64

Observation timestamp (UTC); NaT when the file has none.

PlumeScene

Bases: Module

One plume: its observation, its outline and where the fit starts.

yₙ = Aₙ ΔΩₙ + εₙ, εₙ ~ 𝒩(0, σₙ²), with yₙ, Aₙ, σₙ² and the mask ωₙ held by observation.

Attributes:

Name Type Description
observation ColumnObservation

Instrument (receptors, Aₙ, σₙ², ωₙ) and enhancement yₙ.

origin Float[Array, ' axis']

Pseudo-origin s₀ in the local frame [m].

outline Float[Array, 'vertex axis']

Plume outline in the local frame [m], closed.

in_plume Bool[Array, ' pixel']

Whether each kept pixel lies inside the outline.

direction Float[Array, '']

Starting direction φ₀ [rad], origin to plume centroid, counter-clockwise from the frame's x axis.

pixel_index Int[Array, 'pixel 2']

(row, col) of each kept pixel in the window, to put the pixels back on the image.

plume_id str

Identifier of the plume in its product.

pixel_size float

Pixel side g [m].

window tuple[int, int, int, int]

(row_start, row_stop, col_start, col_stop) of the window in the scene's raster.

window_shape property

window_shape: tuple[int, int]

(N_row, N_col) of the window.

instrument property

instrument: Instrument

The instrument of the observation.

enhancement property

enhancement: Float[Array, ' pixel']

Observed column-mass enhancement yₙ [kg m⁻²].

load_emit_l2b

load_emit_l2b(path: str | Path, *, frame: LocalFrame, bbox: BBox | None = None, glt_path: str | Path | None = None, retrieval_sigma_ppm_m: float | None = None, pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD, clock: TimeAxis | None = None, name: str = 'EMIT') -> ColumnObservation

An EMIT L2B CH₄ enhancement scene as an instrument and its enhancement.

ΔΩ = E · 10⁻⁶ · (p / (k_B T)) · M / N_A, A = 1.

The enhancement E (ppm·m) is already above background. Its uncertainty comes from ch4_uncertainty when the file has it, else from retrieval_sigma_ppm_m.

Parameters:

Name Type Description Default
path str | Path

NetCDF raster (see :func:xrproducts.open_emit_ch4_l2b).

required
frame LocalFrame

Analysis frame.

required
bbox BBox | None

Optional (lon_min, lat_min, lon_max, lat_max) crop.

None
glt_path str | Path | None

Optional geometric lookup table for orthorectification.

None
retrieval_sigma_ppm_m float | None

Per-pixel 1-σ [ppm m] for files without ch4_uncertainty.

None
pressure_pa float

Near-surface pressure p for the ppm·m conversion.

P_STANDARD
temperature_k float

Near-surface temperature T for the ppm·m conversion.

T_STANDARD
clock TimeAxis | None

Sets Instrument.observation_time.

None
name str

Instrument name.

'EMIT'

Returns:

Name Type Description
The ColumnObservation

class:ColumnObservation.

Raises:

Type Description
MissingExtraError

If the io extra is not installed.

MissingVariableError

If neither an uncertainty field nor retrieval_sigma_ppm_m is available.

ScreeningError

If no pixel survives the screening.

Source code in src/plumax/obs/_src/ingest.py
def load_emit_l2b(
    path: str | Path,
    *,
    frame: LocalFrame,
    bbox: BBox | None = None,
    glt_path: str | Path | None = None,
    retrieval_sigma_ppm_m: float | None = None,
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
    clock: TimeAxis | None = None,
    name: str = "EMIT",
) -> ColumnObservation:
    """An EMIT L2B CH₄ enhancement scene as an instrument and its enhancement.

    ΔΩ = E · 10⁻⁶ · (p / (k_B T)) · M / N_A,  A = 1.

    The enhancement E (ppm·m) is already above background. Its uncertainty
    comes from ``ch4_uncertainty`` when the file has it, else from
    ``retrieval_sigma_ppm_m``.

    Args:
        path: NetCDF raster (see :func:`xrproducts.open_emit_ch4_l2b`).
        frame: Analysis frame.
        bbox: Optional ``(lon_min, lat_min, lon_max, lat_max)`` crop.
        glt_path: Optional geometric lookup table for orthorectification.
        retrieval_sigma_ppm_m: Per-pixel 1-σ [ppm m] for files without
            ``ch4_uncertainty``.
        pressure_pa: Near-surface pressure p for the ppm·m conversion.
        temperature_k: Near-surface temperature T for the ppm·m conversion.
        clock: Sets ``Instrument.observation_time``.
        name: Instrument name.

    Returns:
        The :class:`ColumnObservation`.

    Raises:
        MissingExtraError: If the ``io`` extra is not installed.
        MissingVariableError: If neither an uncertainty field nor
            ``retrieval_sigma_ppm_m`` is available.
        ScreeningError: If no pixel survives the screening.
    """
    xrproducts, _ = _readers()
    dataset = xrproducts.open_emit_ch4_l2b(path, glt_path=glt_path)
    if "ch4_uncertainty" in dataset:
        noise_field = dataset["ch4_uncertainty"]
    elif retrieval_sigma_ppm_m is not None:
        noise_field = xr.full_like(dataset["ch4_enhancement"], retrieval_sigma_ppm_m)
    else:
        raise MissingVariableError(
            "load_emit_l2b: the file has no `ch4_uncertainty`; pass "
            "`retrieval_sigma_ppm_m`"
        )

    def to_mass(kept: Float[np.ndarray, " pixel"]) -> Float[np.ndarray, " pixel"]:
        return ppm_m_to_column_mass(
            kept, pressure_pa=pressure_pa, temperature_k=temperature_k
        )

    return _scene_observation(
        dataset,
        "ch4_enhancement",
        noise_field,
        to_mass,
        noise_to_mass=to_mass,
        name=name,
        frame=frame,
        bbox=bbox,
        clock=clock,
    )

load_ghgsat_l2

load_ghgsat_l2(path: str | Path, *, frame: LocalFrame, retrieval_sigma_ppb: float, bbox: BBox | None = None, background_ppb: float | None = None, surface_pressure_pa: float = P_STANDARD, clock: TimeAxis | None = None, name: str = 'GHGSat') -> ColumnObservation

A GHGSat per-plume XCH₄ file as an instrument and its enhancement.

ΔΩ = (XCH₄ − b) · 10⁻⁹ · N_dry(p_s) · M / N_A, A = 1.

GHGSat files carry xch4 [ppb] without a kernel or a per-pixel precision, so the precision is an argument.

Parameters:

Name Type Description Default
path str | Path

Per-plume NetCDF (see :func:xrproducts.open_ghgsat_ch4_l2).

required
frame LocalFrame

Analysis frame.

required
retrieval_sigma_ppb float

Per-pixel 1-σ [ppb].

required
bbox BBox | None

Optional (lon_min, lat_min, lon_max, lat_max) crop.

None
background_ppb float | None

Background XCH₄ b [ppb]; the median of the kept pixels when None.

None
surface_pressure_pa float

Surface pressure p_s for N_dry.

P_STANDARD
clock TimeAxis | None

Sets Instrument.observation_time.

None
name str

Instrument name.

'GHGSat'

Returns:

Name Type Description
The ColumnObservation

class:ColumnObservation.

Raises:

Type Description
MissingExtraError

If the io extra is not installed.

MissingVariableError

If the file has no xch4.

ScreeningError

If no pixel survives the screening.

Source code in src/plumax/obs/_src/ingest.py
def load_ghgsat_l2(
    path: str | Path,
    *,
    frame: LocalFrame,
    retrieval_sigma_ppb: float,
    bbox: BBox | None = None,
    background_ppb: float | None = None,
    surface_pressure_pa: float = P_STANDARD,
    clock: TimeAxis | None = None,
    name: str = "GHGSat",
) -> ColumnObservation:
    """A GHGSat per-plume XCH₄ file as an instrument and its enhancement.

    ΔΩ = (XCH₄ − b) · 10⁻⁹ · N_dry(p_s) · M / N_A,  A = 1.

    GHGSat files carry ``xch4`` [ppb] without a kernel or a per-pixel
    precision, so the precision is an argument.

    Args:
        path: Per-plume NetCDF (see :func:`xrproducts.open_ghgsat_ch4_l2`).
        frame: Analysis frame.
        retrieval_sigma_ppb: Per-pixel 1-σ [ppb].
        bbox: Optional ``(lon_min, lat_min, lon_max, lat_max)`` crop.
        background_ppb: Background XCH₄ b [ppb]; the median of the kept pixels
            when ``None``.
        surface_pressure_pa: Surface pressure p_s for N_dry.
        clock: Sets ``Instrument.observation_time``.
        name: Instrument name.

    Returns:
        The :class:`ColumnObservation`.

    Raises:
        MissingExtraError: If the ``io`` extra is not installed.
        MissingVariableError: If the file has no ``xch4``.
        ScreeningError: If no pixel survives the screening.
    """
    xrproducts, dry_air_column = _readers()
    dataset = xrproducts.open_ghgsat_ch4_l2(path)
    if "xch4" not in dataset:
        raise MissingVariableError(f"load_ghgsat_l2: {path!s} has no `xch4`")
    surface = xr.Dataset({"sp": surface_pressure_pa})
    dry_air = float(dry_air_column(surface)["dry_air_column"])

    def to_mass(kept: Float[np.ndarray, " pixel"]) -> Float[np.ndarray, " pixel"]:
        # `kept` is already screened, so the default background is the median
        # of the pixels that stay (as for TROPOMI), not of the whole file
        background = (
            float(np.median(kept)) if background_ppb is None else background_ppb
        )
        # Δχ = XCH₄ − b
        mixing_ratio_enhancement = kept - background
        return ppb_to_column_mass(mixing_ratio_enhancement, dry_air)

    def noise_to_mass(kept: Float[np.ndarray, " pixel"]) -> Float[np.ndarray, " pixel"]:
        return ppb_to_column_mass(kept, dry_air)

    return _scene_observation(
        dataset,
        "xch4",
        xr.full_like(dataset["xch4"], retrieval_sigma_ppb),
        to_mass,
        noise_to_mass=noise_to_mass,
        name=name,
        frame=frame,
        bbox=bbox,
        clock=clock,
    )

load_tropomi_l2

load_tropomi_l2(path: str | Path, *, frame: LocalFrame, bbox: BBox | None = None, background_ppb: float | None = None, qa_min: float = 0.5, surface_layer: int = -1, clock: TimeAxis | None = None, name: str = 'TROPOMI') -> ColumnObservation

A TROPOMI CH₄ L2 granule as an instrument and its enhancement.

ΔΩ = (XCH₄ − b) · 10⁻⁹ · N_dry(p_s) · M / N_A, σ_Ω = σ_χ · 10⁻⁹ · N_dry · M / N_A, A = A_{surface layer}.

Algorithm
  1. Open the granule with xrproducts (QA screening at qa_min) and add the dry-air column from the surface pressure.
  2. Flatten the swath to pixels; drop NaNs and pixels outside bbox.
  3. Take the background (default: median of the kept XCH₄), convert XCH₄ and its precision to column mass, and pick the near-surface kernel layer.
  4. Place the kept pixel centres in the frame.

Parameters:

Name Type Description Default
path str | Path

S5P_*_L2__CH4____*.nc granule.

required
frame LocalFrame

Analysis frame the receptors are placed in.

required
bbox BBox | None

Optional (lon_min, lat_min, lon_max, lat_max) crop.

None
background_ppb float | None

Background XCH₄ b [ppb]; the median of the kept pixels when None.

None
qa_min float

Minimum qa_value (the product guide recommends 0.5).

0.5
surface_layer int

Index of the near-surface retrieval layer; layers run top of atmosphere first, so the default is -1.

-1
clock TimeAxis | None

Sets Instrument.observation_time as seconds since its t0; zero when None.

None
name str

Instrument name.

'TROPOMI'

Returns:

Name Type Description
The ColumnObservation

class:ColumnObservation.

Raises:

Type Description
MissingExtraError

If the io extra is not installed.

ScreeningError

If no pixel survives the screening.

Source code in src/plumax/obs/_src/ingest.py
def load_tropomi_l2(
    path: str | Path,
    *,
    frame: LocalFrame,
    bbox: BBox | None = None,
    background_ppb: float | None = None,
    qa_min: float = 0.5,
    surface_layer: int = -1,
    clock: TimeAxis | None = None,
    name: str = "TROPOMI",
) -> ColumnObservation:
    """A TROPOMI CH₄ L2 granule as an instrument and its enhancement.

    ΔΩ = (XCH₄ − b) · 10⁻⁹ · N_dry(p_s) · M / N_A,  σ_Ω = σ_χ · 10⁻⁹ · N_dry · M / N_A,
    A = A_{surface layer}.

    Algorithm:
        1. Open the granule with xrproducts (QA screening at ``qa_min``) and add
           the dry-air column from the surface pressure.
        2. Flatten the swath to pixels; drop NaNs and pixels outside ``bbox``.
        3. Take the background (default: median of the kept XCH₄), convert
           XCH₄ and its precision to column mass, and pick the near-surface
           kernel layer.
        4. Place the kept pixel centres in the frame.

    Args:
        path: ``S5P_*_L2__CH4____*.nc`` granule.
        frame: Analysis frame the receptors are placed in.
        bbox: Optional ``(lon_min, lat_min, lon_max, lat_max)`` crop.
        background_ppb: Background XCH₄ b [ppb]; the median of the kept
            pixels when ``None``.
        qa_min: Minimum ``qa_value`` (the product guide recommends 0.5).
        surface_layer: Index of the near-surface retrieval layer; layers run
            top of atmosphere first, so the default is ``-1``.
        clock: Sets ``Instrument.observation_time`` as seconds since its
            ``t0``; zero when ``None``.
        name: Instrument name.

    Returns:
        The :class:`ColumnObservation`.

    Raises:
        MissingExtraError: If the ``io`` extra is not installed.
        ScreeningError: If no pixel survives the screening.
    """
    xrproducts, dry_air_column = _readers()

    # --- read ---
    dataset = xrproducts.open_tropomi_ch4_l2(path, qa_min=qa_min)
    dataset = dry_air_column(dataset, surface_pressure="sp")
    xch4 = dataset["xch4_bias_corrected"]
    pixel_dims = list(xch4.dims)
    kernel = dataset["column_averaging_kernel"].isel(layer=surface_layer)
    fields = {
        "xch4": xch4,
        "sigma": dataset["xch4_precision"],
        "kernel": kernel,
        "dry_air": dataset["dry_air_column"],
        "lat": dataset["lat"],
        "lon": dataset["lon"],
    }

    # --- screen ---
    pixels = {
        key: _flatten(field.transpose(*pixel_dims).values)
        for key, field in fields.items()
    }
    kept = _screen(pixels, bbox)

    # --- convert ---
    if background_ppb is None:
        background_ppb = float(np.median(kept["xch4"]))
    # Δχ = XCH₄ − b
    mixing_ratio_enhancement = kept["xch4"] - background_ppb
    enhancement = ppb_to_column_mass(mixing_ratio_enhancement, kept["dry_air"])
    # σ_Ω = σ_χ · 10⁻⁹ · N_dry · M / N_A
    obs_noise_std = ppb_to_column_mass(kept["sigma"], kept["dry_air"])
    when = _scene_time(dataset)
    return _observation(
        name, frame, kept, enhancement, obs_noise_std, kept["kernel"], when, clock
    )

ppb_to_column_mass

ppb_to_column_mass(delta_ppb: Float[ndarray, '*#pixel'] | float, dry_air_molecules: Float[ndarray, '*#pixel'] | float) -> Float[np.ndarray, ' ...']

Column-mass enhancement of a mixing-ratio enhancement.

ΔΩ = Δχ · 10⁻⁹ · N_dry · M / N_A.

Parameters:

Name Type Description Default
delta_ppb Float[ndarray, '*#pixel'] | float

Mixing-ratio enhancement Δχ [ppb].

required
dry_air_molecules Float[ndarray, '*#pixel'] | float

Dry-air column N_dry [molecules m⁻²].

required

Returns:

Type Description
Float[ndarray, ' ...']

ΔΩ [kg m⁻²].

Examples:

1 ppb over a 1013.25 hPa dry column is about 5.7 mg m⁻²:

>>> import numpy as np
>>> from geophysix.columns import dry_air_column
>>> from geophysix.constants import STANDARD
>>> dry_air = dry_air_column(101_325.0) * STANDARD.avogadro
>>> bool(np.isclose(ppb_to_column_mass(1.0, dry_air), 5.72e-6, rtol=1e-3))
True

Linear in Δχ, elementwise over pixels:

>>> ppb_to_column_mass(np.array([0.0, 10.0, -10.0]), dry_air).shape
(3,)
Source code in src/plumax/obs/_src/ingest.py
def ppb_to_column_mass(
    delta_ppb: Float[np.ndarray, "*#pixel"] | float,
    dry_air_molecules: Float[np.ndarray, "*#pixel"] | float,
) -> Float[np.ndarray, " ..."]:
    """Column-mass enhancement of a mixing-ratio enhancement.

    ΔΩ = Δχ · 10⁻⁹ · N_dry · M / N_A.

    Args:
        delta_ppb: Mixing-ratio enhancement Δχ [ppb].
        dry_air_molecules: Dry-air column N_dry [molecules m⁻²].

    Returns:
        ΔΩ [kg m⁻²].

    Examples:
        1 ppb over a 1013.25 hPa dry column is about 5.7 mg m⁻²:

        >>> import numpy as np
        >>> from geophysix.columns import dry_air_column
        >>> from geophysix.constants import STANDARD
        >>> dry_air = dry_air_column(101_325.0) * STANDARD.avogadro
        >>> bool(np.isclose(ppb_to_column_mass(1.0, dry_air), 5.72e-6, rtol=1e-3))
        True

        Linear in Δχ, elementwise over pixels:

        >>> ppb_to_column_mass(np.array([0.0, 10.0, -10.0]), dry_air).shape
        (3,)
    """
    # dry-air column in mol m⁻²: N_dry / N_A
    dry_air_moles = np.asarray(dry_air_molecules) / AVOGADRO
    # ΔΩ = M · Δχ · 10⁻⁹ · N_dry / N_A
    return np.asarray(
        M_CH4 * column_from_mixing_ratio(np.asarray(delta_ppb) * 1.0e-9, dry_air_moles)
    )

ppm_m_to_column_mass

ppm_m_to_column_mass(enhancement_ppm_m: Float[ndarray, '*#pixel'] | float, *, pressure_pa: float, temperature_k: float, molar_mass: float = M_CH4) -> Float[np.ndarray, ' ...']

Column-mass enhancement of a path-integrated enhancement.

ΔΩ = E · 10⁻⁶ · (p / (k_B T)) · M / N_A.

Parameters:

Name Type Description Default
enhancement_ppm_m Float[ndarray, '*#pixel'] | float

Path-integrated enhancement E [ppm m].

required
pressure_pa float

Layer pressure p [Pa].

required
temperature_k float

Layer temperature T [K].

required
molar_mass float

Molar mass M of the gas [kg mol⁻¹]; CH₄ by default.

M_CH4

Returns:

Type Description
Float[ndarray, ' ...']

ΔΩ [kg m⁻²].

Examples:

1000 ppm·m at 1013.25 hPa and 288.15 K: 42.3 mol m⁻³ · 1 mm · M:

>>> import numpy as np
>>> mass = ppm_m_to_column_mass(
...     1000.0, pressure_pa=101_325.0, temperature_k=288.15
... )
>>> bool(np.isclose(mass, 42.29e-3 * 0.0160425, rtol=1e-3))
True

Thinner air at altitude carries less mass for the same E:

>>> high = ppm_m_to_column_mass(
...     1000.0, pressure_pa=70_000.0, temperature_k=288.15
... )
>>> bool(high < mass)
True
Source code in src/plumax/_src/units.py
def ppm_m_to_column_mass(
    enhancement_ppm_m: Float[np.ndarray, "*#pixel"] | float,
    *,
    pressure_pa: float,
    temperature_k: float,
    molar_mass: float = M_CH4,
) -> Float[np.ndarray, " ..."]:
    """Column-mass enhancement of a path-integrated enhancement.

    ΔΩ = E · 10⁻⁶ · (p / (k_B T)) · M / N_A.

    Args:
        enhancement_ppm_m: Path-integrated enhancement E [ppm m].
        pressure_pa: Layer pressure p [Pa].
        temperature_k: Layer temperature T [K].
        molar_mass: Molar mass M of the gas [kg mol⁻¹]; CH₄ by default.

    Returns:
        ΔΩ [kg m⁻²].

    Examples:
        1000 ppm·m at 1013.25 hPa and 288.15 K: 42.3 mol m⁻³ · 1 mm · M:

        >>> import numpy as np
        >>> mass = ppm_m_to_column_mass(
        ...     1000.0, pressure_pa=101_325.0, temperature_k=288.15
        ... )
        >>> bool(np.isclose(mass, 42.29e-3 * 0.0160425, rtol=1e-3))
        True

        Thinner air at altitude carries less mass for the same E:

        >>> high = ppm_m_to_column_mass(
        ...     1000.0, pressure_pa=70_000.0, temperature_k=288.15
        ... )
        >>> bool(high < mass)
        True
    """
    # ΔΩ = M · E · 10⁻⁶ · p / (k_B T N_A)
    return np.asarray(
        convert(
            enhancement_ppm_m,
            "ppm_m",
            "kg_m2",
            gas=Gas("gas", molar_mass),
            pressure=pressure_pa,
            temperature=temperature_k,
        )
    )

load_emit_plume_complex

load_emit_plume_complex(enhancement_path: str | Path, outlines_path: str | Path, *, plume_id: str, frame: LocalFrame, sensitivity_path: str | Path | None = None, uncertainty_path: str | Path | None = None, quality_path: str | Path | None = None, glt_path: str | Path | None = None, margin_px: int = 10, uncertainty_of: Literal['truth', 'score'] = 'truth', retrieval_sigma_ppm_m: float | None = None, pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD, clock: TimeAxis | None = None, name: str = 'EMIT') -> PlumeScene

One catalogued plume of an EMIT scene as a PlumeScene.

yₙ = κ Eₙ, Aₙ from the sensitivity raster, and σₙ = κ Aₙ uₙ ("truth") or σₙ = κ uₙ ("score"), with κ the ppm m to kg m⁻² factor of :func:ppm_m_to_column_mass.

Algorithm
  1. Open the enhancement with its companions, and the outlines.
  2. Select the plume; crop to its bounding box plus the margin.
  3. Convert the enhancement and its noise to column mass.
  4. Build the mask from the fill values, the sensitivity and the quality raster.
  5. Project receptors, origin and outline into the local frame.
  6. Take the pixel side and the starting direction from them.

The stored enhancement is the raw matched-filter score, so it is converted but never divided by the sensitivity. A pixel is masked (ωₙ = 0) when its enhancement, sensitivity or uncertainty is missing, its sensitivity is not positive, or the quality raster flags it as cloud, cirrus, water (geoops.qa.EMITL2AMask) or saturated (geoops.qa.EMITBandMask, dilated by 10 pixels). A masked pixel stays in the arrays with yₙ = 0, Aₙ = 1 and the median σₙ² of the kept pixels, so the window keeps its pixels for plotting; a pixel with no location, or with none of the three fields, is dropped. The DAAC plume files carry no pseudo-origin; the brightest in-plume pixel stands in for it then.

Parameters:

Name Type Description Default
enhancement_path str | Path

Enhancement raster E [ppm m] (NetCDF, see xrproducts.open_emit_ch4_l2b).

required
outlines_path str | Path

Plume-complex GeoJSON.

required
plume_id str

Identifier of the plume to load.

required
frame LocalFrame

Local metre frame of the analysis.

required
sensitivity_path str | Path | None

Sensitivity raster A; None sets A = 1.

None
uncertainty_path str | Path | None

Uncertainty raster u [ppm m].

None
quality_path str | Path | None

EMIT L2A MASK NetCDF (mask and, if present, band_mask) in swath geometry; flagged pixels get ω = 0. Needs the geo extra.

None
glt_path str | Path | None

Geometric lookup table, for swath-geometry rasters; the quality flags are decoded in swath geometry and go through it too.

None
margin_px int

Margin around the outline's bounding box, in pixels.

10
uncertainty_of Literal['truth', 'score']

Whether u is the noise of the enhancement divided by the sensitivity ("truth") or of the raw score.

'truth'
retrieval_sigma_ppm_m float | None

Constant u for files without an uncertainty raster.

None
pressure_pa float

Near-surface pressure p [Pa] for the conversion.

P_STANDARD
temperature_k float

Near-surface temperature T [K] for the conversion.

T_STANDARD
clock TimeAxis | None

Sets the instrument's observation time.

None
name str

Instrument name.

'EMIT'

Returns:

Name Type Description
The PlumeScene

class:PlumeScene.

Raises:

Type Description
MissingExtraError

If the io extra is not installed, or the geo extra when a quality raster is given.

MissingVariableError

If plume_id is not in the file (the message lists the identifiers it has), or there is neither an uncertainty raster nor retrieval_sigma_ppm_m.

GridMismatchError

If the outline's bounding box leaves the scene, or the quality raster is not on the scene's grid.

ScreeningError

If no pixel survives the mask.

ParameterError

If margin_px is negative or uncertainty_of is unknown.

DomainError

If the plume's centroid is within a pixel of its origin.

Examples:

On the files a catalogue lists for one plume::

scene = load_emit_plume_complex(
    "scene_CH4ENH.nc",
    "plume_complexes.json",
    plume_id="CH4_PlumeComplex-1234",
    frame=frame,
    sensitivity_path="scene_CH4SENS.nc",
    uncertainty_path="scene_CH4UNCERT.nc",
)
scene.instrument.averaging_kernel  # Aₙ, shape (N_Ωy,)
Source code in src/plumax/obs/_src/plume_scene.py
def load_emit_plume_complex(
    enhancement_path: str | Path,
    outlines_path: str | Path,
    *,
    plume_id: str,
    frame: LocalFrame,
    sensitivity_path: str | Path | None = None,
    uncertainty_path: str | Path | None = None,
    quality_path: str | Path | None = None,
    glt_path: str | Path | None = None,
    margin_px: int = 10,
    uncertainty_of: Literal["truth", "score"] = "truth",
    retrieval_sigma_ppm_m: float | None = None,
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
    clock: TimeAxis | None = None,
    name: str = "EMIT",
) -> PlumeScene:
    """One catalogued plume of an EMIT scene as a ``PlumeScene``.

    yₙ = κ Eₙ, Aₙ from the sensitivity raster, and σₙ = κ Aₙ uₙ
    (``"truth"``) or σₙ = κ uₙ (``"score"``), with κ the ppm m to kg m⁻²
    factor of :func:`ppm_m_to_column_mass`.

    Algorithm:
        1. Open the enhancement with its companions, and the outlines.
        2. Select the plume; crop to its bounding box plus the margin.
        3. Convert the enhancement and its noise to column mass.
        4. Build the mask from the fill values, the sensitivity and the
           quality raster.
        5. Project receptors, origin and outline into the local frame.
        6. Take the pixel side and the starting direction from them.

    The stored enhancement is the raw matched-filter score, so it is
    converted but never divided by the sensitivity. A pixel is masked
    (ωₙ = 0) when its enhancement, sensitivity or uncertainty is missing,
    its sensitivity is not positive, or the quality raster flags it as
    cloud, cirrus, water (``geoops.qa.EMITL2AMask``) or saturated
    (``geoops.qa.EMITBandMask``, dilated by 10 pixels). A masked pixel stays
    in the arrays with yₙ = 0, Aₙ = 1 and the median σₙ² of the kept pixels,
    so the window keeps its pixels for plotting; a pixel with no location,
    or with none of the three fields, is dropped. The DAAC plume files carry
    no pseudo-origin; the brightest in-plume pixel stands in for it then.

    Args:
        enhancement_path: Enhancement raster E [ppm m] (NetCDF, see
            ``xrproducts.open_emit_ch4_l2b``).
        outlines_path: Plume-complex GeoJSON.
        plume_id: Identifier of the plume to load.
        frame: Local metre frame of the analysis.
        sensitivity_path: Sensitivity raster A; ``None`` sets A = 1.
        uncertainty_path: Uncertainty raster u [ppm m].
        quality_path: EMIT L2A MASK NetCDF (``mask`` and, if present,
            ``band_mask``) in swath geometry; flagged pixels get ω = 0.
            Needs the ``geo`` extra.
        glt_path: Geometric lookup table, for swath-geometry rasters; the
            quality flags are decoded in swath geometry and go through it too.
        margin_px: Margin around the outline's bounding box, in pixels.
        uncertainty_of: Whether u is the noise of the enhancement divided
            by the sensitivity (``"truth"``) or of the raw score.
        retrieval_sigma_ppm_m: Constant u for files without an
            uncertainty raster.
        pressure_pa: Near-surface pressure p [Pa] for the conversion.
        temperature_k: Near-surface temperature T [K] for the conversion.
        clock: Sets the instrument's observation time.
        name: Instrument name.

    Returns:
        The :class:`PlumeScene`.

    Raises:
        MissingExtraError: If the ``io`` extra is not installed, or the
            ``geo`` extra when a quality raster is given.
        MissingVariableError: If ``plume_id`` is not in the file (the
            message lists the identifiers it has), or there is neither an
            uncertainty raster nor ``retrieval_sigma_ppm_m``.
        GridMismatchError: If the outline's bounding box leaves the scene,
            or the quality raster is not on the scene's grid.
        ScreeningError: If no pixel survives the mask.
        ParameterError: If ``margin_px`` is negative or ``uncertainty_of``
            is unknown.
        DomainError: If the plume's centroid is within a pixel of its origin.

    Examples:
        On the files a catalogue lists for one plume::

            scene = load_emit_plume_complex(
                "scene_CH4ENH.nc",
                "plume_complexes.json",
                plume_id="CH4_PlumeComplex-1234",
                frame=frame,
                sensitivity_path="scene_CH4SENS.nc",
                uncertainty_path="scene_CH4UNCERT.nc",
            )
            scene.instrument.averaging_kernel  # Aₙ, shape (N_Ωy,)
    """
    require_positive("margin_px", margin_px, allow_zero=True)
    if uncertainty_of not in ("truth", "score"):
        raise ParameterError(
            f"uncertainty_of must be 'truth' or 'score', got {uncertainty_of!r}"
        )
    xrproducts, _ = _readers()

    # --- read ---
    dataset = xrproducts.open_emit_ch4_l2b(
        enhancement_path,
        sensitivity_path=sensitivity_path,
        uncertainty_path=uncertainty_path,
        glt_path=glt_path,
    )
    plumes = xrproducts.open_ch4_plume_complexes(outlines_path)
    ids = [str(value) for value in plumes["plume"].values]
    if plume_id not in ids:
        raise MissingVariableError(
            f"load_emit_plume_complex: {plume_id!r} is not in {outlines_path!s}; "
            f"it has {ids}"
        )
    if "ch4_uncertainty" not in dataset and retrieval_sigma_ppm_m is None:
        raise MissingVariableError(
            "load_emit_plume_complex: no uncertainty raster; pass "
            "`uncertainty_path` or `retrieval_sigma_ppm_m`"
        )
    enhancement = _raster(dataset["ch4_enhancement"])
    lat, lon = _raster(dataset["lat"]), _raster(dataset["lon"])
    dtype = enhancement.dtype
    if "ch4_sensitivity" in dataset:
        sensitivity = _raster(dataset["ch4_sensitivity"])
    else:
        sensitivity = np.ones_like(enhancement)
    if "ch4_uncertainty" in dataset:
        uncertainty = _raster(dataset["ch4_uncertainty"])
    else:
        uncertainty = np.full_like(enhancement, retrieval_sigma_ppm_m)
    flags = np.zeros(enhancement.shape, dtype=np.int32)
    if quality_path is not None:
        flags = _quality_flags(quality_path, glt_path, enhancement.shape)

    # --- window ---
    # the outline as (lon, lat) rows
    ring = xrproducts.plume_outline(plumes, plume_id)
    rows, cols = _window(ring, lat, lon, margin_px)
    window = (slice(*rows), slice(*cols))
    fields = {
        "enhancement": enhancement[window],
        "sensitivity": sensitivity[window],
        "uncertainty": uncertainty[window],
        "lat": lat[window],
        "lon": lon[window],
        "flags": flags[window],
    }

    # --- convert ---
    # κ, ppm m → kg m⁻²
    mass_per_ppm_m = float(
        ppm_m_to_column_mass(1.0, pressure_pa=pressure_pa, temperature_k=temperature_k)
    )
    # yₙ = κ Eₙ
    column_mass = (mass_per_ppm_m * fields["enhancement"]).astype(dtype)
    if uncertainty_of == "truth":
        # σₙ = κ Aₙ uₙ
        obs_noise_std = mass_per_ppm_m * fields["sensitivity"] * fields["uncertainty"]
    else:
        # σₙ = κ uₙ
        obs_noise_std = mass_per_ppm_m * fields["uncertainty"]

    # --- mask ---
    keep, mask = _pixel_mask(
        column_mass,
        fields["sensitivity"],
        obs_noise_std,
        fields["lat"],
        fields["lon"],
    )
    mask &= fields["flags"] == 0
    kept = _kept_pixels(
        column_mass,
        fields["sensitivity"],
        obs_noise_std,
        mask,
        keep,
        fields["flags"],
    )

    # --- geometry ---
    # sₙ = (xₙ, yₙ) in the frame
    easting, northing = frame.to_xy(fields["lat"], fields["lon"])
    pixel_size = _pixel_size(easting, northing)
    receptors = einx.id("p, p -> p (1 + 1)", easting[keep], northing[keep])
    outline_x, outline_y = frame.to_xy(ring[:, 1], ring[:, 0])
    outline = einx.id("v, v -> v (1 + 1)", outline_x, outline_y)
    in_plume = _inside(receptors, outline)
    origin = _origin(plumes, plume_id, frame, receptors, kept, in_plume)
    direction = _direction(receptors, kept, in_plume, origin, pixel_size)
    row_index, col_index = np.nonzero(keep)
    pixel_index = einx.id("p, p -> p (1 + 1)", row_index, col_index)

    observation = _column_observation(
        name,
        receptors,
        kept["kernel"],
        kept["variance"],
        kept["enhancement"],
        _scene_time(dataset),
        clock,
        flags=kept["flags"],
        mask=kept["mask"].astype(dtype),
    )
    return PlumeScene(
        observation=observation,
        origin=jnp.asarray(origin),
        outline=jnp.asarray(outline),
        in_plume=jnp.asarray(in_plume),
        direction=jnp.asarray(direction),
        pixel_index=jnp.asarray(pixel_index),
        plume_id=plume_id,
        pixel_size=pixel_size,
        window=(*rows, *cols),
    )

matched_filter_scene

matched_filter_scene(score: Float[ndarray, 'row col'], score_std: Float[ndarray, 'row col'] | float, *, lat: Float[ndarray, 'row col'], lon: Float[ndarray, 'row col'], frame: LocalFrame, sensitivity: Float[ndarray, 'row col'] | None = None, exclude: Bool[ndarray, 'row col'] | None = None, unit: Literal['mol_m2', 'ppm_m', 'kg_m2'] = 'mol_m2', pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD, name: str = 'EMIT') -> ColumnObservation

A ColumnObservation from radtrax's score, noise and sensitivity maps.

yₙ = M α̂ₙ and σₙ = M σ_α,n for a score in mol m⁻², with M the molar mass of methane; Aₙ is the sensitivity, or 1. A scalar score_std is the noise of every pixel.

The noise is that of the raw score (radtrax's score_std), so it is not multiplied by the sensitivity. For unit="ppm_m" the factor is κ of :func:ppm_m_to_column_mass, and for "kg_m2" it is 1. Pixels with a missing value or location, a non-positive sensitivity or set in exclude get ω = 0 (with y = 0, A = 1 and the median σ² of the kept pixels); pixels with no location or none of the fields are dropped.

Parameters:

Name Type Description Default
score Float[ndarray, 'row col']

Matched-filter score α̂ in unit.

required
score_std Float[ndarray, 'row col'] | float

Its standard deviation σ_α, per pixel or one for all.

required
lat Float[ndarray, 'row col']

Pixel-centre latitudes [degrees].

required
lon Float[ndarray, 'row col']

Pixel-centre longitudes [degrees].

required
frame LocalFrame

Local metre frame of the analysis.

required
sensitivity Float[ndarray, 'row col'] | None

Sensitivity A; None sets A = 1.

None
exclude Bool[ndarray, 'row col'] | None

Pixels to mask out, such as geoops.qa masks.

None
unit Literal['mol_m2', 'ppm_m', 'kg_m2']

Unit of score and score_std.

'mol_m2'
pressure_pa float

Near-surface pressure p [Pa], for "ppm_m".

P_STANDARD
temperature_k float

Near-surface temperature T [K], for "ppm_m".

T_STANDARD
name str

Instrument name.

'EMIT'

Returns:

Name Type Description
The ColumnObservation

class:ColumnObservation, with time NaT.

Raises:

Type Description
UnitsError

If unit is not one of the three.

ScreeningError

If no pixel survives the mask.

Examples:

>>> import numpy as np
>>> from plumax.met import LocalFrame
>>> frame = LocalFrame.at(31.95, -102.15)
>>> lat, lon = frame.to_latlon(*np.meshgrid([0.0, 60.0], [0.0, 60.0]))
>>> observation = matched_filter_scene(
...     np.full((2, 2), 0.01), 0.002, lat=lat, lon=lon, frame=frame
... )
>>> observation.enhancement.tolist()  # M α̂ = 0.0160425 × 0.01
[0.000160425, 0.000160425, 0.000160425, 0.000160425]
Source code in src/plumax/obs/_src/plume_scene.py
def matched_filter_scene(
    score: Float[np.ndarray, "row col"],
    score_std: Float[np.ndarray, "row col"] | float,
    *,
    lat: Float[np.ndarray, "row col"],
    lon: Float[np.ndarray, "row col"],
    frame: LocalFrame,
    sensitivity: Float[np.ndarray, "row col"] | None = None,
    exclude: Bool[np.ndarray, "row col"] | None = None,
    unit: Literal["mol_m2", "ppm_m", "kg_m2"] = "mol_m2",
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
    name: str = "EMIT",
) -> ColumnObservation:
    """A ``ColumnObservation`` from radtrax's score, noise and sensitivity maps.

    yₙ = M α̂ₙ and σₙ = M σ_α,n for a score in mol m⁻², with M the molar
    mass of methane; Aₙ is the sensitivity, or 1. A scalar ``score_std`` is
    the noise of every pixel.

    The noise is that of the raw score (radtrax's ``score_std``), so it is
    not multiplied by the sensitivity. For ``unit="ppm_m"`` the factor is κ
    of :func:`ppm_m_to_column_mass`, and for ``"kg_m2"`` it is 1. Pixels
    with a missing value or location, a non-positive sensitivity or set in
    ``exclude`` get ω = 0 (with y = 0, A = 1 and the median σ² of the kept
    pixels); pixels with no location or none of the fields are dropped.

    Args:
        score: Matched-filter score α̂ in ``unit``.
        score_std: Its standard deviation σ_α, per pixel or one for all.
        lat: Pixel-centre latitudes [degrees].
        lon: Pixel-centre longitudes [degrees].
        frame: Local metre frame of the analysis.
        sensitivity: Sensitivity A; ``None`` sets A = 1.
        exclude: Pixels to mask out, such as ``geoops.qa`` masks.
        unit: Unit of ``score`` and ``score_std``.
        pressure_pa: Near-surface pressure p [Pa], for ``"ppm_m"``.
        temperature_k: Near-surface temperature T [K], for ``"ppm_m"``.
        name: Instrument name.

    Returns:
        The :class:`ColumnObservation`, with ``time`` ``NaT``.

    Raises:
        UnitsError: If ``unit`` is not one of the three.
        ScreeningError: If no pixel survives the mask.

    Examples:
        >>> import numpy as np
        >>> from plumax.met import LocalFrame
        >>> frame = LocalFrame.at(31.95, -102.15)
        >>> lat, lon = frame.to_latlon(*np.meshgrid([0.0, 60.0], [0.0, 60.0]))
        >>> observation = matched_filter_scene(
        ...     np.full((2, 2), 0.01), 0.002, lat=lat, lon=lon, frame=frame
        ... )
        >>> observation.enhancement.tolist()  # M α̂ = 0.0160425 × 0.01
        [0.000160425, 0.000160425, 0.000160425, 0.000160425]
    """
    if unit == "mol_m2":
        # yₙ = M α̂ₙ
        factor = M_CH4
    elif unit == "ppm_m":
        # yₙ = κ α̂ₙ
        factor = float(
            ppm_m_to_column_mass(
                1.0, pressure_pa=pressure_pa, temperature_k=temperature_k
            )
        )
    elif unit == "kg_m2":
        factor = 1.0
    else:
        raise UnitsError(
            f"matched_filter_scene: unit must be 'mol_m2', 'ppm_m' or 'kg_m2', "
            f"got {unit!r}"
        )
    values = np.asarray(score)
    dtype = np.result_type(values.dtype, np.float32)
    column_mass = (factor * values).astype(dtype)
    # σₙ = M σ_α,n
    obs_noise_std = factor * np.broadcast_to(
        np.asarray(score_std, dtype=dtype), values.shape
    )
    gain = (
        np.ones_like(column_mass)
        if sensitivity is None
        else np.asarray(sensitivity, dtype=dtype)
    )
    lat, lon = np.asarray(lat), np.asarray(lon)
    keep, mask = _pixel_mask(column_mass, gain, obs_noise_std, lat, lon)
    flags = np.zeros(values.shape, dtype=np.int32)
    if exclude is not None:
        excluded = np.asarray(exclude, dtype=bool)
        flags = np.where(excluded, int(QualityFlag.CLOUD), 0).astype(np.int32)
        mask &= ~excluded
    kept = _kept_pixels(column_mass, gain, obs_noise_std, mask, keep, flags)
    easting, northing = frame.to_xy(lat, lon)
    receptors = einx.id("p, p -> p (1 + 1)", easting[keep], northing[keep])
    return _column_observation(
        name,
        receptors,
        kept["kernel"],
        kept["variance"],
        kept["enhancement"],
        np.datetime64("NaT"),
        None,
        flags=kept["flags"],
        mask=kept["mask"].astype(dtype),
    )

plume_scene: one plume for the image fit

load_emit_plume_complex loads one catalogued plume of an EMIT scene as a PlumeScene: the window around its outline (plus a margin), with the sensitivity as the averaging kernel, a per-pixel noise, the quality mask (cloud, cirrus and water from the L2A mask, and the saturation mask from the band mask, through geoops.qa), the pseudo-origin and a starting direction. matched_filter_scene builds the same observation from radtrax's score, noise and sensitivity maps. The enhancement is never divided by the sensitivity; the model is multiplied by it instead.

One plume from a matched-filter product (implementation in plumax.obs._src.plume_scene).

PlumeScene

Bases: Module

One plume: its observation, its outline and where the fit starts.

yₙ = Aₙ ΔΩₙ + εₙ, εₙ ~ 𝒩(0, σₙ²), with yₙ, Aₙ, σₙ² and the mask ωₙ held by observation.

Attributes:

Name Type Description
observation ColumnObservation

Instrument (receptors, Aₙ, σₙ², ωₙ) and enhancement yₙ.

origin Float[Array, ' axis']

Pseudo-origin s₀ in the local frame [m].

outline Float[Array, 'vertex axis']

Plume outline in the local frame [m], closed.

in_plume Bool[Array, ' pixel']

Whether each kept pixel lies inside the outline.

direction Float[Array, '']

Starting direction φ₀ [rad], origin to plume centroid, counter-clockwise from the frame's x axis.

pixel_index Int[Array, 'pixel 2']

(row, col) of each kept pixel in the window, to put the pixels back on the image.

plume_id str

Identifier of the plume in its product.

pixel_size float

Pixel side g [m].

window tuple[int, int, int, int]

(row_start, row_stop, col_start, col_stop) of the window in the scene's raster.

window_shape property

window_shape: tuple[int, int]

(N_row, N_col) of the window.

instrument property

instrument: Instrument

The instrument of the observation.

enhancement property

enhancement: Float[Array, ' pixel']

Observed column-mass enhancement yₙ [kg m⁻²].

load_emit_plume_complex

load_emit_plume_complex(enhancement_path: str | Path, outlines_path: str | Path, *, plume_id: str, frame: LocalFrame, sensitivity_path: str | Path | None = None, uncertainty_path: str | Path | None = None, quality_path: str | Path | None = None, glt_path: str | Path | None = None, margin_px: int = 10, uncertainty_of: Literal['truth', 'score'] = 'truth', retrieval_sigma_ppm_m: float | None = None, pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD, clock: TimeAxis | None = None, name: str = 'EMIT') -> PlumeScene

One catalogued plume of an EMIT scene as a PlumeScene.

yₙ = κ Eₙ, Aₙ from the sensitivity raster, and σₙ = κ Aₙ uₙ ("truth") or σₙ = κ uₙ ("score"), with κ the ppm m to kg m⁻² factor of :func:ppm_m_to_column_mass.

Algorithm
  1. Open the enhancement with its companions, and the outlines.
  2. Select the plume; crop to its bounding box plus the margin.
  3. Convert the enhancement and its noise to column mass.
  4. Build the mask from the fill values, the sensitivity and the quality raster.
  5. Project receptors, origin and outline into the local frame.
  6. Take the pixel side and the starting direction from them.

The stored enhancement is the raw matched-filter score, so it is converted but never divided by the sensitivity. A pixel is masked (ωₙ = 0) when its enhancement, sensitivity or uncertainty is missing, its sensitivity is not positive, or the quality raster flags it as cloud, cirrus, water (geoops.qa.EMITL2AMask) or saturated (geoops.qa.EMITBandMask, dilated by 10 pixels). A masked pixel stays in the arrays with yₙ = 0, Aₙ = 1 and the median σₙ² of the kept pixels, so the window keeps its pixels for plotting; a pixel with no location, or with none of the three fields, is dropped. The DAAC plume files carry no pseudo-origin; the brightest in-plume pixel stands in for it then.

Parameters:

Name Type Description Default
enhancement_path str | Path

Enhancement raster E [ppm m] (NetCDF, see xrproducts.open_emit_ch4_l2b).

required
outlines_path str | Path

Plume-complex GeoJSON.

required
plume_id str

Identifier of the plume to load.

required
frame LocalFrame

Local metre frame of the analysis.

required
sensitivity_path str | Path | None

Sensitivity raster A; None sets A = 1.

None
uncertainty_path str | Path | None

Uncertainty raster u [ppm m].

None
quality_path str | Path | None

EMIT L2A MASK NetCDF (mask and, if present, band_mask) in swath geometry; flagged pixels get ω = 0. Needs the geo extra.

None
glt_path str | Path | None

Geometric lookup table, for swath-geometry rasters; the quality flags are decoded in swath geometry and go through it too.

None
margin_px int

Margin around the outline's bounding box, in pixels.

10
uncertainty_of Literal['truth', 'score']

Whether u is the noise of the enhancement divided by the sensitivity ("truth") or of the raw score.

'truth'
retrieval_sigma_ppm_m float | None

Constant u for files without an uncertainty raster.

None
pressure_pa float

Near-surface pressure p [Pa] for the conversion.

P_STANDARD
temperature_k float

Near-surface temperature T [K] for the conversion.

T_STANDARD
clock TimeAxis | None

Sets the instrument's observation time.

None
name str

Instrument name.

'EMIT'

Returns:

Name Type Description
The PlumeScene

class:PlumeScene.

Raises:

Type Description
MissingExtraError

If the io extra is not installed, or the geo extra when a quality raster is given.

MissingVariableError

If plume_id is not in the file (the message lists the identifiers it has), or there is neither an uncertainty raster nor retrieval_sigma_ppm_m.

GridMismatchError

If the outline's bounding box leaves the scene, or the quality raster is not on the scene's grid.

ScreeningError

If no pixel survives the mask.

ParameterError

If margin_px is negative or uncertainty_of is unknown.

DomainError

If the plume's centroid is within a pixel of its origin.

Examples:

On the files a catalogue lists for one plume::

scene = load_emit_plume_complex(
    "scene_CH4ENH.nc",
    "plume_complexes.json",
    plume_id="CH4_PlumeComplex-1234",
    frame=frame,
    sensitivity_path="scene_CH4SENS.nc",
    uncertainty_path="scene_CH4UNCERT.nc",
)
scene.instrument.averaging_kernel  # Aₙ, shape (N_Ωy,)
Source code in src/plumax/obs/_src/plume_scene.py
def load_emit_plume_complex(
    enhancement_path: str | Path,
    outlines_path: str | Path,
    *,
    plume_id: str,
    frame: LocalFrame,
    sensitivity_path: str | Path | None = None,
    uncertainty_path: str | Path | None = None,
    quality_path: str | Path | None = None,
    glt_path: str | Path | None = None,
    margin_px: int = 10,
    uncertainty_of: Literal["truth", "score"] = "truth",
    retrieval_sigma_ppm_m: float | None = None,
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
    clock: TimeAxis | None = None,
    name: str = "EMIT",
) -> PlumeScene:
    """One catalogued plume of an EMIT scene as a ``PlumeScene``.

    yₙ = κ Eₙ, Aₙ from the sensitivity raster, and σₙ = κ Aₙ uₙ
    (``"truth"``) or σₙ = κ uₙ (``"score"``), with κ the ppm m to kg m⁻²
    factor of :func:`ppm_m_to_column_mass`.

    Algorithm:
        1. Open the enhancement with its companions, and the outlines.
        2. Select the plume; crop to its bounding box plus the margin.
        3. Convert the enhancement and its noise to column mass.
        4. Build the mask from the fill values, the sensitivity and the
           quality raster.
        5. Project receptors, origin and outline into the local frame.
        6. Take the pixel side and the starting direction from them.

    The stored enhancement is the raw matched-filter score, so it is
    converted but never divided by the sensitivity. A pixel is masked
    (ωₙ = 0) when its enhancement, sensitivity or uncertainty is missing,
    its sensitivity is not positive, or the quality raster flags it as
    cloud, cirrus, water (``geoops.qa.EMITL2AMask``) or saturated
    (``geoops.qa.EMITBandMask``, dilated by 10 pixels). A masked pixel stays
    in the arrays with yₙ = 0, Aₙ = 1 and the median σₙ² of the kept pixels,
    so the window keeps its pixels for plotting; a pixel with no location,
    or with none of the three fields, is dropped. The DAAC plume files carry
    no pseudo-origin; the brightest in-plume pixel stands in for it then.

    Args:
        enhancement_path: Enhancement raster E [ppm m] (NetCDF, see
            ``xrproducts.open_emit_ch4_l2b``).
        outlines_path: Plume-complex GeoJSON.
        plume_id: Identifier of the plume to load.
        frame: Local metre frame of the analysis.
        sensitivity_path: Sensitivity raster A; ``None`` sets A = 1.
        uncertainty_path: Uncertainty raster u [ppm m].
        quality_path: EMIT L2A MASK NetCDF (``mask`` and, if present,
            ``band_mask``) in swath geometry; flagged pixels get ω = 0.
            Needs the ``geo`` extra.
        glt_path: Geometric lookup table, for swath-geometry rasters; the
            quality flags are decoded in swath geometry and go through it too.
        margin_px: Margin around the outline's bounding box, in pixels.
        uncertainty_of: Whether u is the noise of the enhancement divided
            by the sensitivity (``"truth"``) or of the raw score.
        retrieval_sigma_ppm_m: Constant u for files without an
            uncertainty raster.
        pressure_pa: Near-surface pressure p [Pa] for the conversion.
        temperature_k: Near-surface temperature T [K] for the conversion.
        clock: Sets the instrument's observation time.
        name: Instrument name.

    Returns:
        The :class:`PlumeScene`.

    Raises:
        MissingExtraError: If the ``io`` extra is not installed, or the
            ``geo`` extra when a quality raster is given.
        MissingVariableError: If ``plume_id`` is not in the file (the
            message lists the identifiers it has), or there is neither an
            uncertainty raster nor ``retrieval_sigma_ppm_m``.
        GridMismatchError: If the outline's bounding box leaves the scene,
            or the quality raster is not on the scene's grid.
        ScreeningError: If no pixel survives the mask.
        ParameterError: If ``margin_px`` is negative or ``uncertainty_of``
            is unknown.
        DomainError: If the plume's centroid is within a pixel of its origin.

    Examples:
        On the files a catalogue lists for one plume::

            scene = load_emit_plume_complex(
                "scene_CH4ENH.nc",
                "plume_complexes.json",
                plume_id="CH4_PlumeComplex-1234",
                frame=frame,
                sensitivity_path="scene_CH4SENS.nc",
                uncertainty_path="scene_CH4UNCERT.nc",
            )
            scene.instrument.averaging_kernel  # Aₙ, shape (N_Ωy,)
    """
    require_positive("margin_px", margin_px, allow_zero=True)
    if uncertainty_of not in ("truth", "score"):
        raise ParameterError(
            f"uncertainty_of must be 'truth' or 'score', got {uncertainty_of!r}"
        )
    xrproducts, _ = _readers()

    # --- read ---
    dataset = xrproducts.open_emit_ch4_l2b(
        enhancement_path,
        sensitivity_path=sensitivity_path,
        uncertainty_path=uncertainty_path,
        glt_path=glt_path,
    )
    plumes = xrproducts.open_ch4_plume_complexes(outlines_path)
    ids = [str(value) for value in plumes["plume"].values]
    if plume_id not in ids:
        raise MissingVariableError(
            f"load_emit_plume_complex: {plume_id!r} is not in {outlines_path!s}; "
            f"it has {ids}"
        )
    if "ch4_uncertainty" not in dataset and retrieval_sigma_ppm_m is None:
        raise MissingVariableError(
            "load_emit_plume_complex: no uncertainty raster; pass "
            "`uncertainty_path` or `retrieval_sigma_ppm_m`"
        )
    enhancement = _raster(dataset["ch4_enhancement"])
    lat, lon = _raster(dataset["lat"]), _raster(dataset["lon"])
    dtype = enhancement.dtype
    if "ch4_sensitivity" in dataset:
        sensitivity = _raster(dataset["ch4_sensitivity"])
    else:
        sensitivity = np.ones_like(enhancement)
    if "ch4_uncertainty" in dataset:
        uncertainty = _raster(dataset["ch4_uncertainty"])
    else:
        uncertainty = np.full_like(enhancement, retrieval_sigma_ppm_m)
    flags = np.zeros(enhancement.shape, dtype=np.int32)
    if quality_path is not None:
        flags = _quality_flags(quality_path, glt_path, enhancement.shape)

    # --- window ---
    # the outline as (lon, lat) rows
    ring = xrproducts.plume_outline(plumes, plume_id)
    rows, cols = _window(ring, lat, lon, margin_px)
    window = (slice(*rows), slice(*cols))
    fields = {
        "enhancement": enhancement[window],
        "sensitivity": sensitivity[window],
        "uncertainty": uncertainty[window],
        "lat": lat[window],
        "lon": lon[window],
        "flags": flags[window],
    }

    # --- convert ---
    # κ, ppm m → kg m⁻²
    mass_per_ppm_m = float(
        ppm_m_to_column_mass(1.0, pressure_pa=pressure_pa, temperature_k=temperature_k)
    )
    # yₙ = κ Eₙ
    column_mass = (mass_per_ppm_m * fields["enhancement"]).astype(dtype)
    if uncertainty_of == "truth":
        # σₙ = κ Aₙ uₙ
        obs_noise_std = mass_per_ppm_m * fields["sensitivity"] * fields["uncertainty"]
    else:
        # σₙ = κ uₙ
        obs_noise_std = mass_per_ppm_m * fields["uncertainty"]

    # --- mask ---
    keep, mask = _pixel_mask(
        column_mass,
        fields["sensitivity"],
        obs_noise_std,
        fields["lat"],
        fields["lon"],
    )
    mask &= fields["flags"] == 0
    kept = _kept_pixels(
        column_mass,
        fields["sensitivity"],
        obs_noise_std,
        mask,
        keep,
        fields["flags"],
    )

    # --- geometry ---
    # sₙ = (xₙ, yₙ) in the frame
    easting, northing = frame.to_xy(fields["lat"], fields["lon"])
    pixel_size = _pixel_size(easting, northing)
    receptors = einx.id("p, p -> p (1 + 1)", easting[keep], northing[keep])
    outline_x, outline_y = frame.to_xy(ring[:, 1], ring[:, 0])
    outline = einx.id("v, v -> v (1 + 1)", outline_x, outline_y)
    in_plume = _inside(receptors, outline)
    origin = _origin(plumes, plume_id, frame, receptors, kept, in_plume)
    direction = _direction(receptors, kept, in_plume, origin, pixel_size)
    row_index, col_index = np.nonzero(keep)
    pixel_index = einx.id("p, p -> p (1 + 1)", row_index, col_index)

    observation = _column_observation(
        name,
        receptors,
        kept["kernel"],
        kept["variance"],
        kept["enhancement"],
        _scene_time(dataset),
        clock,
        flags=kept["flags"],
        mask=kept["mask"].astype(dtype),
    )
    return PlumeScene(
        observation=observation,
        origin=jnp.asarray(origin),
        outline=jnp.asarray(outline),
        in_plume=jnp.asarray(in_plume),
        direction=jnp.asarray(direction),
        pixel_index=jnp.asarray(pixel_index),
        plume_id=plume_id,
        pixel_size=pixel_size,
        window=(*rows, *cols),
    )

matched_filter_scene

matched_filter_scene(score: Float[ndarray, 'row col'], score_std: Float[ndarray, 'row col'] | float, *, lat: Float[ndarray, 'row col'], lon: Float[ndarray, 'row col'], frame: LocalFrame, sensitivity: Float[ndarray, 'row col'] | None = None, exclude: Bool[ndarray, 'row col'] | None = None, unit: Literal['mol_m2', 'ppm_m', 'kg_m2'] = 'mol_m2', pressure_pa: float = P_STANDARD, temperature_k: float = T_STANDARD, name: str = 'EMIT') -> ColumnObservation

A ColumnObservation from radtrax's score, noise and sensitivity maps.

yₙ = M α̂ₙ and σₙ = M σ_α,n for a score in mol m⁻², with M the molar mass of methane; Aₙ is the sensitivity, or 1. A scalar score_std is the noise of every pixel.

The noise is that of the raw score (radtrax's score_std), so it is not multiplied by the sensitivity. For unit="ppm_m" the factor is κ of :func:ppm_m_to_column_mass, and for "kg_m2" it is 1. Pixels with a missing value or location, a non-positive sensitivity or set in exclude get ω = 0 (with y = 0, A = 1 and the median σ² of the kept pixels); pixels with no location or none of the fields are dropped.

Parameters:

Name Type Description Default
score Float[ndarray, 'row col']

Matched-filter score α̂ in unit.

required
score_std Float[ndarray, 'row col'] | float

Its standard deviation σ_α, per pixel or one for all.

required
lat Float[ndarray, 'row col']

Pixel-centre latitudes [degrees].

required
lon Float[ndarray, 'row col']

Pixel-centre longitudes [degrees].

required
frame LocalFrame

Local metre frame of the analysis.

required
sensitivity Float[ndarray, 'row col'] | None

Sensitivity A; None sets A = 1.

None
exclude Bool[ndarray, 'row col'] | None

Pixels to mask out, such as geoops.qa masks.

None
unit Literal['mol_m2', 'ppm_m', 'kg_m2']

Unit of score and score_std.

'mol_m2'
pressure_pa float

Near-surface pressure p [Pa], for "ppm_m".

P_STANDARD
temperature_k float

Near-surface temperature T [K], for "ppm_m".

T_STANDARD
name str

Instrument name.

'EMIT'

Returns:

Name Type Description
The ColumnObservation

class:ColumnObservation, with time NaT.

Raises:

Type Description
UnitsError

If unit is not one of the three.

ScreeningError

If no pixel survives the mask.

Examples:

>>> import numpy as np
>>> from plumax.met import LocalFrame
>>> frame = LocalFrame.at(31.95, -102.15)
>>> lat, lon = frame.to_latlon(*np.meshgrid([0.0, 60.0], [0.0, 60.0]))
>>> observation = matched_filter_scene(
...     np.full((2, 2), 0.01), 0.002, lat=lat, lon=lon, frame=frame
... )
>>> observation.enhancement.tolist()  # M α̂ = 0.0160425 × 0.01
[0.000160425, 0.000160425, 0.000160425, 0.000160425]
Source code in src/plumax/obs/_src/plume_scene.py
def matched_filter_scene(
    score: Float[np.ndarray, "row col"],
    score_std: Float[np.ndarray, "row col"] | float,
    *,
    lat: Float[np.ndarray, "row col"],
    lon: Float[np.ndarray, "row col"],
    frame: LocalFrame,
    sensitivity: Float[np.ndarray, "row col"] | None = None,
    exclude: Bool[np.ndarray, "row col"] | None = None,
    unit: Literal["mol_m2", "ppm_m", "kg_m2"] = "mol_m2",
    pressure_pa: float = P_STANDARD,
    temperature_k: float = T_STANDARD,
    name: str = "EMIT",
) -> ColumnObservation:
    """A ``ColumnObservation`` from radtrax's score, noise and sensitivity maps.

    yₙ = M α̂ₙ and σₙ = M σ_α,n for a score in mol m⁻², with M the molar
    mass of methane; Aₙ is the sensitivity, or 1. A scalar ``score_std`` is
    the noise of every pixel.

    The noise is that of the raw score (radtrax's ``score_std``), so it is
    not multiplied by the sensitivity. For ``unit="ppm_m"`` the factor is κ
    of :func:`ppm_m_to_column_mass`, and for ``"kg_m2"`` it is 1. Pixels
    with a missing value or location, a non-positive sensitivity or set in
    ``exclude`` get ω = 0 (with y = 0, A = 1 and the median σ² of the kept
    pixels); pixels with no location or none of the fields are dropped.

    Args:
        score: Matched-filter score α̂ in ``unit``.
        score_std: Its standard deviation σ_α, per pixel or one for all.
        lat: Pixel-centre latitudes [degrees].
        lon: Pixel-centre longitudes [degrees].
        frame: Local metre frame of the analysis.
        sensitivity: Sensitivity A; ``None`` sets A = 1.
        exclude: Pixels to mask out, such as ``geoops.qa`` masks.
        unit: Unit of ``score`` and ``score_std``.
        pressure_pa: Near-surface pressure p [Pa], for ``"ppm_m"``.
        temperature_k: Near-surface temperature T [K], for ``"ppm_m"``.
        name: Instrument name.

    Returns:
        The :class:`ColumnObservation`, with ``time`` ``NaT``.

    Raises:
        UnitsError: If ``unit`` is not one of the three.
        ScreeningError: If no pixel survives the mask.

    Examples:
        >>> import numpy as np
        >>> from plumax.met import LocalFrame
        >>> frame = LocalFrame.at(31.95, -102.15)
        >>> lat, lon = frame.to_latlon(*np.meshgrid([0.0, 60.0], [0.0, 60.0]))
        >>> observation = matched_filter_scene(
        ...     np.full((2, 2), 0.01), 0.002, lat=lat, lon=lon, frame=frame
        ... )
        >>> observation.enhancement.tolist()  # M α̂ = 0.0160425 × 0.01
        [0.000160425, 0.000160425, 0.000160425, 0.000160425]
    """
    if unit == "mol_m2":
        # yₙ = M α̂ₙ
        factor = M_CH4
    elif unit == "ppm_m":
        # yₙ = κ α̂ₙ
        factor = float(
            ppm_m_to_column_mass(
                1.0, pressure_pa=pressure_pa, temperature_k=temperature_k
            )
        )
    elif unit == "kg_m2":
        factor = 1.0
    else:
        raise UnitsError(
            f"matched_filter_scene: unit must be 'mol_m2', 'ppm_m' or 'kg_m2', "
            f"got {unit!r}"
        )
    values = np.asarray(score)
    dtype = np.result_type(values.dtype, np.float32)
    column_mass = (factor * values).astype(dtype)
    # σₙ = M σ_α,n
    obs_noise_std = factor * np.broadcast_to(
        np.asarray(score_std, dtype=dtype), values.shape
    )
    gain = (
        np.ones_like(column_mass)
        if sensitivity is None
        else np.asarray(sensitivity, dtype=dtype)
    )
    lat, lon = np.asarray(lat), np.asarray(lon)
    keep, mask = _pixel_mask(column_mass, gain, obs_noise_std, lat, lon)
    flags = np.zeros(values.shape, dtype=np.int32)
    if exclude is not None:
        excluded = np.asarray(exclude, dtype=bool)
        flags = np.where(excluded, int(QualityFlag.CLOUD), 0).astype(np.int32)
        mask &= ~excluded
    kept = _kept_pixels(column_mass, gain, obs_noise_std, mask, keep, flags)
    easting, northing = frame.to_xy(lat, lon)
    receptors = einx.id("p, p -> p (1 + 1)", easting[keep], northing[keep])
    return _column_observation(
        name,
        receptors,
        kept["kernel"],
        kept["variance"],
        kept["enhancement"],
        np.datetime64("NaT"),
        None,
        flags=kept["flags"],
        mask=kept["mask"].astype(dtype),
    )