Skip to content

Plume

Trace-gas retrieval post-processing for methane / CO₂ plumes — SBMP retrieval, detection masks, footprint vectorisation, integrated mass enhancement, and cross-sectional flux. Algorithm sources are cited in the operator docstrings (Varon et al., Frankenberg et al., Krings et al.).

  • Retrieval: SBMP (Sentinel-2 SWIR ratio, Varon 2021)
  • Detection / segmentation: PlumeMask, PlumeContours, PlumeFootprint (polygons from georeader.vectorize.get_polygons, measure.DEFAULT_REGIONPROPS metadata in pixel units)
  • Instance QA: PlumeShapeFilter (fiber-shape morphology gate), PlumeColumnStats (in-mask vs background statistics), PlumeQNDFeatures (quantile-normality-deviation features)
  • Quantification: ColumnToMass, IMEEstimate, CrossSectionalFlux, WindAdvectionCone
  • Tier-A primitives: plume_mask, convert_column_units, wind_advection_cone

Second carriers are positional call arguments on the primary carrier's pixel grid, never constructor kwargs (see Multi-input operators): IMEEstimate(wind_speed=3.5)(kg_m2, plume_mask), CrossSectionalFlux(...)(kg_m2, plume_mask), PlumeFootprint()(mask, kg_m2), SBMP()(scene, reference_scene), PlumeColumnStats()(labels, column), PlumeQNDFeatures()(labels, column, albedo).

geoops.plume

Trace-gas plume detection, footprints, and emission estimators.

ColumnToMass

Bases: Operator

Convert column enhancement units (ppm m / mol m^-2 / kg m^-2).

Thin wrapper over :func:convert_column_units. The ppm m conversion assumes a standard molar volume (298.15 K, 1 atm); see that function's docstring for the exact relation and caveats. Nodata pixels (non-finite or equal to the fill value) are not converted: they hold NaN and the output declares fill_value=NaN (a converted column is a new quantity, so the input's fill -- e.g. -9999 ppm m -- is not carried over).

Parameters:

Name Type Description Default
gas str

"CH4" (default) or "CO2".

'CH4'
units_in ColumnUnit

Units of the input carrier.

'ppm_m'
units_out ColumnUnit

Desired output units.

'kg_m2'

Examples:

>>> kg_m2 = gz.plume.ColumnToMass(
...     gas="CH4", units_in="ppm_m", units_out="kg_m2",
... )(enhancement)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class ColumnToMass(Operator):
    """Convert column enhancement units (ppm m / mol m^-2 / kg m^-2).

    Thin wrapper over :func:`convert_column_units`. The ppm m conversion
    assumes a standard molar volume (298.15 K, 1 atm); see that
    function's docstring for the exact relation and caveats. Nodata
    pixels (non-finite or equal to the fill value) are not converted:
    they hold ``NaN`` and the output declares ``fill_value=NaN``
    (a converted column is a new quantity, so the input's fill -- e.g.
    ``-9999`` ppm m -- is not carried over).

    Args:
        gas: ``"CH4"`` (default) or ``"CO2"``.
        units_in: Units of the input carrier.
        units_out: Desired output units.

    Examples:
        >>> kg_m2 = gz.plume.ColumnToMass(
        ...     gas="CH4", units_in="ppm_m", units_out="kg_m2",
        ... )(enhancement)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(
        self,
        *,
        gas: str = "CH4",
        units_in: ColumnUnit = "ppm_m",
        units_out: ColumnUnit = "kg_m2",
    ) -> None:
        self.gas = gas
        self.units_in = units_in
        self.units_out = units_out

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = convert_column_units(
            np.asarray(gt),
            gas=self.gas,
            units_in=self.units_in,
            units_out=self.units_out,
        )
        if np.ndim(out) < 2:
            return wrap_like(gt, out)
        out = np.asarray(out, dtype=np.result_type(out, np.float32))
        return wrap_filled(gt, out, fill_value=np.nan)

CrossSectionalFlux

Bases: Operator

Estimate cross-sectional flux at downwind transects.

For each transect at downwind distance :math:d_k, the operator integrates column mass across the plume:

.. math::

Q_k \;=\; U \int_{-\infty}^{\infty}
               \Omega(d_k, y) \, dy
    \;\approx\; U \sum_{i \in \mathrm{strip}_k}
               \Omega_i \,\Delta y_i

where :math:\mathrm{strip}_k is the set of plume pixels whose along-wind distance to the source falls within half a pixel of :math:d_k. This is the cross-section method of Krings et al. (2011) and Varon et al. (2018, appendix); a flat downwind profile of :math:Q_k versus :math:d_k confirms a steady-state estimate.

The enhancement carrier MUST be in kg/m^2 (see :class:ColumnToMass). Nodata enhancement pixels (non-finite or equal to the fill value) add nothing to a transect's flux. The implementation assumes (approximately) square pixels: it uses :math:\Delta y = \sqrt{\mathrm{pixel\_area}} as the across-wind pixel size. For strongly anisotropic pixel grids, reproject first.

Geo-dependent: transect placement and pixel size come from the carrier's transform and CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError) in a projected CRS with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Called as op(enhancement, plume_mask): plume_mask is a boolean plume carrier on the enhancement's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
source tuple[float, float]

(x, y) source coordinates in the carrier CRS (m).

required
wind_u float

Eastward wind component (m/s).

required
wind_v float

Northward wind component (m/s).

required
n_transects int

Number of downwind transects to evaluate.

5
transect_spacing_m float

Along-wind distance between transects (m).

100.0

Returns:

Type Description
GeoDataFrame

One row per transect: geometry (across-wind LineString), transect_id, distance_m, flux_kg_s, n_pixels.

Examples:

Evaluate fluxes at 100 m, 200 m, 300 m downwind::

gdf = gz.plume.CrossSectionalFlux(
    source=(x0, y0),
    wind_u=3.0, wind_v=1.0,
    n_transects=3, transect_spacing_m=100.0,
)(kg_m2, mask)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class CrossSectionalFlux(Operator):
    r"""Estimate cross-sectional flux at downwind transects.

    For each transect at downwind distance :math:`d_k`, the operator
    integrates column mass across the plume:

    .. math::

        Q_k \;=\; U \int_{-\infty}^{\infty}
                       \Omega(d_k, y) \, dy
            \;\approx\; U \sum_{i \in \mathrm{strip}_k}
                       \Omega_i \,\Delta y_i

    where :math:`\mathrm{strip}_k` is the set of plume pixels whose
    along-wind distance to the source falls within half a pixel of
    :math:`d_k`. This is the cross-section method of Krings et al. (2011)
    and Varon et al. (2018, appendix); a flat downwind profile of
    :math:`Q_k` versus :math:`d_k` confirms a steady-state estimate.

    The enhancement carrier MUST be in kg/m^2 (see :class:`ColumnToMass`).
    Nodata enhancement pixels (non-finite or equal to the fill value) add
    nothing to a transect's flux.
    The implementation assumes (approximately) square pixels: it uses
    :math:`\Delta y = \sqrt{\mathrm{pixel\_area}}` as the across-wind
    pixel size. For strongly anisotropic pixel grids, reproject first.

    Geo-dependent: transect placement and pixel size come from the
    carrier's transform and CRS, so the input must be a georeferenced
    ``GeoArray`` (plain arrays raise ``TypeError``) in a projected CRS
    with metre units; a geographic CRS raises ``ValueError`` (reproject
    with :class:`geoops.geom.Reproject` first).

    Called as ``op(enhancement, plume_mask)``: ``plume_mask`` is a boolean
    plume carrier on the enhancement's pixel grid (``ValueError``
    otherwise).

    Args:
        source: ``(x, y)`` source coordinates in the carrier CRS (m).
        wind_u: Eastward wind component (m/s).
        wind_v: Northward wind component (m/s).
        n_transects: Number of downwind transects to evaluate.
        transect_spacing_m: Along-wind distance between transects (m).

    Returns:
        geopandas.GeoDataFrame: One row per transect: ``geometry``
            (across-wind ``LineString``), ``transect_id``,
            ``distance_m``, ``flux_kg_s``, ``n_pixels``.

    Examples:
        Evaluate fluxes at 100 m, 200 m, 300 m downwind::

            gdf = gz.plume.CrossSectionalFlux(
                source=(x0, y0),
                wind_u=3.0, wind_v=1.0,
                n_transects=3, transect_spacing_m=100.0,
            )(kg_m2, mask)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        source: tuple[float, float],
        wind_u: float,
        wind_v: float,
        n_transects: int = 5,
        transect_spacing_m: float = 100.0,
    ) -> None:
        self.source = as_tuple(source)
        self.wind_u = wind_u
        self.wind_v = wind_v
        self.n_transects = n_transects
        self.transect_spacing_m = transect_spacing_m

    def _apply(
        self, gt: GeoArray, plume_mask: GeoArray | np.ndarray
    ) -> gpd.GeoDataFrame:
        LineString = optional_name(
            "shapely.geometry",
            "LineString",
            "vector",
            feature="geoops.plume.CrossSectionalFlux",
        )
        gpd = optional_module(
            "geopandas", "vector", feature="geoops.plume.CrossSectionalFlux"
        )
        require_ndim(gt, (2, 3), "CrossSectionalFlux")
        require_geoarray(gt, "CrossSectionalFlux")
        require_projected_crs(gt, "CrossSectionalFlux")
        require_grid_match(
            gt, plume_mask, "CrossSectionalFlux", names=("enhancement", "plume_mask")
        )
        wind_norm = float(np.hypot(self.wind_u, self.wind_v))
        if wind_norm == 0.0:
            raise ValueError("wind vector must be non-zero")
        mask = squeeze_single_band(
            np.asarray(plume_mask), name="CrossSectionalFlux"
        ).astype(bool)
        enhancement = _single_band_nan(gt, name="CrossSectionalFlux")
        area = pixel_area(affine_of(gt))
        width = float(np.sqrt(area))
        xs, ys = pixel_centers(mask.shape, affine_of(gt))
        dx = xs - self.source[0]
        dy = ys - self.source[1]
        along = (dx * self.wind_u + dy * self.wind_v) / wind_norm
        across = (-dx * self.wind_v + dy * self.wind_u) / wind_norm
        rows: list[dict[str, Any]] = []
        for idx in range(self.n_transects):
            distance = (idx + 1) * self.transect_spacing_m
            on_transect = mask & (np.abs(along - distance) <= width / 2.0)
            flux = float(np.nansum(enhancement[on_transect] * wind_norm * width))
            half_len = max(
                float(np.max(np.abs(across[mask]))) if mask.any() else width,
                width,
            )
            cx = self.source[0] + (self.wind_u / wind_norm) * distance
            cy = self.source[1] + (self.wind_v / wind_norm) * distance
            px = -self.wind_v / wind_norm
            py = self.wind_u / wind_norm
            line = LineString(
                [
                    (cx - px * half_len, cy - py * half_len),
                    (cx + px * half_len, cy + py * half_len),
                ]
            )
            rows.append(
                {
                    "geometry": line,
                    "transect_id": idx + 1,
                    "distance_m": float(distance),
                    "flux_kg_s": flux,
                    "n_pixels": int(on_transect.sum()),
                }
            )
        return gpd.GeoDataFrame(rows, geometry="geometry", crs=gt.crs)

IMEEstimate

Bases: Operator

Integrated Mass Enhancement (IME) flux estimator.

Implements the IME method of Varon et al. (2018), AMT Quantifying methane point sources from fine-scale satellite observations of atmospheric methane plumes:

.. math::

\mathrm{IME} \;=\; \sum_{i \in \mathrm{plume}}
                    \Omega_i \,\Delta A_i, \qquad
Q \;=\; \frac{U_{\mathrm{eff}}\,\mathrm{IME}}{L}

where :math:\Omega_i is the column enhancement (kg/m^2) of pixel :math:i, :math:\Delta A_i is its area (m^2), :math:L is the effective plume length (m) — see :func:plume_length — and :math:U_{\mathrm{eff}} is the effective wind speed (m/s). Varon et al. (2018) calibrate :math:U_{\mathrm{eff}} against LES simulations; this operator takes the calibrated value as wind_speed.

The enhancement carrier MUST be in kg/m^2. Use :class:ColumnToMass upstream to convert from ppm m or mol/m^2: passing other units silently produces nonsense. Nodata enhancement pixels (non-finite or equal to the fill value) add nothing to the IME.

Geo-dependent: pixel area (m^2) and plume length (m) are derived from the carrier's transform, so the input must be a georeferenced GeoArray (plain arrays raise TypeError) in a projected CRS with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Called as op(enhancement, plume_mask): plume_mask is a boolean carrier selecting plume pixels on the enhancement's pixel grid (same shape, transform and CRS; ValueError otherwise -- a mask on another grid would be indexed against the wrong pixels).

Parameters:

Name Type Description Default
wind_speed float

Effective wind speed :math:U_{\mathrm{eff}} in m/s.

required
length_method Literal['max_axis', 'convex_hull', 'skeleton']

Length estimator: "max_axis", "convex_hull", or "skeleton". See :func:plume_length; "skeleton" raises ValueError for compact plumes whose skeleton collapses to a point.

'max_axis'
pixel_area_m2 float | None

Override the pixel area (m^2); default is the absolute input transform determinant in the projected CRS's metres (exact on an equal-area projection; on UTM it ignores the projection's scale factor, a < 0.1 % error near the central meridian).

None
return_uncertainty bool

Append emission_rate_uncertainty_kg_s.

True
uncertainty_fraction float

Fractional 1-sigma uncertainty on Q. The default 0.5 follows Varon et al. (2018) Table 3.

0.5

Returns:

Type Description
dict

Result with keys ime_kg, length_m, wind_speed_m_s, emission_rate_kg_s, and optionally emission_rate_uncertainty_kg_s.

Examples:

Estimate Q in kg/s from a ppm m enhancement map::

import geoops as gz

kg_m2 = gz.plume.ColumnToMass(units_in="ppm_m")(enhancement)
mask = gz.plume.PlumeMask(threshold="percentile:99")(kg_m2)
result = gz.plume.IMEEstimate(
    wind_speed=3.5,
    length_method="convex_hull",
)(kg_m2, mask)
print(result["emission_rate_kg_s"])
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class IMEEstimate(Operator):
    r"""Integrated Mass Enhancement (IME) flux estimator.

    Implements the IME method of Varon et al. (2018), AMT
    *Quantifying methane point sources from fine-scale satellite
    observations of atmospheric methane plumes*:

    .. math::

        \mathrm{IME} \;=\; \sum_{i \in \mathrm{plume}}
                            \Omega_i \,\Delta A_i, \qquad
        Q \;=\; \frac{U_{\mathrm{eff}}\,\mathrm{IME}}{L}

    where :math:`\Omega_i` is the column enhancement (kg/m^2) of pixel
    :math:`i`, :math:`\Delta A_i` is its area (m^2), :math:`L` is the
    effective plume length (m) — see :func:`plume_length` — and
    :math:`U_{\mathrm{eff}}` is the effective wind speed (m/s). Varon
    et al. (2018) calibrate :math:`U_{\mathrm{eff}}` against LES
    simulations; this operator takes the calibrated value as
    ``wind_speed``.

    The ``enhancement`` carrier MUST be in kg/m^2. Use
    :class:`ColumnToMass` upstream to convert from ppm m or mol/m^2:
    passing other units silently produces nonsense. Nodata enhancement
    pixels (non-finite or equal to the fill value) add nothing to the IME.

    Geo-dependent: pixel area (m^2) and plume length (m) are derived from
    the carrier's transform, so the input must be a georeferenced
    ``GeoArray`` (plain arrays raise ``TypeError``) in a projected CRS
    with metre units; a geographic CRS raises ``ValueError`` (reproject
    with :class:`geoops.geom.Reproject` first).

    Called as ``op(enhancement, plume_mask)``: ``plume_mask`` is a boolean
    carrier selecting plume pixels on the enhancement's pixel grid (same
    shape, transform and CRS; ``ValueError`` otherwise -- a mask on another
    grid would be indexed against the wrong pixels).

    Args:
        wind_speed: Effective wind speed :math:`U_{\mathrm{eff}}` in m/s.
        length_method: Length estimator: ``"max_axis"``, ``"convex_hull"``,
            or ``"skeleton"``. See :func:`plume_length`; ``"skeleton"``
            raises ``ValueError`` for compact plumes whose skeleton
            collapses to a point.
        pixel_area_m2: Override the pixel area (m^2); default is the
            absolute input transform determinant in the projected CRS's
            metres (exact on an equal-area projection; on UTM it ignores
            the projection's scale factor, a < 0.1 % error near the
            central meridian).
        return_uncertainty: Append ``emission_rate_uncertainty_kg_s``.
        uncertainty_fraction: Fractional 1-sigma uncertainty on Q. The
            default 0.5 follows Varon et al. (2018) Table 3.

    Returns:
        dict: Result with keys ``ime_kg``, ``length_m``,
            ``wind_speed_m_s``, ``emission_rate_kg_s``, and optionally
            ``emission_rate_uncertainty_kg_s``.

    Examples:
        Estimate Q in kg/s from a ppm m enhancement map::

            import geoops as gz

            kg_m2 = gz.plume.ColumnToMass(units_in="ppm_m")(enhancement)
            mask = gz.plume.PlumeMask(threshold="percentile:99")(kg_m2)
            result = gz.plume.IMEEstimate(
                wind_speed=3.5,
                length_method="convex_hull",
            )(kg_m2, mask)
            print(result["emission_rate_kg_s"])
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        wind_speed: float,
        length_method: Literal["max_axis", "convex_hull", "skeleton"] = "max_axis",
        pixel_area_m2: float | None = None,
        return_uncertainty: bool = True,
        uncertainty_fraction: float = 0.5,
    ) -> None:
        self.wind_speed = wind_speed
        self.length_method = length_method
        self.pixel_area_m2 = pixel_area_m2
        self.return_uncertainty = return_uncertainty
        if uncertainty_fraction < 0.0:
            raise ValueError("uncertainty_fraction must be non-negative")
        self.uncertainty_fraction = uncertainty_fraction

    def _apply(
        self, gt: GeoArray, plume_mask: GeoArray | np.ndarray
    ) -> dict[str, float]:
        require_ndim(gt, (2, 3), "IMEEstimate")
        require_geoarray(gt, "IMEEstimate")
        require_projected_crs(gt, "IMEEstimate")
        require_grid_match(
            gt, plume_mask, "IMEEstimate", names=("enhancement", "plume_mask")
        )
        mask = squeeze_single_band(np.asarray(plume_mask), name="IMEEstimate").astype(
            bool
        )
        enhancement = _single_band_nan(gt, name="IMEEstimate")
        area = (
            self.pixel_area_m2
            if self.pixel_area_m2 is not None
            else pixel_area(affine_of(gt))
        )
        ime_kg = float(np.nansum(enhancement[mask] * area))
        length_m = plume_length(mask, affine_of(gt), method=self.length_method)
        rate = 0.0 if length_m == 0.0 else ime_kg * self.wind_speed / length_m
        out = {
            "ime_kg": ime_kg,
            "length_m": float(length_m),
            "wind_speed_m_s": float(self.wind_speed),
            "emission_rate_kg_s": float(rate),
        }
        if self.return_uncertainty:
            out["emission_rate_uncertainty_kg_s"] = float(
                abs(rate) * self.uncertainty_fraction
            )
        return out

PlumeColumnStats

Bases: Operator

Per-instance in-mask vs background statistics of a column field.

Adapted from Pérez Carrasco et al. (2026), rfc_utils.xch4_metrics. For every non-zero label in the input map, returns a row with the in-mask mean, the out-of-mask (background) mean / std, and three derived metrics used by the paper's Random-Forest false-plume classifier:

  • contrast = mean_plume / mean_background
  • z_score = (mean_plume - mean_background) / std_background
  • intensity_per_area = (sum_plume - mean_background * n_plume) / n_plume

Nodata column pixels (non-finite or equal to the column carrier's fill value) are left out of every statistic.

Called as op(labels, column): column is the column field (single-band GeoArray or plain array) on the label map's pixel grid (ValueError otherwise).

Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeColumnStats(Operator):
    """Per-instance in-mask vs background statistics of a column field.

    Adapted from Pérez Carrasco et al. (2026), ``rfc_utils.xch4_metrics``.
    For every non-zero label in the input map, returns a row with the
    in-mask mean, the out-of-mask (background) mean / std, and three
    derived metrics used by the paper's Random-Forest false-plume
    classifier:

    - ``contrast`` = ``mean_plume / mean_background``
    - ``z_score`` = ``(mean_plume - mean_background) / std_background``
    - ``intensity_per_area`` = ``(sum_plume - mean_background * n_plume)
      / n_plume``

    Nodata column pixels (non-finite or equal to the column carrier's
    fill value) are left out of every statistic.

    Called as ``op(labels, column)``: ``column`` is the column field
    (single-band ``GeoArray`` or plain array) on the label map's pixel
    grid (``ValueError`` otherwise).
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def _apply(
        self, gt: GeoArray | np.ndarray, column: GeoArray | np.ndarray
    ) -> pd.DataFrame:
        reject_geotensor(gt, "PlumeColumnStats")
        require_ndim(gt, (2, 3), "PlumeColumnStats")
        require_grid_match(gt, column, "PlumeColumnStats", names=("labels", "column"))
        labels = squeeze_single_band(np.asarray(gt), name="PlumeColumnStats").astype(
            np.int64, copy=False
        )
        col_arr = _single_band_nan(column, name="PlumeColumnStats").astype(
            float, copy=False
        )
        if col_arr.shape != labels.shape:
            raise ValueError(
                "column shape "
                f"{col_arr.shape} does not match label shape {labels.shape}"
            )
        rows: list[dict[str, Any]] = []
        for lbl, compact, bbox in _iter_instances(labels):
            y0, x0, y1, x1 = bbox
            full_mask = np.zeros_like(col_arr, dtype=bool)
            full_mask[y0:y1, x0:x1] = compact
            mean_plume, bg_mean, bg_std, contrast, z_score, ipa = _in_out_mask_stats(
                col_arr, full_mask
            )
            rows.append(
                {
                    "label": lbl,
                    "area": int(compact.sum()),
                    "mean_enhancement": mean_plume,
                    "background_mean": bg_mean,
                    "background_std": bg_std,
                    "contrast": contrast,
                    "z_score": z_score,
                    "intensity_per_area": ipa,
                }
            )
        if not rows:
            return pd.DataFrame(
                columns=[
                    "label",
                    "area",
                    "mean_enhancement",
                    "background_mean",
                    "background_std",
                    "contrast",
                    "z_score",
                    "intensity_per_area",
                ]
            )
        return pd.DataFrame(rows)

PlumeContours

Bases: Operator

Connected-component labelling of a plume mask.

Returns either an int32 label image (default) or a boolean mask of the retained components. Component size threshold and connectivity follow :func:label_components.

Nodata pixels (non-finite -- e.g. a NaN score -- or equal to the input's fill value) are never part of a contour. In the boolean output they are False (fill_value=False). In the label image they hold the input's fill value when it is a non-positive int32 value (e.g. -9999, so it cannot collide with a label); otherwise (NaN, no fill, or a positive fill) they are 0 (background), and a GeoArray output then carries fill_value=0.

Examples:

>>> labels = gz.plume.PlumeContours(min_area_px=50)(mask)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeContours(Operator):
    """Connected-component labelling of a plume mask.

    Returns either an int32 label image (default) or a boolean mask of
    the retained components. Component size threshold and connectivity
    follow :func:`label_components`.

    Nodata pixels (non-finite -- e.g. a ``NaN`` score -- or equal to the
    input's fill value) are never part of a contour. In the boolean
    output they are ``False`` (``fill_value=False``). In the
    label image they hold the input's fill value when it is a
    non-positive int32 value (e.g. ``-9999``, so it cannot collide with
    a label); otherwise (``NaN``, no fill, or a
    positive fill) they are ``0`` (background), and a GeoArray output
    then carries ``fill_value=0``.

    Examples:
        >>> labels = gz.plume.PlumeContours(min_area_px=50)(mask)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # connected components
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        min_area_px: int = 50,
        return_labels: bool = True,
        connectivity: Connectivity = 8,
    ) -> None:
        self.min_area_px = min_area_px
        self.return_labels = return_labels
        self.connectivity = connectivity

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        valid = valid_pixels(gt)
        labels = label_components(
            squeeze_single_band(np.asarray(gt), name="PlumeContours").astype(bool)
            & valid,
            min_area_px=self.min_area_px,
            connectivity=self.connectivity,
        )
        if not self.return_labels:
            return wrap_like(gt, labels > 0, fill_value=False)
        # ``carried_fill`` is None unless the fill is an int32 value; a
        # positive fill would collide with a component label.
        fill = carried_fill(gt, labels.dtype)
        if fill is None or isinstance(fill, bool | np.bool_) or fill > 0:
            fill = 0
        return wrap_filled(gt, labels, fill_value=fill, valid=valid)

PlumeFootprint

Bases: Operator

Vectorize a plume mask into polygons with per-plume metadata.

The region properties come from the same machinery as :class:geoops.measure.RegionProps (defaults to :data:geoops.measure.DEFAULT_REGIONPROPS, pixel units) and the polygons from :func:georeader.vectorize.get_polygons. Returns a GeoDataFrame with one row per surviving plume: geometry, area_m2, centroid, mean_enhancement / max_enhancement (if enhancement is supplied), n_pixels, label_id, and skimage region properties such as major_axis_length, orientation, eccentricity, solidity, perimeter, bbox-*, and inertia_tensor_eigvals-*.

Nodata pixels of a boolean mask never form a polygon, non-positive labels are background, and nodata enhancement pixels are ignored by the per-polygon statistics.

Geo-dependent: polygonisation needs the carrier's transform and CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError). Areas are in m^2 and the simplify tolerance in m, so the CRS must be projected with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Parameters:

Name Type Description Default
min_area_m2 float

Drop polygons smaller than this area (m^2).

500.0
simplify_tolerance float | None

Douglas-Peucker tolerance (m) for polygon simplification; None to skip.

15.0
properties Sequence[str] | None

Region properties forwarded to regionprops_table.

None
extra_properties Sequence[Callable[..., Any]] | None

User-defined regionprops_table callables.

None

Called as op(mask, enhancement=None). The optional enhancement carrier must sit on the mask's pixel grid (ValueError otherwise); it enables the mean_enhancement / max_enhancement statistics per polygon.

Examples:

>>> gdf = gz.plume.PlumeFootprint(min_area_m2=500.0)(mask, kg_m2)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeFootprint(Operator):
    """Vectorize a plume mask into polygons with per-plume metadata.

    The region properties come from the same machinery as
    :class:`geoops.measure.RegionProps` (defaults to
    :data:`geoops.measure.DEFAULT_REGIONPROPS`, pixel units) and the
    polygons from :func:`georeader.vectorize.get_polygons`. Returns a
    ``GeoDataFrame`` with one row per surviving plume: ``geometry``, ``area_m2``,
    ``centroid``,
    ``mean_enhancement`` / ``max_enhancement`` (if ``enhancement`` is
    supplied), ``n_pixels``, ``label_id``, and skimage region properties such as
    ``major_axis_length``, ``orientation``, ``eccentricity``, ``solidity``,
    ``perimeter``, ``bbox-*``, and ``inertia_tensor_eigvals-*``.

    Nodata pixels of a boolean mask never form a polygon, non-positive
    labels are background, and nodata ``enhancement`` pixels are ignored
    by the per-polygon statistics.

    Geo-dependent: polygonisation needs the carrier's transform and CRS,
    so the input must be a georeferenced ``GeoArray`` (plain arrays
    raise ``TypeError``). Areas are in m^2 and the simplify tolerance in
    m, so the CRS must be projected with metre units; a geographic CRS
    raises ``ValueError`` (reproject with :class:`geoops.geom.Reproject`
    first).

    Args:
        min_area_m2: Drop polygons smaller than this area (m^2).
        simplify_tolerance: Douglas-Peucker tolerance (m) for polygon
            simplification; ``None`` to skip.
        properties: Region properties forwarded to ``regionprops_table``.
        extra_properties: User-defined ``regionprops_table`` callables.

    Called as ``op(mask, enhancement=None)``. The optional ``enhancement``
    carrier must sit on the mask's pixel grid (``ValueError`` otherwise);
    it enables the ``mean_enhancement`` / ``max_enhancement`` statistics
    per polygon.

    Examples:
        >>> gdf = gz.plume.PlumeFootprint(min_area_m2=500.0)(mask, kg_m2)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        min_area_m2: float = 500.0,
        simplify_tolerance: float | None = 15.0,
        properties: Sequence[str] | None = None,
        extra_properties: Sequence[Callable[..., Any]] | None = None,
    ) -> None:
        self.min_area_m2 = min_area_m2
        self.simplify_tolerance = simplify_tolerance
        self.properties = tuple(
            DEFAULT_REGIONPROPS if properties is None else properties
        )
        self.extra_properties = (
            None
            if extra_properties is None
            else tuple(
                reject_config_summary(f, "extra_properties") for f in extra_properties
            )
        )

    def _apply(
        self, gt: GeoArray, enhancement: GeoArray | np.ndarray | None = None
    ) -> gpd.GeoDataFrame:
        gpd = optional_module(
            "geopandas", "vector", feature="geoops.plume.PlumeFootprint"
        )
        unary_union = optional_name(
            "shapely.ops",
            "unary_union",
            "vector",
            feature="geoops.plume.PlumeFootprint",
        )
        vectorize = optional_name(
            "georeader",
            "vectorize",
            "sensors",
            feature="geoops.plume.PlumeFootprint",
        )
        require_ndim(gt, (2, 3), "PlumeFootprint")
        require_geoarray(gt, "PlumeFootprint")
        require_projected_crs(gt, "PlumeFootprint")
        if enhancement is not None:
            require_grid_match(
                gt, enhancement, "PlumeFootprint", names=("mask", "enhancement")
            )
        mask_arr = squeeze_single_band(np.asarray(gt), name="PlumeFootprint")
        if mask_arr.dtype == bool:
            labels = label_components(
                mask_arr & squeeze_single_band(valid_pixels(gt), name="PlumeFootprint"),
                min_area_px=1,
                connectivity=8,
            )
        else:
            # Non-positive labels (background, or a label image's fill
            # value such as -9999) are not plumes.
            labels = np.where(mask_arr > 0, mask_arr, 0).astype(np.int32, copy=False)
        enh = (
            None
            if enhancement is None
            else _single_band_nan(enhancement, name="PlumeFootprint")
        )
        properties = list(self.properties)
        if enh is not None:
            properties.extend(
                prop
                for prop in ("centroid_weighted", "mean_intensity", "max_intensity")
                if prop not in properties
            )
        props = regionprops_frame(
            labels,
            intensity_image=enh,
            properties=properties,
            extra_properties=self.extra_properties,
        )
        # Cast keys to int defensively: skimage returns numpy-int labels and
        # pandas to_dict("index") propagates that dtype. Python int hashes
        # equal in CPython but the explicit cast makes the lookup contract
        # obvious and survives dtype changes upstream.
        #
        # When the caller's ``properties`` omits ``"label"`` we still need a
        # per-component lookup, so synthesise it from ``regionprops_table``'s
        # row order (which mirrors ``sorted(unique(labels) - {0})``).
        if props.empty:
            props_by_label = {}
        else:
            if "label" in props.columns:
                indexed = props.set_index("label", drop=False)
            else:
                synthetic_labels = sorted(int(v) for v in np.unique(labels) if v != 0)
                indexed = props.copy()
                indexed.index = pd.Index(synthetic_labels[: len(indexed)])
            props_by_label = {int(k): v for k, v in indexed.to_dict("index").items()}

        rows: list[dict[str, Any]] = []
        for label_id in sorted(int(v) for v in np.unique(labels) if v != 0):
            component = labels == label_id
            n_pixels = int(component.sum())
            # One component can still vectorise to several 4-connected
            # polygons (diagonal-only contacts); union them.
            geometries = vectorize.get_polygons(
                component, min_area=0.0, tolerance=0.0, transform=affine_of(gt)
            )
            if not geometries:
                continue
            geometry = unary_union(geometries)
            if self.simplify_tolerance is not None:
                geometry = geometry.simplify(
                    self.simplify_tolerance, preserve_topology=True
                )
            area_m2 = float(geometry.area)
            if area_m2 < self.min_area_m2:
                continue
            component_values = None if enh is None else enh[component]
            region_props = props_by_label.get(label_id, {})

            # Bind region_props / component_values via default args to avoid
            # the late-binding closure trap that ruff B023 flags.
            def _nan_safe(
                reducer: Callable[[np.ndarray], float],
                key: str,
                rp: dict[str, Any] = region_props,
                vals: np.ndarray | None = component_values,
            ) -> float:
                # Prefer the regionprops_table value, but fall back to the
                # NaN-aware reducer when skimage propagates NaN through
                # ``mean_intensity`` / ``max_intensity`` (it does not ignore
                # NaNs internally). ``vals`` is non-None here.
                rp_val = rp.get(key)
                if rp_val is None or not np.isfinite(float(rp_val)):
                    return float(reducer(vals))
                return float(rp_val)

            mean_enhancement = (
                None
                if component_values is None
                else _nan_safe(np.nanmean, "mean_intensity")
            )
            max_enhancement = (
                None
                if component_values is None
                else _nan_safe(np.nanmax, "max_intensity")
            )
            rows.append(
                {
                    **region_props,
                    "geometry": geometry,
                    "area_m2": area_m2,
                    "centroid": geometry.centroid,
                    "mean_enhancement": mean_enhancement,
                    "max_enhancement": max_enhancement,
                    "n_pixels": n_pixels,
                    "label_id": label_id,
                }
            )
        if not rows:
            # No surviving components (empty mask, or all polygons filtered
            # out by ``min_area_m2``). Construct an empty GeoDataFrame with
            # the expected schema so downstream consumers see a stable
            # column layout instead of a constructor error.
            return gpd.GeoDataFrame(
                {
                    "geometry": [],
                    "area_m2": [],
                    "centroid": [],
                    "mean_enhancement": [],
                    "max_enhancement": [],
                    "n_pixels": [],
                    "label_id": [],
                },
                geometry="geometry",
                crs=gt.crs,
            )
        return gpd.GeoDataFrame(rows, geometry="geometry", crs=gt.crs)

    def get_config(self) -> dict[str, Any]:
        return {
            "min_area_m2": self.min_area_m2,
            "simplify_tolerance": self.simplify_tolerance,
            "properties": list(self.properties),
            "extra_properties": None
            if self.extra_properties is None
            else [{"callable": callable_name(f)} for f in self.extra_properties],
        }

PlumeMask

Bases: Operator

Binary plume mask from a single-band score or enhancement map.

Thresholds the input (absolute number, Otsu, or percentile) and drops connected components smaller than min_area_px pixels — the Frankenberg et al. (2016) detection convention, also used by Varon et al. (2018, 2021) for S2/AVIRIS plume identification.

Parameters:

Name Type Description Default
threshold ThresholdMode

float (absolute), "otsu", or "percentile:<p>" with p in [0, 100].

'otsu'
min_area_px int

Minimum component size in pixels.

50
connectivity Connectivity

4 or 8 connectivity for component labelling.

8
nbins int

Histogram bins for the "otsu" threshold (see :func:geoops.segment.otsu_threshold); ignored by the other modes. Default 256.

256

Nodata pixels (non-finite or equal to the input's fill value) are excluded from the Otsu / percentile threshold and are always False in the mask, which declares fill_value=False.

Examples:

>>> mask = gz.plume.PlumeMask(
...     threshold="percentile:99.5", min_area_px=50,
... )(enhancement)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeMask(Operator):
    """Binary plume mask from a single-band score or enhancement map.

    Thresholds the input (absolute number, Otsu, or percentile) and
    drops connected components smaller than ``min_area_px`` pixels — the
    Frankenberg et al. (2016) detection convention, also used by Varon
    et al. (2018, 2021) for S2/AVIRIS plume identification.

    Args:
        threshold: ``float`` (absolute), ``"otsu"``, or
            ``"percentile:<p>"`` with ``p`` in [0, 100].
        min_area_px: Minimum component size in pixels.
        connectivity: 4 or 8 connectivity for component labelling.
        nbins: Histogram bins for the ``"otsu"`` threshold (see
            :func:`geoops.segment.otsu_threshold`); ignored by the other modes.
            Default ``256``.

    Nodata pixels (non-finite or equal to the input's fill value) are
    excluded from the Otsu / percentile threshold and are always
    ``False`` in the mask, which declares ``fill_value=False``.

    Examples:
        >>> mask = gz.plume.PlumeMask(
        ...     threshold="percentile:99.5", min_area_px=50,
        ... )(enhancement)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a scene threshold, then connected components
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        threshold: ThresholdMode = "otsu",
        min_area_px: int = 50,
        connectivity: Connectivity = 8,
        nbins: int = 256,
    ) -> None:
        self.threshold = threshold
        self.min_area_px = min_area_px
        self.connectivity = connectivity
        self.nbins = nbins

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        mask = plume_mask(
            _single_band_nan(gt, name="PlumeMask"),
            threshold=self.threshold,
            min_area_px=self.min_area_px,
            connectivity=self.connectivity,
            nbins=self.nbins,
        )
        return wrap_like(gt, mask, fill_value=False)

PlumeQNDFeatures

Bases: Operator

Per-instance Quantile-Normality-Deviation features for plume QA.

Adapted from Pérez Carrasco et al. (2026) — the feature pipeline that feeds the Random-Forest false-plume classifier (rfc_utils.get_QND_df_cms / get_plume_info). For each non-zero label in the input map this operator emits one row containing:

  • qnd_column_* — polynomial coefficients of the Kolmogorov-Smirnov distance between the in-mask CDF of the column field and a Gaussian fit to the full scene's column distribution, sampled across 100 percentiles in [0.01, 0.99].
  • qnd_albedo_* — same construction over the optional albedo field.
  • n_clumps — DBSCAN cluster count of in-mask pixels above the perc_threshold percentile (per the paper's clump-count signal).
  • contrast / z_score / intensity_per_area — the same stats that :class:PlumeColumnStats emits, included so a single call assembles the full feature vector used by the paper.

Nodata column / albedo pixels (non-finite or equal to the carrier's fill value) are left out of every feature.

Called as op(labels, column, albedo=None): column is the column-enhancement carrier and albedo an optional albedo carrier, both on the label map's pixel grid (ValueError otherwise). Without albedo the qnd_albedo_* coefficients are NaN.

Parameters:

Name Type Description Default
degree int

Degree of the QND polynomial (paper default: 6).

6
eps float

DBSCAN eps (pixels).

50.0
min_samples int

DBSCAN min_samples.

50
perc_threshold float

Percentile (within the instance mask) above which pixels are eligible for clustering.

98.0
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeQNDFeatures(Operator):
    """Per-instance Quantile-Normality-Deviation features for plume QA.

    Adapted from Pérez Carrasco et al. (2026) — the feature pipeline that
    feeds the Random-Forest false-plume classifier
    (``rfc_utils.get_QND_df_cms`` / ``get_plume_info``). For each non-zero
    label in the input map this operator emits one row containing:

    - ``qnd_column_*`` — polynomial coefficients of the
      Kolmogorov-Smirnov distance between the in-mask CDF of the column
      field and a Gaussian fit to the full scene's column distribution,
      sampled across 100 percentiles in ``[0.01, 0.99]``.
    - ``qnd_albedo_*`` — same construction over the optional albedo field.
    - ``n_clumps`` — DBSCAN cluster count of in-mask pixels above the
      ``perc_threshold`` percentile (per the paper's clump-count signal).
    - ``contrast`` / ``z_score`` / ``intensity_per_area`` — the same stats
      that :class:`PlumeColumnStats` emits, included so a single call
      assembles the full feature vector used by the paper.

    Nodata column / albedo pixels (non-finite or equal to the carrier's
    fill value) are left out of every feature.

    Called as ``op(labels, column, albedo=None)``: ``column`` is the
    column-enhancement carrier and ``albedo`` an optional albedo carrier,
    both on the label map's pixel grid (``ValueError`` otherwise). Without
    ``albedo`` the ``qnd_albedo_*`` coefficients are NaN.

    Args:
        degree: Degree of the QND polynomial (paper default: 6).
        eps: DBSCAN ``eps`` (pixels).
        min_samples: DBSCAN ``min_samples``.
        perc_threshold: Percentile (within the instance mask) above which
            pixels are eligible for clustering.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        degree: int = 6,
        eps: float = 50.0,
        min_samples: int = 50,
        perc_threshold: float = 98.0,
    ) -> None:
        if degree < 1:
            raise ValueError("degree must be >= 1")
        if eps <= 0:
            raise ValueError("eps must be positive")
        if min_samples < 1:
            raise ValueError("min_samples must be >= 1")
        if not 0.0 < perc_threshold < 100.0:
            raise ValueError("perc_threshold must be in (0, 100)")
        self.degree = int(degree)
        self.eps = float(eps)
        self.min_samples = int(min_samples)
        self.perc_threshold = float(perc_threshold)

    def _apply(
        self,
        gt: GeoArray | np.ndarray,
        column: GeoArray | np.ndarray,
        albedo: GeoArray | np.ndarray | None = None,
    ) -> pd.DataFrame:
        reject_geotensor(gt, "PlumeQNDFeatures")
        require_ndim(gt, (2, 3), "PlumeQNDFeatures")
        require_grid_match(gt, column, "PlumeQNDFeatures", names=("labels", "column"))
        if albedo is not None:
            require_grid_match(
                gt, albedo, "PlumeQNDFeatures", names=("labels", "albedo")
            )
        labels = squeeze_single_band(np.asarray(gt), name="PlumeQNDFeatures").astype(
            np.int64, copy=False
        )
        col_arr = _single_band_nan(column, name="PlumeQNDFeatures").astype(
            float, copy=False
        )
        if col_arr.shape != labels.shape:
            raise ValueError(
                "column shape "
                f"{col_arr.shape} does not match label shape {labels.shape}"
            )
        if albedo is None:
            alb_arr = None
        else:
            alb_arr = _single_band_nan(albedo, name="PlumeQNDFeatures").astype(
                float, copy=False
            )
            if alb_arr.shape != labels.shape:
                raise ValueError(
                    "albedo shape "
                    f"{alb_arr.shape} does not match label shape {labels.shape}"
                )

        col_keys = [f"qnd_column_c{i}" for i in range(self.degree + 1)]
        alb_keys = [f"qnd_albedo_c{i}" for i in range(self.degree + 1)]
        rows: list[dict[str, Any]] = []
        for lbl, compact, bbox in _iter_instances(labels):
            y0, x0, y1, x1 = bbox
            full_mask = np.zeros_like(col_arr, dtype=bool)
            full_mask[y0:y1, x0:x1] = compact
            qnd_col = _qnd_polynomial(col_arr, full_mask, self.degree)
            qnd_alb = (
                _qnd_polynomial(alb_arr, full_mask, self.degree)
                if alb_arr is not None
                else np.full(self.degree + 1, np.nan)
            )
            n_clumps = _dbscan_clump_count(
                col_arr,
                full_mask,
                eps=self.eps,
                min_samples=self.min_samples,
                perc_threshold=self.perc_threshold,
            )
            _mp, _bm, _bs, contrast, z_score, ipa = _in_out_mask_stats(
                col_arr, full_mask
            )
            row: dict[str, Any] = {
                "label": lbl,
                "area": int(compact.sum()),
                "n_clumps": n_clumps,
                "contrast": contrast,
                "z_score": z_score,
                "intensity_per_area": ipa,
            }
            row.update(dict(zip(col_keys, qnd_col.tolist(), strict=True)))
            row.update(dict(zip(alb_keys, qnd_alb.tolist(), strict=True)))
            rows.append(row)

        if not rows:
            empty_cols = [
                "label",
                "area",
                "n_clumps",
                "contrast",
                "z_score",
                "intensity_per_area",
                *col_keys,
                *alb_keys,
            ]
            return pd.DataFrame(columns=empty_cols)
        return pd.DataFrame(rows)

PlumeShapeFilter

Bases: Operator

Drop instance labels that fail a fiber-shape morphology gate.

Adapted from Pérez Carrasco et al. (2026), physical_constraints. apply_physical_constraints — a post-Mask R-CNN gate that distinguishes elongated plume features from compact false positives. Per instance:

  1. area = mask.sum(); drop when below min_area_px.
  2. fiber_length = longest Euclidean path through the skeleton, in pixel widths (diagonal steps count sqrt(2); see :func:geoops.measure.skeleton_length).
  3. major_axis = regionprops.axis_major_length — the PCA-based major axis of the equivalent ellipse. The original paper uses cv2.minAreaRect (rotated minimum-area rectangle), avoided here to keep the optional-dependency surface unchanged; the two measures agree closely for typical plume morphologies.
  4. fiber_width = area / fiber_length.
  5. Keep iff min_fiber_to_major_ratio <= fiber_length / major_axis <= max_fiber_to_major_ratio AND min_fiber_width <= fiber_width <= max_fiber_width.

Surviving instances keep their original integer labels; rejected instances are mapped to background (0).

Parameters:

Name Type Description Default
min_area_px int

Minimum pixel count to consider an instance.

50
min_fiber_to_major_ratio float

Lower bound on fiber/major.

1.0
max_fiber_to_major_ratio float

Upper bound on fiber/major.

10.0
min_fiber_width float

Lower bound on area / fiber_length.

1.0
max_fiber_width float

Upper bound on area / fiber_length.

100.0
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class PlumeShapeFilter(Operator):
    """Drop instance labels that fail a fiber-shape morphology gate.

    Adapted from Pérez Carrasco et al. (2026), ``physical_constraints.
    apply_physical_constraints`` — a post-Mask R-CNN gate that distinguishes
    elongated plume features from compact false positives. Per instance:

    1. ``area = mask.sum()``; drop when below ``min_area_px``.
    2. ``fiber_length`` = longest Euclidean path through the skeleton, in
       pixel widths (diagonal steps count ``sqrt(2)``; see
       :func:`geoops.measure.skeleton_length`).
    3. ``major_axis`` = ``regionprops.axis_major_length`` — the PCA-based
       major axis of the equivalent ellipse. The original paper uses
       ``cv2.minAreaRect`` (rotated minimum-area rectangle), avoided here
       to keep the optional-dependency surface unchanged; the two measures
       agree closely for typical plume morphologies.
    4. ``fiber_width = area / fiber_length``.
    5. Keep iff
       ``min_fiber_to_major_ratio <= fiber_length / major_axis
       <= max_fiber_to_major_ratio`` AND
       ``min_fiber_width <= fiber_width <= max_fiber_width``.

    Surviving instances keep their original integer labels; rejected
    instances are mapped to background (``0``).

    Args:
        min_area_px: Minimum pixel count to consider an instance.
        min_fiber_to_major_ratio: Lower bound on ``fiber/major``.
        max_fiber_to_major_ratio: Upper bound on ``fiber/major``.
        min_fiber_width: Lower bound on ``area / fiber_length``.
        max_fiber_width: Upper bound on ``area / fiber_length``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # shape measures of connected components
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        min_area_px: int = 50,
        min_fiber_to_major_ratio: float = 1.0,
        max_fiber_to_major_ratio: float = 10.0,
        min_fiber_width: float = 1.0,
        max_fiber_width: float = 100.0,
    ) -> None:
        if min_area_px < 0:
            raise ValueError("min_area_px must be non-negative")
        if min_fiber_to_major_ratio < 0 or max_fiber_to_major_ratio <= 0:
            raise ValueError("fiber-to-major ratio bounds must be non-negative")
        if min_fiber_to_major_ratio > max_fiber_to_major_ratio:
            raise ValueError("min_fiber_to_major_ratio must be <= max")
        if min_fiber_width < 0 or max_fiber_width <= 0:
            raise ValueError("fiber width bounds must be non-negative")
        if min_fiber_width > max_fiber_width:
            raise ValueError("min_fiber_width must be <= max")
        self.min_area_px = int(min_area_px)
        self.min_fiber_to_major_ratio = float(min_fiber_to_major_ratio)
        self.max_fiber_to_major_ratio = float(max_fiber_to_major_ratio)
        self.min_fiber_width = float(min_fiber_width)
        self.max_fiber_width = float(max_fiber_width)

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        labels = squeeze_single_band(np.asarray(gt), name="PlumeShapeFilter").astype(
            np.int64, copy=False
        )
        kept: set[int] = set()
        for lbl, compact, _bbox in _iter_instances(labels):
            area = int(compact.sum())
            if area < self.min_area_px:
                continue
            fiber_length = skeleton_length(compact)
            if fiber_length <= 0:
                continue
            major_axis = _major_axis_length(compact)
            if major_axis <= 0:
                continue
            ratio = fiber_length / major_axis
            fiber_width = area / fiber_length
            if not (
                self.min_fiber_to_major_ratio <= ratio <= self.max_fiber_to_major_ratio
            ):
                continue
            if not self.min_fiber_width <= fiber_width <= self.max_fiber_width:
                continue
            kept.add(lbl)

        if not kept:
            out = np.zeros_like(labels, dtype=np.int32)
        else:
            keep_mask = np.isin(labels, list(kept))
            out = np.where(keep_mask, labels, 0).astype(np.int32, copy=False)
        return wrap_like(gt, out, fill_value=0)

SBMP

Bases: Operator

Single-band multi-pass Sentinel-2 SWIR ratio retrieval.

Emits a unitless methane "enhancement score" that highlights pixels where SWIR-2 (B12, ~2200 nm — a strong CH4 absorption window) is depressed relative to SWIR-1 (B11, ~1600 nm — weakly absorbing).

With a second positional carrier, the reference_scene (a clean-air acquisition over the same geography and pixel grid), the operator computes the log-ratio change

.. math::

\Delta \;=\; \log\!\Bigl(\tfrac{\rho_{B11} + \varepsilon}
                               {\rho_{B12} + \varepsilon}\Bigr)
           - \log\!\Bigl(\tfrac{\rho^{ref}_{B11} + \varepsilon}
                               {\rho^{ref}_{B12} + \varepsilon}\Bigr)

following Varon et al. (2021) — Satellite discovery of anomalously large methane point sources from oil/gas production (RSE, 251). The reference-scene formulation cancels static surface signatures so plume pixels dominate :math:\Delta.

Without a reference scene the operator falls back to the same-scene normalized SWIR contrast (SWIR1 - SWIR2) / (SWIR1 + SWIR2 + eps), which is a cheap detection prefilter (Ehret et al., 2022, TGRS) but is not a quantitative column retrieval — pair it with ColumnToMass only when calibrated against a per-scene ppm m mapping.

Inputs are radiance or reflectance arrays with band axis axis; negative values are clipped to zero before the log to keep the operator finite over noisy radiances. The output is single-band; nodata pixels (non-finite or equal to the fill value in any band of the input or the reference scene) hold NaN, and a GeoArray output declares fill_value=NaN.

Band names are resolved with the package-wide resolver (:func:geoops._src.bands.resolve_band: attrs band_names, then descriptions, then bands), so a GeoArray must name its bands. Only a plain ndarray with exactly 12 bands falls back to the Sentinel-2 L2A order (B1-B8, B8A, B9, B11, B12; no B10); on any other unnamed input pass integer indices.

Parameters:

Name Type Description Default
swir1 BandRef

Index or band name of the SWIR-1 channel. Default "B11".

'B11'
swir2 BandRef

Index or band name of the SWIR-2 channel. Default "B12".

'B12'
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
eps float

Numerical guard against division by zero. Default 1e-10.

1e-10

Called as op(scene, reference_scene=None). The optional reference_scene is a clean-air GeoArray or plain array on the scene's pixel grid (ValueError otherwise) with the same band layout; a GeoArray reference resolves the band names against its own attrs, a plain array uses the scene's band positions. When supplied, the output is the log-ratio change.

Examples:

Reference-scene retrieval over a single source::

import geoops as gz

score = gz.plume.SBMP()(post_event_s2, pre_event_s2)
mask = gz.plume.PlumeMask(threshold="percentile:99.5")(score)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class SBMP(Operator):
    r"""Single-band multi-pass Sentinel-2 SWIR ratio retrieval.

    Emits a unitless methane "enhancement score" that highlights pixels
    where SWIR-2 (B12, ~2200 nm — a strong CH4 absorption window) is
    depressed relative to SWIR-1 (B11, ~1600 nm — weakly absorbing).

    With a second positional carrier, the ``reference_scene`` (a clean-air
    acquisition over the same geography and pixel grid), the operator
    computes the log-ratio change

    .. math::

        \Delta \;=\; \log\!\Bigl(\tfrac{\rho_{B11} + \varepsilon}
                                       {\rho_{B12} + \varepsilon}\Bigr)
                   - \log\!\Bigl(\tfrac{\rho^{ref}_{B11} + \varepsilon}
                                       {\rho^{ref}_{B12} + \varepsilon}\Bigr)

    following Varon et al. (2021) — *Satellite discovery of anomalously
    large methane point sources from oil/gas production* (RSE, 251). The
    reference-scene formulation cancels static surface signatures so
    plume pixels dominate :math:`\Delta`.

    Without a reference scene the operator falls back to the same-scene
    normalized SWIR contrast
    ``(SWIR1 - SWIR2) / (SWIR1 + SWIR2 + eps)``, which is a cheap
    detection prefilter (Ehret et al., 2022, TGRS) but is *not* a
    quantitative column retrieval — pair it with ``ColumnToMass`` only
    when calibrated against a per-scene ppm m mapping.

    Inputs are radiance or reflectance arrays with band axis ``axis``;
    negative values are clipped to zero before the log to keep the
    operator finite over noisy radiances. The output is single-band;
    nodata pixels (non-finite or equal to the fill value in any band of
    the input or the reference scene) hold ``NaN``, and a GeoArray
    output declares ``fill_value=NaN``.

    Band names are resolved with the package-wide resolver
    (:func:`geoops._src.bands.resolve_band`: ``attrs`` ``band_names``,
    then ``descriptions``, then ``bands``), so a GeoArray must name its
    bands. Only a plain ndarray with exactly 12 bands falls back to the
    Sentinel-2 L2A order (``B1``-``B8``, ``B8A``, ``B9``, ``B11``,
    ``B12``; no B10); on any other unnamed input pass integer indices.

    Args:
        swir1: Index or band name of the SWIR-1 channel. Default ``"B11"``.
        swir2: Index or band name of the SWIR-2 channel. Default ``"B12"``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
        eps: Numerical guard against division by zero. Default ``1e-10``.

    Called as ``op(scene, reference_scene=None)``. The optional
    ``reference_scene`` is a clean-air ``GeoArray`` or plain array on the
    scene's pixel grid (``ValueError`` otherwise) with the same band
    layout; a GeoArray reference resolves the band names against its own
    ``attrs``, a plain array uses the scene's band positions. When
    supplied, the output is the log-ratio change.

    Examples:
        Reference-scene retrieval over a single source::

            import geoops as gz

            score = gz.plume.SBMP()(post_event_s2, pre_event_s2)
            mask = gz.plume.PlumeMask(threshold="percentile:99.5")(score)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a band ratio between two passes
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "time"}, effects={"band": "reduce", "time": "reduce"}
    )

    def __init__(
        self,
        *,
        swir1: BandRef = "B11",
        swir2: BandRef = "B12",
        dim: str = "band",
        eps: float = 1e-10,
        axis: int | None = None,
    ) -> None:
        self.swir1 = swir1
        self.swir2 = swir2
        self.dim = band_dim(dim, axis, "SBMP")
        self.eps = eps

    def _apply(
        self,
        gt: GeoArray | np.ndarray,
        reference_scene: GeoArray | np.ndarray | None = None,
    ) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="SBMP")
        if reference_scene is not None:
            require_grid_match(
                gt, reference_scene, "SBMP", names=("scene", "reference_scene")
            )
        arr = np.asarray(gt, dtype=float)
        idx1 = _band_position(gt, self.swir1, axis)
        idx2 = _band_position(gt, self.swir2, axis)
        swir1 = _extract_and_clip_band(arr, idx1, axis)
        swir2 = _extract_and_clip_band(arr, idx2, axis)
        ratio = np.log((swir1 + self.eps) / (swir2 + self.eps))
        if reference_scene is not None:
            ref = np.asarray(reference_scene, dtype=float)
            # A named reference resolves its own bands; an unnamed one is
            # assumed to share the scene's band layout.
            if isinstance(reference_scene, GeoArray):
                idx1 = _band_position(reference_scene, self.swir1, axis)
                idx2 = _band_position(reference_scene, self.swir2, axis)
            ref_swir1 = _extract_and_clip_band(ref, idx1, axis)
            ref_swir2 = _extract_and_clip_band(ref, idx2, axis)
            ref_ratio = np.log((ref_swir1 + self.eps) / (ref_swir2 + self.eps))
            out = ratio - ref_ratio
        else:
            out = (swir1 - swir2) / (swir1 + swir2 + self.eps)
        invalid = invalid_values(gt).any(axis=axis)
        if reference_scene is not None:
            invalid = invalid | invalid_values(reference_scene).any(axis=axis)
        return wrap_filled(
            gt, keep_band_axis(out, gt), fill_value=np.nan, valid=~invalid
        )

WindAdvectionCone

Bases: Operator

Mask likely downwind plume extent from a source and wind vector.

Rasterizes a circular sector centered at source, oriented along (wind_u, wind_v), with half-angle half_angle_deg and radius max_distance. The mask is useful as a prior for plume segmentation when the source location and wind are known (e.g. from a reanalysis product), following the practice of Varon et al. (2018, 2021).

Geo-dependent: the cone is rasterised in CRS coordinates via the carrier's transform, so the input must be a georeferenced GeoArray (plain arrays raise TypeError). max_distance is in metres and the cone angle is measured in the map plane, so the carrier CRS must be projected with metre units; a geographic CRS raises ValueError (reproject with :class:geoops.geom.Reproject first).

Parameters:

Name Type Description Default
source tuple[float, float]

(x, y) source coordinates. If crs is supplied, source is interpreted in that CRS and reprojected to the carrier CRS (which must then be set); otherwise it is in carrier CRS coordinates (m).

required
wind_u float

Eastward wind component (m/s).

required
wind_v float

Northward wind component (m/s).

required
half_angle_deg float

Half-angle of the cone in degrees, in [0, 180]; 180 is the full disc (see :func:wind_advection_cone).

30.0
max_distance float

Radius of the cone (m).

5000.0
crs str | None

Optional CRS of source.

None

Examples:

>>> cone = gz.plume.WindAdvectionCone(
...     source=(x0, y0), wind_u=3.0, wind_v=1.0,
...     half_angle_deg=30.0, max_distance=5000.0,
... )(enhancement)
Source code in packages/geotoolz-ops/src/geoops/plume/_src/operators.py
class WindAdvectionCone(Operator):
    """Mask likely downwind plume extent from a source and wind vector.

    Rasterizes a circular sector centered at ``source``, oriented along
    ``(wind_u, wind_v)``, with half-angle ``half_angle_deg`` and radius
    ``max_distance``. The mask is useful as a prior for plume
    segmentation when the source location and wind are known (e.g. from
    a reanalysis product), following the practice of Varon et al. (2018,
    2021).

    Geo-dependent: the cone is rasterised in CRS coordinates via the
    carrier's transform, so the input must be a georeferenced
    ``GeoArray`` (plain arrays raise ``TypeError``). ``max_distance`` is
    in metres and the cone angle is measured in the map plane, so the
    carrier CRS must be projected with metre units; a geographic CRS
    raises ``ValueError`` (reproject with :class:`geoops.geom.Reproject`
    first).

    Args:
        source: ``(x, y)`` source coordinates. If ``crs`` is supplied,
            ``source`` is interpreted in that CRS and reprojected to the
            carrier CRS (which must then be set); otherwise it is in
            carrier CRS coordinates (m).
        wind_u: Eastward wind component (m/s).
        wind_v: Northward wind component (m/s).
        half_angle_deg: Half-angle of the cone in degrees, in [0, 180];
            ``180`` is the full disc (see :func:`wind_advection_cone`).
        max_distance: Radius of the cone (m).
        crs: Optional CRS of ``source``.

    Examples:
        >>> cone = gz.plume.WindAdvectionCone(
        ...     source=(x0, y0), wind_u=3.0, wind_v=1.0,
        ...     half_angle_deg=30.0, max_distance=5000.0,
        ... )(enhancement)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # depends only on the grid, the source and the wind
    coupling: ClassVar[Coupling] = Coupling(reads_values=False)

    def __init__(
        self,
        *,
        source: tuple[float, float],
        wind_u: float,
        wind_v: float,
        half_angle_deg: float = 30.0,
        max_distance: float = 5000.0,
        crs: str | None = None,
    ) -> None:
        self.source = as_tuple(source)
        self.wind_u = wind_u
        self.wind_v = wind_v
        self.half_angle_deg = half_angle_deg
        self.max_distance = max_distance
        self.crs = crs

    @over_frames
    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "WindAdvectionCone")
        require_projected_crs(gt, "WindAdvectionCone")
        arr = squeeze_single_band(np.asarray(gt), name="WindAdvectionCone")
        source = self.source
        if self.crs is not None:
            if gt.crs is None:
                raise ValueError(
                    "WindAdvectionCone was given source crs="
                    f"{self.crs!r} but the input GeoArray has no CRS, so "
                    "the source cannot be reprojected onto it. Set the "
                    "carrier CRS, or pass source in carrier coordinates "
                    "with crs=None."
                )
            src_crs = CRS.from_user_input(self.crs)
            dst_crs = CRS.from_user_input(gt.crs)
            if src_crs != dst_crs:
                transformer = Transformer.from_crs(src_crs, dst_crs, always_xy=True)
                source = transformer.transform(*source)
        mask = wind_advection_cone(
            arr.shape,
            affine_of(gt),
            source=source,
            wind_u=self.wind_u,
            wind_v=self.wind_v,
            half_angle_deg=self.half_angle_deg,
            max_distance=self.max_distance,
        )
        return wrap_like(gt, mask, fill_value=False)

convert_column_units(values, *, gas='CH4', units_in='ppm_m', units_out='kg_m2', pressure_pa=STANDARD.standard_pressure, temperature_k=_NEAR_SURFACE_TEMPERATURE_K)

Convert column enhancement among ppm m, mol/m^2, and kg/m^2.

The conversions are

.. math::

\Omega_{\mathrm{mol/m^2}} \;=\; \frac{X \cdot 10^{-6}}{V_m}, \qquad
\Omega_{\mathrm{kg/m^2}}  \;=\; M_{\mathrm{gas}}
                                \cdot \Omega_{\mathrm{mol/m^2}}

where X is the column-integrated volume mixing ratio in ppm m, :math:V_m = R T / p is the molar volume of an ideal gas at pressure pressure_pa and temperature temperature_k (1 atm and 298.15 K by default, :math:V_m \approx 0.024465 m^3/mol), and :math:M_{\mathrm{gas}} is the molar mass (CH4: 0.0160425 kg/mol; CO2: 0.0440095 kg/mol). The maths is geophysix.columns.convert.

The ppm m branch therefore assumes near-surface conditions unless you pass the air's pressure and temperature. Pass mol_m2 or kg_m2 inputs when retrieval-specific pressure and temperature corrections have already been applied upstream (e.g. by a matched-filter retrieval per Thompson 2015 / Foote 2020).

Source code in packages/geotoolz-ops/src/geoops/plume/_src/array.py
def convert_column_units(
    values: Num[np.ndarray, "*dims"],
    *,
    gas: str = "CH4",
    units_in: ColumnUnit = "ppm_m",
    units_out: ColumnUnit = "kg_m2",
    pressure_pa: float = STANDARD.standard_pressure,
    temperature_k: float = _NEAR_SURFACE_TEMPERATURE_K,
) -> Float[np.ndarray, "*dims"]:
    r"""Convert column enhancement among ppm m, mol/m^2, and kg/m^2.

    The conversions are

    .. math::

        \Omega_{\mathrm{mol/m^2}} \;=\; \frac{X \cdot 10^{-6}}{V_m}, \qquad
        \Omega_{\mathrm{kg/m^2}}  \;=\; M_{\mathrm{gas}}
                                        \cdot \Omega_{\mathrm{mol/m^2}}

    where ``X`` is the column-integrated volume mixing ratio in ppm m,
    :math:`V_m = R T / p` is the molar volume of an ideal gas at pressure
    ``pressure_pa`` and temperature ``temperature_k`` (1 atm and 298.15 K by
    default, :math:`V_m \approx 0.024465` m^3/mol), and
    :math:`M_{\mathrm{gas}}` is the molar mass (CH4: 0.0160425 kg/mol; CO2:
    0.0440095 kg/mol). The maths is `geophysix.columns.convert`.

    The ppm m branch therefore assumes near-surface conditions unless you
    pass the air's pressure and temperature. Pass ``mol_m2`` or ``kg_m2``
    inputs when retrieval-specific pressure and temperature corrections have
    already been applied upstream (e.g. by a matched-filter retrieval per
    Thompson 2015 / Foote 2020).
    """
    gas_key = gas.upper()
    if gas_key not in _GASES:
        supported = ", ".join(sorted(_GASES))
        raise ValueError(f"unsupported gas {gas!r}; expected one of {supported}")
    if units_in not in ("ppm_m", "mol_m2", "kg_m2"):
        raise ValueError("units_in must be 'ppm_m', 'mol_m2', or 'kg_m2'")
    if units_out not in ("ppm_m", "mol_m2", "kg_m2"):
        raise ValueError("units_out must be 'ppm_m', 'mol_m2', or 'kg_m2'")
    return convert(
        np.asarray(values, dtype=float),
        units_in,
        units_out,
        gas=_GASES[gas_key],
        pressure=pressure_pa,
        temperature=temperature_k,
    )

plume_mask(values, *, threshold='otsu', min_area_px=50, connectivity=8, nbins=256)

Threshold an enhancement map and remove small connected components.

Parameters:

Name Type Description Default
values Num[ndarray, 'h w'] | Num[ndarray, '1 h w']

Single-band enhancement map, (H, W) or (1, H, W).

required
threshold ThresholdMode

Absolute number, "otsu", or "percentile:<p>"; see :func:geoops.segment.resolve_threshold.

'otsu'
min_area_px int

Minimum connected-component size in pixels.

50
connectivity Connectivity

4 or 8 connectivity for component labelling.

8
nbins int

Histogram bins for the "otsu" threshold. Default 256.

256

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask of the surviving plume pixels.

Source code in packages/geotoolz-ops/src/geoops/plume/_src/array.py
def plume_mask(
    values: Num[np.ndarray, "h w"] | Num[np.ndarray, "1 h w"],
    *,
    threshold: ThresholdMode = "otsu",
    min_area_px: int = 50,
    connectivity: Connectivity = 8,
    nbins: int = 256,
) -> Bool[np.ndarray, "h w"]:
    """Threshold an enhancement map and remove small connected components.

    Args:
        values: Single-band enhancement map, ``(H, W)`` or ``(1, H, W)``.
        threshold: Absolute number, ``"otsu"``, or ``"percentile:<p>"``;
            see :func:`geoops.segment.resolve_threshold`.
        min_area_px: Minimum connected-component size in pixels.
        connectivity: 4 or 8 connectivity for component labelling.
        nbins: Histogram bins for the ``"otsu"`` threshold. Default ``256``.

    Returns:
        Boolean ``(H, W)`` mask of the surviving plume pixels.
    """
    arr = squeeze_single_band(values)
    raw = threshold_mask(arr, threshold, nbins=nbins)
    return label_components(raw, min_area_px=min_area_px, connectivity=connectivity) > 0

wind_advection_cone(shape, transform, *, source, wind_u, wind_v, half_angle_deg=30.0, max_distance=5000.0)

Rasterize an analytical downwind sector mask.

Marks pixels whose center lies within max_distance of source and whose bearing from the source is within half_angle_deg of the wind direction (wind_u, wind_v) — a geometric prior for where an advected plume can be. The source pixel itself is included.

With d = (x − x₀, y − y₀) the offset of a pixel center from the source and ŵ = (u, v) / ‖(u, v)‖ the unit wind vector, a pixel is inside when

‖d‖ ≤ max_distance  and  d·ŵ ≥ ‖d‖ · cos(half_angle_deg)

i.e. the angle between d and ŵ is at most half_angle_deg. For half_angle_deg ≤ 90 the angle test alone keeps the sector in the downwind half-plane (cos ≥ 0 ⇒ d·ŵ ≥ 0); half_angle_deg > 90 widens it past the crosswind line, and half_angle_deg = 180 is the full disc of radius max_distance, upwind pixels included.

Parameters:

Name Type Description Default
shape tuple[int, int]

Raster shape (H, W).

required
transform Any

Affine-like geotransform of the raster; its CRS units must match source and max_distance.

required
source tuple[float, float]

(x, y) source coordinates in CRS units.

required
wind_u float

Eastward wind component.

required
wind_v float

Northward wind component.

required
half_angle_deg float

Half-angle of the sector in degrees, in [0, 180].

30.0
max_distance float

Sector radius in CRS units.

5000.0

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask, True inside the downwind sector.

Raises:

Type Description
ValueError

If the wind vector is zero, half_angle_deg is outside [0, 180], or max_distance is not positive.

Source code in packages/geotoolz-ops/src/geoops/plume/_src/array.py
def wind_advection_cone(
    shape: tuple[int, int],
    transform: Any,
    *,
    source: tuple[float, float],
    wind_u: float,
    wind_v: float,
    half_angle_deg: float = 30.0,
    max_distance: float = 5000.0,
) -> Bool[np.ndarray, "h w"]:
    """Rasterize an analytical downwind sector mask.

    Marks pixels whose center lies within ``max_distance`` of ``source``
    and whose bearing from the source is within ``half_angle_deg`` of the
    wind direction ``(wind_u, wind_v)`` — a geometric prior for where an
    advected plume can be. The source pixel itself is included.

    With ``d = (x − x₀, y − y₀)`` the offset of a pixel center from the
    source and ``ŵ = (u, v) / ‖(u, v)‖`` the unit wind vector, a pixel is
    inside when

        ‖d‖ ≤ max_distance  and  d·ŵ ≥ ‖d‖ · cos(half_angle_deg)

    i.e. the angle between ``d`` and ``ŵ`` is at most ``half_angle_deg``.
    For ``half_angle_deg ≤ 90`` the angle test alone keeps the sector in
    the downwind half-plane (``cos ≥ 0 ⇒ d·ŵ ≥ 0``); ``half_angle_deg > 90``
    widens it past the crosswind line, and ``half_angle_deg = 180`` is the
    full disc of radius ``max_distance``, upwind pixels included.

    Args:
        shape: Raster shape ``(H, W)``.
        transform: Affine-like geotransform of the raster; its CRS units
            must match ``source`` and ``max_distance``.
        source: ``(x, y)`` source coordinates in CRS units.
        wind_u: Eastward wind component.
        wind_v: Northward wind component.
        half_angle_deg: Half-angle of the sector in degrees, in [0, 180].
        max_distance: Sector radius in CRS units.

    Returns:
        Boolean ``(H, W)`` mask, True inside the downwind sector.

    Raises:
        ValueError: If the wind vector is zero, ``half_angle_deg`` is
            outside [0, 180], or ``max_distance`` is not positive.
    """
    wind_norm = float(np.hypot(wind_u, wind_v))
    if wind_norm == 0.0:
        raise ValueError("wind vector must be non-zero")
    if not 0.0 <= half_angle_deg <= 180.0:
        raise ValueError("half_angle_deg must be in [0, 180]")
    if max_distance <= 0.0:
        raise ValueError("max_distance must be positive")

    xs, ys = pixel_centers(shape, transform)
    dx = xs - source[0]
    dy = ys - source[1]
    distances = np.hypot(dx, dy)
    projection = (dx * wind_u + dy * wind_v) / wind_norm
    cos_angle = np.divide(
        projection,
        distances,
        out=np.ones_like(distances, dtype=float),
        where=distances > 0,
    )
    # Clip rounding overshoot so half_angle_deg=180 (cos = −1) is the full disc.
    cos_angle = np.clip(cos_angle, -1.0, 1.0)
    min_cos = np.cos(np.deg2rad(half_angle_deg))
    return (distances <= max_distance) & (cos_angle >= min_cos)