Skip to content

QA

geoops.qa is the home of QA / cloud-mask extraction: generic decoders, sensor presets, and the decoding primitives they share:

  • mask_from_qa_bits — single-bit-flag decoding (OR of bits).
  • mask_from_scl — categorical class membership (Sentinel-2 SCL).
  • mask_from_bit_field — contiguous multi-bit field decoding (needed for MODIS).
  • flagged_band_count and mask_from_band_count — EMIT's packed per-band mask: the bands flagged per pixel, and the dilated saturation mask above each detector column's baseline.

One vocabulary throughout: qa_band selects the QA band from a stack (None, the default for the generic decoders, means the carrier is the QA band), bits lists independent flag bits, values lists categorical class / field values, and the sensor presets take targets — registry names to mask out.

Pick the generic decoders (MaskClouds, MaskCloudShadow, MaskCirrus, MaskSnow, MaskWater, MaskNoData — one implementation under several semantic names) when you have an explicit list of bits / values; invert=True turns the list into a keep-list. MaskInvalid marks nodata pixels (the carrier fill, NaN fills included, or non-finite values); MaskSaturated flags pixels at or above a saturation value (reduce_bands=False for per-band flags). Pick LandsatQA_PIXEL / S2QA60 / S2SCL / MODISStateQA / EMITL2AMask when you want the published-spec defaults, EMITBandMask for the saturation mask of an EMIT scene, and DecodeBitmask to unpack a QA bitmask into named boolean layers. SCL holds the Sentinel-2 SCL class IDs and SCL_CLOUDS, SCL_CLOUDS_AND_INVALID, SCL_INVALID, SCL_LAND, SCL_WATER the common class sets; SENSOR_QA_REGISTRY maps each sensor preset's targets names to bits / values. S2Cloudless, CloudSEN12 and OmniCloudMask are placeholders reserved for optional ML-based detectors: they configure and serialise today but raise ImportError when called. To apply a mask, use geoops.mask.ApplyMask.

geoops.qa

QA bit decoding, SCL classes, and sensor mask presets.

The operators in this module return boolean masks where True means "mask this pixel out". Use them with geoops.mask.ApplyMask or downstream mask-combination operators.

Two operator families:

  • Generic extraction (MaskClouds, MaskCloudShadow, MaskCirrus, MaskSnow, MaskWater, MaskNoData, MaskInvalid, MaskSaturated, DecodeBitmask) — pass explicit bits / values with an optional qa_band (None = the carrier is the QA band).
  • Sensor presets (S2QA60, S2SCL, LandsatQA_PIXEL, MODISStateQA, EMITL2AMask, and EMITBandMask for EMIT's packed band mask) — published bit/class layouts baked in; pick targets by name.

CloudSEN12

Bases: Operator

Placeholder for the optional ML-based CloudSEN12 detector.

Raises ImportError on call.

Examples:

>>> from geoops.qa import CloudSEN12
>>> CloudSEN12(checkpoint="default").get_config()
{'checkpoint': 'default'}
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class CloudSEN12(Operator):
    """Placeholder for the optional ML-based CloudSEN12 detector.

    Raises ``ImportError`` on call.

    Examples:
        >>> from geoops.qa import CloudSEN12
        >>> CloudSEN12(checkpoint="default").get_config()
        {'checkpoint': 'default'}
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a learned detector over bands and neighbourhoods
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, checkpoint: str = "default") -> None:
        self.checkpoint = checkpoint

    def _apply(self, gt: GeoArray) -> GeoArray:
        raise ImportError(
            "CloudSEN12 requires the optional ML mask extra, which is not "
            "packaged in this release."
        )

DecodeBitmask

Bases: Operator

Unpack a QA bitmask into named boolean mask layers.

A more general sibling of MaskClouds (bits= mode): instead of returning a single OR-ed mask, this operator returns a stacked multi-band boolean carrier with one layer per named entry in bits.

Parameters:

Name Type Description Default
bits Mapping[str, Sequence[int]] | Sequence[Sequence[Any]]

Mapping from output-layer name to bit positions, or the equivalent [[name, bits], ...] pairs that get_config emits.

required
mode str

"any" marks a pixel when any listed bit is set; "all" requires every listed bit to be set (rare — useful for confidence-pair sub-fields).

'any'
qa_band BandSelector

Optional integer or named band selector. When omitted, the input carrier itself is treated as the QA band.

None
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

Returns:

Type Description
GeoArray | ndarray

A multi-band boolean carrier with shape (n_layers, height, width), matching the input carrier kind. For GeoArray input the output band_names attr is set from the keys of bits; plain np.ndarray input returns a plain stacked boolean array (no metadata to carry the names).

Examples:

>>> from geoops.qa import DecodeBitmask
>>> # Landsat-8 QA_PIXEL — one band per flag.
>>> op = DecodeBitmask(
...     bits={"cloud": [3], "cirrus": [2], "shadow": [4]},
...     qa_band="QA_PIXEL",
... )
>>> layers = op(landsat_stack)  # (3, H, W) bool GeoArray
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class DecodeBitmask(Operator):
    """Unpack a QA bitmask into named boolean mask layers.

    A more general sibling of `MaskClouds` (``bits=`` mode): instead
    of returning a single OR-ed mask, this operator returns a *stacked*
    multi-band boolean carrier with one layer per named entry in
    ``bits``.

    Args:
        bits: Mapping from output-layer name to bit positions, or the
            equivalent ``[[name, bits], ...]`` pairs that ``get_config``
            emits.
        mode: ``"any"`` marks a pixel when any listed bit is set;
            ``"all"`` requires every listed bit to be set (rare —
            useful for confidence-pair sub-fields).
        qa_band: Optional integer or named band selector. When omitted,
            the input carrier itself is treated as the QA band.
        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.

    Returns:
        GeoArray | numpy.ndarray: A multi-band boolean carrier with
            shape ``(n_layers, height, width)``, matching the input
            carrier kind. For GeoArray input the output ``band_names``
            attr is set from the keys of ``bits``; plain ``np.ndarray``
            input returns a plain stacked boolean array (no metadata to
            carry the names).

    Examples:
        >>> from geoops.qa import DecodeBitmask
        >>> # Landsat-8 QA_PIXEL — one band per flag.
        >>> op = DecodeBitmask(
        ...     bits={"cloud": [3], "cirrus": [2], "shadow": [4]},
        ...     qa_band="QA_PIXEL",
        ... )
        >>> layers = op(landsat_stack)  # (3, H, W) bool GeoArray
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # one QA band -> one boolean layer per named bit field
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "expand"})

    def __init__(
        self,
        *,
        bits: Mapping[str, Sequence[int]] | Sequence[Sequence[Any]],
        mode: str = "any",
        qa_band: BandSelector = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        bits_map = mapping_from_pairs(bits)
        if not bits_map:
            raise ValueError("DecodeBitmask: `bits` must not be empty")
        if mode not in {"any", "all"}:
            raise ValueError("mode must be 'any' or 'all'")
        self.bits = {
            name: tuple(int(bit) for bit in bit_list)
            for name, bit_list in bits_map.items()
        }
        for name, bit_list in self.bits.items():
            if not bit_list:
                raise ValueError(f"bits[{name!r}] must not be empty")
        self.mode = mode
        self.qa_band = qa_band
        self.dim = band_dim(dim, axis, "DecodeBitmask")

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, type(self).__name__)
        qa = _select_qa(gt, self.qa_band, dim_axis(gt, self.dim, name="DecodeBitmask"))
        names = list(self.bits)
        layers = [
            _decode_bits_with_mode(qa, self.bits[name], self.mode) for name in names
        ]
        mask = np.stack(layers, axis=0)
        if not isinstance(gt, GeoArray):
            return mask
        return wrap_like(
            gt,
            mask,
            fill_value=False,
            attrs=strip_band_attrs(gt.attrs),
            band_names=names,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "bits": mapping_to_pairs(self.bits),
            "mode": self.mode,
            "qa_band": self.qa_band,
            "dim": self.dim,
        }

EMITBandMask

Bases: Operator

Saturation mask from EMIT's packed band mask; True = mask out.

satᵢⱼ = [nᵢⱼ - minᵢ nᵢⱼ > 0], grown by dilation pixels in city-block distance, with nᵢⱼ the bands flagged at pixel (i, j).

The carrier is EMIT's band_mask in swath geometry: uint8, one bit per spectral band packed into 36 bytes along dim (EMIT L2A User Guide V1.0, Table 3-3; the L1B band mask has the same layout). A set bit marks a band interpolated over a bad detector element or saturation. See geoops.qa.flagged_band_count and geoops.qa.mask_from_band_count for the maths: the column minimum removes the static detector defects, and what is left is saturation.

Compute it before orthorectifying, since the columns must be detector elements. Nodata pixels of the carrier (its fill value) neither set a column's baseline nor are flagged, and the output declares fill_value=False. Every byte value can be data, and a pixel with any byte equal to the fill is nodata, so declare a fill only for a value the product reserves for missing pixels. A (Y, H, W) carrier gives an (H, W) mask.

Parameters:

Name Type Description Default
dilation int

Growth of the mask in pixels (city-block distance). Default 10, SPIIRE's.

10
dim str

Name of the packed-byte dim (default "band").

'band'

Examples:

>>> import numpy as np
>>> from geoops.qa import EMITBandMask
>>> bandmask = np.zeros((36, 5, 5), dtype=np.uint8)
>>> bandmask[0] = 0b0000_0111   # three bad bands in every pixel
>>> bandmask[4, 2, 2] = 0b1100_0000   # two more at one pixel
>>> EMITBandMask(dilation=0)(bandmask).astype(int).sum()
np.int64(1)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class EMITBandMask(Operator):
    """Saturation mask from EMIT's packed band mask; True = mask out.

    satᵢⱼ = [nᵢⱼ - minᵢ nᵢⱼ > 0], grown by ``dilation`` pixels in city-block
    distance, with nᵢⱼ the bands flagged at pixel (i, j).

    The carrier is EMIT's ``band_mask`` in swath geometry: ``uint8``, one
    bit per spectral band packed into 36 bytes along ``dim`` (EMIT L2A User
    Guide V1.0, Table 3-3; the L1B band mask has the same layout). A set
    bit marks a band interpolated over a bad detector element or
    saturation. See `geoops.qa.flagged_band_count` and
    `geoops.qa.mask_from_band_count` for the maths: the column minimum
    removes the static detector defects, and what is left is saturation.

    Compute it before orthorectifying, since the columns must be detector
    elements. Nodata pixels of the carrier (its fill value) neither set a
    column's baseline nor are flagged, and the output declares
    ``fill_value=False``. Every byte value can be data, and a pixel with any
    byte equal to the fill is nodata, so declare a fill only for a value
    the product reserves for missing pixels. A ``(Y, H, W)`` carrier gives
    an ``(H, W)`` mask.

    Args:
        dilation: Growth of the mask in pixels (city-block distance).
            Default 10, SPIIRE's.
        dim: Name of the packed-byte dim (default ``"band"``).

    Examples:
        >>> import numpy as np
        >>> from geoops.qa import EMITBandMask
        >>> bandmask = np.zeros((36, 5, 5), dtype=np.uint8)
        >>> bandmask[0] = 0b0000_0111   # three bad bands in every pixel
        >>> bandmask[4, 2, 2] = 0b1100_0000   # two more at one pixel
        >>> EMITBandMask(dilation=0)(bandmask).astype(int).sum()
        np.int64(1)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the bytes of a pixel, and the whole column for its baseline
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(self, *, dilation: int = 10, dim: str = "band") -> None:
        if dilation < 0:
            raise ValueError(f"EMITBandMask: dilation must be >= 0, got {dilation}")
        self.dilation = dilation
        self.dim = dim

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "EMITBandMask")
        axis = dim_axis(gt, self.dim, name="EMITBandMask")
        packed = np.moveaxis(np.asarray(gt), axis, -1)
        valid = valid_pixels(gt) if isinstance(gt, GeoArray) else None
        # nᵢⱼ = ∑_k b_ijk
        count = flagged_band_count(packed)
        mask = mask_from_band_count(count, valid=valid, dilation=self.dilation)
        return wrap_filled(gt, mask, fill_value=False, valid=valid)

EMITL2AMask

Bases: Operator

Named flags of the EMIT L2A mask product, OR-combined; True = mask out.

maskᵢⱼ = OR over t in targets of [flag_{ij, band(t)} > 0].

The carrier is the mask variable of an EMIT L2A MASK file, one band per flag, in the order of the EMIT L2A User Guide V1.0, Table 3-4 (SENSOR_QA_REGISTRY["emit_l2a_mask"]): cloud, cirrus, water, spacecraft and dilated_cloud are bands 0 to 4 and aggregate (the OR of the first five) is band 7. Bands 5 and 6 hold the aerosol optical depth and the water vapour, which are not flags. The default, cloud, cirrus and water, is SPIIRE's mask of clouds and surface water.

Nodata pixels of the carrier are never flagged, and the output declares fill_value=False. A (B, H, W) carrier gives an (H, W) mask.

Parameters:

Name Type Description Default
targets Sequence[str]

Flag names from SENSOR_QA_REGISTRY["emit_l2a_mask"]. Default ("cloud", "cirrus", "water").

('cloud', 'cirrus', 'water')
dim str

Name of the band dim (default "band").

'band'

Examples:

>>> import numpy as np
>>> from geoops.qa import EMITL2AMask
>>> flags = np.zeros((8, 2, 2), dtype=np.float32)
>>> flags[2, 0, 1] = 1.0   # water
>>> flags[3, 1, 1] = 1.0   # spacecraft, not a default target
>>> EMITL2AMask()(flags).tolist()
[[False, True], [False, False]]
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class EMITL2AMask(Operator):
    """Named flags of the EMIT L2A mask product, OR-combined; True = mask out.

    maskᵢⱼ = OR over t in targets of [flag_{ij, band(t)} > 0].

    The carrier is the ``mask`` variable of an EMIT L2A MASK file, one band
    per flag, in the order of the EMIT L2A User Guide V1.0, Table 3-4
    (``SENSOR_QA_REGISTRY["emit_l2a_mask"]``): ``cloud``, ``cirrus``,
    ``water``, ``spacecraft`` and ``dilated_cloud`` are bands 0 to 4 and
    ``aggregate`` (the OR of the first five) is band 7. Bands 5 and 6 hold
    the aerosol optical depth and the water vapour, which are not flags.
    The default, cloud, cirrus and water, is SPIIRE's mask of clouds and
    surface water.

    Nodata pixels of the carrier are never flagged, and the output declares
    ``fill_value=False``. A ``(B, H, W)`` carrier gives an ``(H, W)`` mask.

    Args:
        targets: Flag names from ``SENSOR_QA_REGISTRY["emit_l2a_mask"]``.
            Default ``("cloud", "cirrus", "water")``.
        dim: Name of the band dim (default ``"band"``).

    Examples:
        >>> import numpy as np
        >>> from geoops.qa import EMITL2AMask
        >>> flags = np.zeros((8, 2, 2), dtype=np.float32)
        >>> flags[2, 0, 1] = 1.0   # water
        >>> flags[3, 1, 1] = 1.0   # spacecraft, not a default target
        >>> EMITL2AMask()(flags).tolist()
        [[False, True], [False, False]]
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # OR across the selected flag bands
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        targets: Sequence[str] = ("cloud", "cirrus", "water"),
        dim: str = "band",
    ) -> None:
        self.targets = tuple(str(target) for target in targets)
        _registry_bit_groups("emit_l2a_mask", self.targets)
        self.dim = dim

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "EMITL2AMask")
        axis = dim_axis(gt, self.dim, name="EMITL2AMask")
        flags = np.asarray(gt)
        entries = _registry_bit_groups("emit_l2a_mask", self.targets)
        indices = [entry["band"][0] for entry in entries.values()]
        if max(indices) >= flags.shape[axis]:
            raise ValueError(
                f"EMITL2AMask: target band {max(indices)} needs at least "
                f"{max(indices) + 1} bands, the carrier has {flags.shape[axis]}"
            )
        # flag_{ij, band(t)} > 0 for each target
        selected = np.take(flags, indices, axis=axis) > 0
        # OR over the targets
        mask = np.any(selected, axis=axis)
        valid = valid_pixels(gt) if isinstance(gt, GeoArray) else None
        return wrap_filled(gt, mask, fill_value=False, valid=valid)

LandsatQA_PIXEL

Bases: Operator

Landsat Collection-2 QA_PIXEL mask preset.

Returns True where any requested targets flag is set in QA_PIXEL. Defaults to cloud, cloud shadow, and cirrus targets (the standard "drop cloudy" mask for L8/L9).

Sensor selection: pass sensor="l7" for Landsat 4-7 Collection-2 — same bit layout as L8/L9 except bit 2 ("cirrus") is unused on TM/ETM+. For sensor="l89" (default) the full L8/L9 layout is used.

Accepts a GeoArray or a plain np.ndarray and returns the same carrier kind; plain arrays need an integer qa_band.

Parameters:

Name Type Description Default
qa_band int | str

Band selector for QA_PIXEL.

'QA_PIXEL'
targets Sequence[str] | None

Target flag names to OR together. See SENSOR_QA_REGISTRY["landsat_qa_pixel"] for available target names.

None
sensor str

"l89" (Landsat 8/9, default) or "l7" (Landsat 4-7).

'l89'
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

Examples:

>>> from geoops.qa import LandsatQA_PIXEL
>>> # L8/L9 default "drop everything not clear".
>>> mask = LandsatQA_PIXEL()(landsat8_stack)
>>> # L7 — same but no cirrus bit.
>>> mask = LandsatQA_PIXEL(
...     sensor="l7", targets=["cloud", "cloud_shadow"]
... )(landsat7_stack)
References

USGS, "Landsat 8-9 Collection 2 Level-2 Science Product Guide", LSDS-1619, 2022. USGS, "Landsat 4-7 Collection 2 Level-2 Science Product Guide", LSDS-1618, 2022.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class LandsatQA_PIXEL(Operator):
    """Landsat Collection-2 QA_PIXEL mask preset.

    Returns True where any requested ``targets`` flag is set in
    ``QA_PIXEL``. Defaults to cloud, cloud shadow, and cirrus targets
    (the standard "drop cloudy" mask for L8/L9).

    Sensor selection: pass ``sensor="l7"`` for Landsat 4-7
    Collection-2 — same bit layout as L8/L9 except bit 2 ("cirrus") is
    unused on TM/ETM+. For ``sensor="l89"`` (default) the full L8/L9
    layout is used.

    Accepts a ``GeoArray`` or a plain ``np.ndarray`` and returns the
    same carrier kind; plain arrays need an integer ``qa_band``.

    Args:
        qa_band: Band selector for QA_PIXEL.
        targets: Target flag names to OR together. See
            ``SENSOR_QA_REGISTRY["landsat_qa_pixel"]`` for available
            target names.
        sensor: ``"l89"`` (Landsat 8/9, default) or ``"l7"`` (Landsat
            4-7).
        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.

    Examples:
        >>> from geoops.qa import LandsatQA_PIXEL
        >>> # L8/L9 default "drop everything not clear".
        >>> mask = LandsatQA_PIXEL()(landsat8_stack)
        >>> # L7 — same but no cirrus bit.
        >>> mask = LandsatQA_PIXEL(
        ...     sensor="l7", targets=["cloud", "cloud_shadow"]
        ... )(landsat7_stack)

    References:
        USGS, "Landsat 8-9 Collection 2 Level-2 Science Product Guide",
        LSDS-1619, 2022.
        USGS, "Landsat 4-7 Collection 2 Level-2 Science Product Guide",
        LSDS-1618, 2022.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # reads the QA_PIXEL band only
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    _SENSOR_KEYS: ClassVar[dict[str, str]] = {
        "l89": "landsat_qa_pixel",
        "l7": "landsat_qa_pixel_l7",
    }
    _DEFAULT_TARGETS_L89: ClassVar[tuple[str, ...]] = (
        "cloud",
        "cloud_shadow",
        "cirrus",
    )
    _DEFAULT_TARGETS_L7: ClassVar[tuple[str, ...]] = ("cloud", "cloud_shadow")

    def __init__(
        self,
        *,
        qa_band: int | str = "QA_PIXEL",
        targets: Sequence[str] | None = None,
        sensor: str = "l89",
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        if sensor not in self._SENSOR_KEYS:
            raise ValueError(
                f"sensor must be one of {sorted(self._SENSOR_KEYS)}; got {sensor!r}"
            )
        if targets is None:
            targets = (
                self._DEFAULT_TARGETS_L7
                if sensor == "l7"
                else self._DEFAULT_TARGETS_L89
            )
        self.qa_band = qa_band
        self.targets = tuple(str(target) for target in targets)
        self.sensor = sensor
        self.dim = band_dim(dim, axis, "LandsatQA_PIXEL")

    def _apply(self, gt: Any) -> Any:
        registry_key = self._SENSOR_KEYS[self.sensor]
        return _preset_mask(gt, self, registry_key, "LandsatQA_PIXEL")

    def get_config(self) -> dict[str, Any]:
        return {
            "qa_band": self.qa_band,
            "targets": list(self.targets),
            "sensor": self.sensor,
            "dim": self.dim,
        }

MODISStateQA

Bases: Operator

MODIS state_1km (or state_500m) QA mask preset.

Returns True where any requested targets is set in the MODIS State QA band. Defaults to cloud and cloud-shadow targets.

The cloud and cirrus targets are decoded as 2-bit fields, not independent bit flags: bits [0, 1] are the cloud state (0=clear, 1=cloudy, 2=mixed, 3=not-set) and bits [8, 9] are cirrus level (0=none, 1=small, 2=average, 3=high). The default "cloud" target matches cloudy + mixed; "cirrus" matches small/average/high.

Accepts a GeoArray or a plain np.ndarray and returns the same carrier kind; plain arrays need an integer qa_band.

Parameters:

Name Type Description Default
qa_band int | str

Band selector for the state QA band.

'state_1km'
targets Sequence[str]

Target flag names to OR together. See SENSOR_QA_REGISTRY["modis_state_qa"].

('cloud', 'cloud_shadow')
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

Examples:

>>> from geoops.qa import MODISStateQA
>>> # Default cloud + cloud-shadow mask.
>>> mask = MODISStateQA()(modis_state_band)
>>> # Include cirrus too.
>>> mask = MODISStateQA(targets=["cloud", "cloud_shadow", "cirrus"])(state)
References

Vermote, E. F., "MODIS Surface Reflectance User's Guide", 2015, Table 12.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MODISStateQA(Operator):
    """MODIS ``state_1km`` (or ``state_500m``) QA mask preset.

    Returns True where any requested ``targets`` is set in the MODIS
    State QA band. Defaults to cloud and cloud-shadow targets.

    The cloud and cirrus targets are decoded as *2-bit fields*, not
    independent bit flags: bits ``[0, 1]`` are the cloud state
    (0=clear, 1=cloudy, 2=mixed, 3=not-set) and bits ``[8, 9]`` are
    cirrus level (0=none, 1=small, 2=average, 3=high). The default
    "cloud" target matches cloudy + mixed; "cirrus" matches
    small/average/high.

    Accepts a ``GeoArray`` or a plain ``np.ndarray`` and returns the
    same carrier kind; plain arrays need an integer ``qa_band``.

    Args:
        qa_band: Band selector for the state QA band.
        targets: Target flag names to OR together. See
            ``SENSOR_QA_REGISTRY["modis_state_qa"]``.
        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.

    Examples:
        >>> from geoops.qa import MODISStateQA
        >>> # Default cloud + cloud-shadow mask.
        >>> mask = MODISStateQA()(modis_state_band)
        >>> # Include cirrus too.
        >>> mask = MODISStateQA(targets=["cloud", "cloud_shadow", "cirrus"])(state)

    References:
        Vermote, E. F., "MODIS Surface Reflectance User's Guide",
        2015, Table 12.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # reads the state QA band only
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    def __init__(
        self,
        *,
        qa_band: int | str = "state_1km",
        targets: Sequence[str] = ("cloud", "cloud_shadow"),
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.qa_band = qa_band
        self.targets = tuple(str(target) for target in targets)
        self.dim = band_dim(dim, axis, "MODISStateQA")

    def _apply(self, gt: Any) -> Any:
        return _preset_mask(gt, self, "modis_state_qa", "MODISStateQA")

    def get_config(self) -> dict[str, Any]:
        return {
            "qa_band": self.qa_band,
            "targets": list(self.targets),
            "dim": self.dim,
        }

MaskCirrus

Bases: _QAMask

Return True where a QA band marks cirrus pixels.

Examples:

>>> from geoops.qa import MaskCirrus
>>> # Sentinel-2 QA60: bit 11 is "cirrus".
>>> mask = MaskCirrus(qa_band="QA60", bits=[11])(s2_geoarray)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskCirrus(_QAMask):
    """Return True where a QA band marks cirrus pixels.

    Examples:
        >>> from geoops.qa import MaskCirrus
        >>> # Sentinel-2 QA60: bit 11 is "cirrus".
        >>> mask = MaskCirrus(qa_band="QA60", bits=[11])(s2_geoarray)
    """

MaskCloudShadow

Bases: _QAMask

Return True where a QA band marks cloud-shadow pixels.

Examples:

>>> from geoops.qa import MaskCloudShadow
>>> # Landsat-8 QA_PIXEL: bit 4 is "cloud shadow".
>>> mask = MaskCloudShadow(qa_band="QA_PIXEL", bits=[4])(landsat_stack)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskCloudShadow(_QAMask):
    """Return True where a QA band marks cloud-shadow pixels.

    Examples:
        >>> from geoops.qa import MaskCloudShadow
        >>> # Landsat-8 QA_PIXEL: bit 4 is "cloud shadow".
        >>> mask = MaskCloudShadow(qa_band="QA_PIXEL", bits=[4])(landsat_stack)
    """

MaskClouds

Bases: _QAMask

Return True where a QA band marks cloud-contaminated pixels.

Examples:

>>> from geoops.qa import MaskClouds
>>> # Sentinel-2 QA60: bit 10 is "opaque clouds".
>>> mask = MaskClouds(qa_band="QA60", bits=[10])(s2_geoarray)
>>> # Sentinel-2 SCL: the cloud-like classes.
>>> from geoops.qa import SCL_CLOUDS
>>> mask = MaskClouds(qa_band="SCL", values=sorted(SCL_CLOUDS))(s2_l2a)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskClouds(_QAMask):
    """Return True where a QA band marks cloud-contaminated pixels.

    Examples:
        >>> from geoops.qa import MaskClouds
        >>> # Sentinel-2 QA60: bit 10 is "opaque clouds".
        >>> mask = MaskClouds(qa_band="QA60", bits=[10])(s2_geoarray)
        >>> # Sentinel-2 SCL: the cloud-like classes.
        >>> from geoops.qa import SCL_CLOUDS
        >>> mask = MaskClouds(qa_band="SCL", values=sorted(SCL_CLOUDS))(s2_l2a)
    """

MaskInvalid

Bases: Operator

Mark invalid (nodata) pixels: True = invalid, drop it.

The package-polarity counterpart of georeader's GeoTensor.invalidmask() reduced over bands: a pixel is invalid when any band equals the fill value or is non-finite. Unlike georeader's comparison, a NaN fill (fill_value=nan) matches NaN pixels (see :mod:geoops._src.valid).

Uses the carrier's fill_value by default; pass invalid_value explicitly to mark a different sentinel (required for plain-ndarray carriers, which have no fill value).

Parameters:

Name Type Description Default
invalid_value float | int | None

Sentinel value treated as "invalid". None uses the carrier's fill_value.

None
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

Examples:

>>> from geoops.mask import ApplyMask
>>> from geoops.qa import MaskInvalid
>>> mask = MaskInvalid()(geoarray)  # True = invalid
>>> clean = ApplyMask(mask=MaskInvalid(), fill_value=np.nan)(geoarray)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskInvalid(Operator):
    """Mark invalid (nodata) pixels: True = invalid, drop it.

    The package-polarity counterpart of georeader's
    ``GeoTensor.invalidmask()`` reduced over bands: a pixel is invalid
    when *any* band equals the fill value or is non-finite. Unlike
    georeader's comparison, a ``NaN`` fill (``fill_value=nan``)
    matches ``NaN`` pixels (see :mod:`geoops._src.valid`).

    Uses the carrier's ``fill_value`` by default; pass
    ``invalid_value`` explicitly to mark a different sentinel (required
    for plain-ndarray carriers, which have no fill value).

    Args:
        invalid_value: Sentinel value treated as "invalid". ``None``
            uses the carrier's ``fill_value``.
        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.

    Examples:
        >>> from geoops.mask import ApplyMask
        >>> from geoops.qa import MaskInvalid
        >>> mask = MaskInvalid()(geoarray)  # True = invalid
        >>> clean = ApplyMask(mask=MaskInvalid(), fill_value=np.nan)(geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # invalid where any band is nodata
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        invalid_value: float | int | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.invalid_value = invalid_value
        self.dim = band_dim(dim, axis, "MaskInvalid")

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, type(self).__name__)
        mask = _invalid_mask(
            gt,
            self.invalid_value,
            dim_axis(gt, self.dim, name="MaskInvalid"),
            "MaskInvalid",
        )
        return wrap_like(gt, mask, fill_value=False)

MaskNoData

Bases: _QAMask

Return True where pixels are no-data by QA value or carrier fill value.

Two operating modes:

  1. QA-driven: pass bits / values (plus qa_band when the QA band is part of a stack) to decode no-data from a dedicated QA band, exactly like the other _QAMask shortcuts.
  2. Fill-driven (default): without bits / values it is MaskInvalid — pixels invalid in any band (equal to the carrier's fill_value, a NaN fill matching NaN, or non-finite) are marked (see :mod:geoops._src.valid).

The QA-driven mode accepts a GeoArray or a plain np.ndarray and returns the same carrier kind; the fill-driven mode reads carrier metadata, so it requires a GeoArray with a fill_value.

Parameters:

Name Type Description Default
qa_band BandSelector

Optional QA band selector (QA-driven mode only).

None
bits Sequence[int] | None

Bit positions that mark no-data.

None
values Sequence[int] | None

Categorical values that mark no-data (e.g. SCL=0).

None
mode str

"any" (default) or "all"; only used with bits.

'any'
axis int | None

Position of the band axis. Default -3.

None
invert bool

Flip the QA-driven mask (see MaskClouds).

False

Returns:

Type Description
GeoArray

Boolean no-data mask.

Examples:

>>> from geoops.qa import MaskNoData
>>> # Sentinel-2 SCL: class 0 is NO_DATA.
>>> nodata = MaskNoData(qa_band="SCL", values=[0])(s2_l2a)
>>> # Fill-value fallback when no QA band is available.
>>> nodata = MaskNoData()(carrier_with_fill_value)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskNoData(_QAMask):
    """Return True where pixels are no-data by QA value or carrier fill value.

    Two operating modes:

    1. **QA-driven**: pass ``bits`` / ``values`` (plus ``qa_band`` when
       the QA band is part of a stack) to decode no-data from a
       dedicated QA band, exactly like the other `_QAMask` shortcuts.
    2. **Fill-driven** (default): without ``bits`` / ``values`` it is
       `MaskInvalid` — pixels invalid in *any* band (equal to the
       carrier's ``fill_value``, a ``NaN`` fill matching
       ``NaN``, or non-finite) are marked (see
       :mod:`geoops._src.valid`).

    The QA-driven mode accepts a ``GeoArray`` or a plain ``np.ndarray``
    and returns the same carrier kind; the fill-driven mode reads
    carrier metadata, so it requires a GeoArray with a
    ``fill_value``.

    Args:
        qa_band: Optional QA band selector (QA-driven mode only).
        bits: Bit positions that mark no-data.
        values: Categorical values that mark no-data (e.g. SCL=0).
        mode: ``"any"`` (default) or ``"all"``; only used with ``bits``.
        axis: Position of the band axis. Default ``-3``.
        invert: Flip the QA-driven mask (see `MaskClouds`).

    Returns:
        GeoArray: Boolean no-data mask.

    Examples:
        >>> from geoops.qa import MaskNoData
        >>> # Sentinel-2 SCL: class 0 is NO_DATA.
        >>> nodata = MaskNoData(qa_band="SCL", values=[0])(s2_l2a)
        >>> # Fill-value fallback when no QA band is available.
        >>> nodata = MaskNoData()(carrier_with_fill_value)
    """

    # the fill-driven path reads the whole carrier through the NumPy nodata
    # model (geoops._src.valid), so the operator stays NumPy-only
    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the QA band, or any band equal to the fill
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, type(self).__name__)
        if self.bits is not None or self.values is not None:
            return super()._apply(gt)
        if self.qa_band is not None:
            raise ValueError(
                "MaskNoData: qa_band needs bits or values to decode; drop "
                "qa_band to fall back to the carrier fill value."
            )
        mask = _invalid_mask(
            gt, None, dim_axis(gt, self.dim, name="MaskNoData"), "MaskNoData"
        )
        return wrap_like(gt, mask, fill_value=False)

MaskSaturated

Bases: Operator

Return True where pixels are at or above a saturation value.

The one saturation mask in the package. Nodata pixels (fill value or non-finite, see :mod:geoops._src.valid) are never reported as saturated — so a uint16 fill at the dtype maximum is not flagged — and the output declares fill_value=False.

Parameters:

Name Type Description Default
qa_band BandSelector

Optional band selector. When omitted, every band is tested.

None
saturation_value float | int | None

Saturation threshold; pixels >= it are flagged. If omitted, integer arrays use the dtype maximum and float arrays use 1.0 (the reflectance ceiling); other dtypes require an explicit value.

None
reduce_bands bool

When True (default) and qa_band is None, OR-reduce the per-band flags over axis into one (H, W) mask; when False, return one flag per band (same shape as the input).

True
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

Returns:

Type Description
GeoArray | ndarray

Boolean mask with saturated pixels marked True, matching the input carrier kind (GeoArray in → GeoArray out, plain np.ndarray in → plain array out).

Examples:

>>> from geoops.qa import MaskSaturated
>>> # uint16 Sentinel-2 — saturation_value defaults to 65535.
>>> sat = MaskSaturated()(s2_uint16_stack)
>>> # Per-band flags at a reflectance ceiling.
>>> sat = MaskSaturated(saturation_value=1.0, reduce_bands=False)(refl)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskSaturated(Operator):
    """Return True where pixels are at or above a saturation value.

    The one saturation mask in the package. Nodata pixels (fill value or
    non-finite, see :mod:`geoops._src.valid`) are never reported as
    saturated — so a ``uint16`` fill at the dtype maximum is not flagged
    — and the output declares ``fill_value=False``.

    Args:
        qa_band: Optional band selector. When omitted, every band is
            tested.
        saturation_value: Saturation threshold; pixels ``>=`` it are
            flagged. If omitted, integer arrays use the dtype maximum and
            float arrays use ``1.0`` (the reflectance ceiling); other
            dtypes require an explicit value.
        reduce_bands: When True (default) and ``qa_band`` is None,
            OR-reduce the per-band flags over ``axis`` into one
            ``(H, W)`` mask; when False, return one flag per band
            (same shape as the input).
        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.

    Returns:
        GeoArray | numpy.ndarray: Boolean mask with saturated pixels
            marked True, matching the input carrier kind (``GeoArray``
            in → ``GeoArray`` out, plain ``np.ndarray`` in → plain
            array out).

    Examples:
        >>> from geoops.qa import MaskSaturated
        >>> # uint16 Sentinel-2 — saturation_value defaults to 65535.
        >>> sat = MaskSaturated()(s2_uint16_stack)
        >>> # Per-band flags at a reflectance ceiling.
        >>> sat = MaskSaturated(saturation_value=1.0, reduce_bands=False)(refl)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # saturated where any band reaches the limit
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        qa_band: BandSelector = None,
        saturation_value: float | int | None = None,
        reduce_bands: bool = True,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.qa_band = qa_band
        self.saturation_value = saturation_value
        self.reduce_bands = reduce_bands
        self.dim = band_dim(dim, axis, "MaskSaturated")

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="MaskSaturated")
        arr = _select_qa(gt, self.qa_band, axis)
        saturation_value = self.saturation_value
        if saturation_value is None:
            if np.issubdtype(arr.dtype, np.integer):
                saturation_value = np.iinfo(arr.dtype).max
            elif np.issubdtype(arr.dtype, np.floating):
                saturation_value = 1.0
            else:
                raise ValueError(
                    f"MaskSaturated: pass saturation_value for {arr.dtype} inputs."
                )
        mask = arr >= saturation_value
        if self.reduce_bands and self.qa_band is None and mask.ndim > 2:
            mask = np.any(mask, axis=axis)
        valid = valid_pixels(gt) if np.ndim(gt) >= 2 else ~invalid_values(gt)
        return wrap_filled(gt, mask, fill_value=False, valid=valid)

MaskSnow

Bases: _QAMask

Return True where a QA band marks snow or ice pixels.

Examples:

>>> from geoops.qa import MaskSnow
>>> # Landsat-8 QA_PIXEL: bit 5 is "snow / ice".
>>> mask = MaskSnow(qa_band="QA_PIXEL", bits=[5])(landsat_stack)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskSnow(_QAMask):
    """Return True where a QA band marks snow or ice pixels.

    Examples:
        >>> from geoops.qa import MaskSnow
        >>> # Landsat-8 QA_PIXEL: bit 5 is "snow / ice".
        >>> mask = MaskSnow(qa_band="QA_PIXEL", bits=[5])(landsat_stack)
    """

MaskWater

Bases: _QAMask

Return True where a QA band marks water pixels.

Examples:

>>> from geoops.qa import MaskWater
>>> # Landsat-8 QA_PIXEL: bit 7 is "water".
>>> mask = MaskWater(qa_band="QA_PIXEL", bits=[7])(landsat_stack)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class MaskWater(_QAMask):
    """Return True where a QA band marks water pixels.

    Examples:
        >>> from geoops.qa import MaskWater
        >>> # Landsat-8 QA_PIXEL: bit 7 is "water".
        >>> mask = MaskWater(qa_band="QA_PIXEL", bits=[7])(landsat_stack)
    """

OmniCloudMask

Bases: Operator

Placeholder for the optional ML-based OmniCloudMask detector.

Raises ImportError on call.

Examples:

>>> from geoops.qa import OmniCloudMask
>>> OmniCloudMask(checkpoint="default").get_config()
{'checkpoint': 'default'}
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class OmniCloudMask(Operator):
    """Placeholder for the optional ML-based OmniCloudMask detector.

    Raises ``ImportError`` on call.

    Examples:
        >>> from geoops.qa import OmniCloudMask
        >>> OmniCloudMask(checkpoint="default").get_config()
        {'checkpoint': 'default'}
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a learned detector over bands and neighbourhoods
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, checkpoint: str = "default") -> None:
        self.checkpoint = checkpoint

    def _apply(self, gt: GeoArray) -> GeoArray:
        raise ImportError(
            "OmniCloudMask requires the optional ML mask extra, which is not "
            "packaged in this release."
        )

S2Cloudless

Bases: Operator

Placeholder for the optional ML-based s2cloudless mask.

Raises ImportError on call. Reserved for the future [cloud-ml] extra so that pipelines can be configured today and light up once the dependency is installed.

Examples:

>>> from geoops.qa import S2Cloudless
>>> S2Cloudless(threshold=0.4).get_config()
{'threshold': 0.4}
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class S2Cloudless(Operator):
    """Placeholder for the optional ML-based s2cloudless mask.

    Raises ``ImportError`` on call. Reserved for the future
    ``[cloud-ml]`` extra so that pipelines can be configured today and
    light up once the dependency is installed.

    Examples:
        >>> from geoops.qa import S2Cloudless
        >>> S2Cloudless(threshold=0.4).get_config()
        {'threshold': 0.4}
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a learned detector over bands and neighbourhoods
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    # Calling this Operator raises ImportError — its `get_config` is
    # still serialisable, but actually instantiating the underlying
    # model is closure-like. Mark non-YAML so callers don't accidentally
    # depend on it round-tripping through configs in production.
    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, threshold: float = 0.4) -> None:
        self.threshold = threshold

    def _apply(self, gt: GeoArray) -> GeoArray:
        raise ImportError(
            "S2Cloudless requires the optional ML mask extra, which is not "
            "packaged in this release."
        )

S2QA60

Bases: Operator

Sentinel-2 L1C QA60 cloud + cirrus mask preset.

QA60 (per ESA's S2 L1C product specification) encodes opaque clouds in bit 10 and cirrus in bit 11 (SENSOR_QA_REGISTRY["s2_qa60"]). Returns True where any requested targets bit is set.

Note: QA60 is unreliable / zeroed-out on newer processing baselines (≥ 04.00). Prefer the L2A SCL band (S2SCL) or an ML-based detector when available.

Accepts a GeoArray or a plain np.ndarray and returns the same carrier kind; plain arrays need an integer qa_band (the default is a band name, which requires GeoArray attrs).

Parameters:

Name Type Description Default
qa_band int | str

Band selector for QA60 within the input stack.

'QA60'
targets Sequence[str]

Target names to OR together ("cloud", "cirrus"). Default both.

('cloud', 'cirrus')
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

Examples:

>>> from geoops.qa import S2QA60
>>> mask = S2QA60()(s2_l1c_stack_with_qa60_appended)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class S2QA60(Operator):
    """Sentinel-2 L1C QA60 cloud + cirrus mask preset.

    QA60 (per ESA's S2 L1C product specification) encodes opaque clouds
    in bit 10 and cirrus in bit 11 (``SENSOR_QA_REGISTRY["s2_qa60"]``).
    Returns True where any requested ``targets`` bit is set.

    Note: QA60 is unreliable / zeroed-out on newer processing baselines
    (≥ 04.00). Prefer the L2A SCL band (`S2SCL`) or an ML-based
    detector when available.

    Accepts a ``GeoArray`` or a plain ``np.ndarray`` and returns the
    same carrier kind; plain arrays need an integer ``qa_band`` (the
    default is a band *name*, which requires GeoArray attrs).

    Args:
        qa_band: Band selector for QA60 within the input stack.
        targets: Target names to OR together (``"cloud"``,
            ``"cirrus"``). Default both.
        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.

    Examples:
        >>> from geoops.qa import S2QA60
        >>> mask = S2QA60()(s2_l1c_stack_with_qa60_appended)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # reads the QA60 band only
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    def __init__(
        self,
        *,
        qa_band: int | str = "QA60",
        targets: Sequence[str] = ("cloud", "cirrus"),
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.qa_band = qa_band
        self.targets = tuple(str(target) for target in targets)
        self.dim = band_dim(dim, axis, "S2QA60")

    def _apply(self, gt: Any) -> Any:
        return _preset_mask(gt, self, "s2_qa60", "S2QA60")

    def get_config(self) -> dict[str, Any]:
        return {
            "qa_band": self.qa_band,
            "targets": list(self.targets),
            "dim": self.dim,
        }

S2SCL

Bases: Operator

Sentinel-2 L2A SCL preset that masks the requested targets classes.

Returns True for pixels whose SCL class belongs to any of the named targets (see SENSOR_QA_REGISTRY["s2_scl"], derived from geoops.qa.SCL). The default targets are every class except vegetation, soil and water — i.e. vegetation, soil, and water are kept.

Accepts a GeoArray or a plain np.ndarray and returns the same carrier kind; plain arrays need an integer qa_band.

Parameters:

Name Type Description Default
qa_band int | str

Band selector for the SCL band.

'SCL'
targets Sequence[str]

Class names to mask out. See SENSOR_QA_REGISTRY["s2_scl"] for the full vocabulary.

_DEFAULT_TARGETS
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

Examples:

>>> from geoops.qa import S2SCL
>>> # Default: mask everything that isn't vegetation/soil/water.
>>> mask = S2SCL()(s2_l2a_with_scl)
>>> # Custom: mask clouds, cirrus and cloud shadow only.
>>> mask = S2SCL(targets=["cloud", "cirrus", "cloud_shadow"])(s2_l2a)
Source code in packages/geotoolz-ops/src/geoops/qa/_src/operators.py
class S2SCL(Operator):
    """Sentinel-2 L2A SCL preset that masks the requested ``targets`` classes.

    Returns True for pixels whose SCL class belongs to any of the named
    ``targets`` (see ``SENSOR_QA_REGISTRY["s2_scl"]``, derived from
    `geoops.qa.SCL`). The default targets are every class except
    vegetation, soil and water — i.e. vegetation, soil, and water are
    kept.

    Accepts a ``GeoArray`` or a plain ``np.ndarray`` and returns the
    same carrier kind; plain arrays need an integer ``qa_band``.

    Args:
        qa_band: Band selector for the SCL band.
        targets: Class names to mask out. See
            ``SENSOR_QA_REGISTRY["s2_scl"]`` for the full vocabulary.
        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.

    Examples:
        >>> from geoops.qa import S2SCL
        >>> # Default: mask everything that isn't vegetation/soil/water.
        >>> mask = S2SCL()(s2_l2a_with_scl)
        >>> # Custom: mask clouds, cirrus and cloud shadow only.
        >>> mask = S2SCL(targets=["cloud", "cirrus", "cloud_shadow"])(s2_l2a)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # reads the SCL band only
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    _DEFAULT_TARGETS: ClassVar[tuple[str, ...]] = (
        "no_data",
        "saturated",
        "dark",
        "cloud_shadow",
        "unclassified",
        "cloud",
        "cirrus",
        "snow",
    )

    def __init__(
        self,
        *,
        qa_band: int | str = "SCL",
        targets: Sequence[str] = _DEFAULT_TARGETS,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.qa_band = qa_band
        self.targets = tuple(str(name) for name in targets)
        self.dim = band_dim(dim, axis, "S2SCL")

    def _apply(self, gt: Any) -> Any:
        return _preset_mask(gt, self, "s2_scl", "S2SCL")

    def get_config(self) -> dict[str, Any]:
        return {
            "qa_band": self.qa_band,
            "targets": list(self.targets),
            "dim": self.dim,
        }

SCL

Bases: IntEnum

Sentinel-2 L2A Scene Classification Layer class IDs.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/scl.py
class SCL(IntEnum):
    """Sentinel-2 L2A Scene Classification Layer class IDs."""

    NO_DATA = 0
    SATURATED_OR_DEFECTIVE = 1
    DARK_AREA_PIXELS = 2
    CLOUD_SHADOWS = 3
    VEGETATION = 4
    NOT_VEGETATED = 5
    WATER = 6
    UNCLASSIFIED = 7
    CLOUD_MEDIUM_PROBABILITY = 8
    CLOUD_HIGH_PROBABILITY = 9
    THIN_CIRRUS = 10
    SNOW = 11

flagged_band_count(bandmask)

Number of bands flagged in each pixel's packed band mask.

nᵢⱼ = ∑_k b_ijk, the bits set across the pixel's bytes.

EMIT's band_mask packs one bit per spectral band into 36 bytes for its 285 bands (EMIT L2A User Guide, Table 3-3); a set bit marks a band interpolated over a bad detector element or saturation. The count does not depend on the bit order within a byte.

Algorithm
  1. Look up the bits set in every byte value in a 256-entry table.
  2. Gather it for each byte and sum over the bytes.

The table avoids np.unpackbits, which would allocate eight times the input.

Parameters:

Name Type Description Default
bandmask UInt8[ndarray, 'row col byte']

Packed band mask, the bytes on the last axis.

required

Returns:

Type Description
Int[ndarray, 'row col']

The count nᵢⱼ, int64.

Examples:

>>> bandmask = np.array([[[0b1010_0000, 0b0000_0001]]], dtype=np.uint8)
>>> flagged_band_count(bandmask).tolist()
[[3]]
Source code in packages/geotoolz-ops/src/geoops/qa/_src/array.py
def flagged_band_count(
    bandmask: UInt8[np.ndarray, "row col byte"],
) -> Int[np.ndarray, "row col"]:
    """Number of bands flagged in each pixel's packed band mask.

    nᵢⱼ = ∑_k b_ijk, the bits set across the pixel's bytes.

    EMIT's ``band_mask`` packs one bit per spectral band into 36 bytes for
    its 285 bands (EMIT L2A User Guide, Table 3-3); a set bit marks a band
    interpolated over a bad detector element or saturation. The count does
    not depend on the bit order within a byte.

    Algorithm:
        1. Look up the bits set in every byte value in a 256-entry table.
        2. Gather it for each byte and sum over the bytes.

    The table avoids ``np.unpackbits``, which would allocate eight times
    the input.

    Args:
        bandmask: Packed band mask, the bytes on the last axis.

    Returns:
        The count nᵢⱼ, ``int64``.

    Examples:
        >>> bandmask = np.array([[[0b1010_0000, 0b0000_0001]]], dtype=np.uint8)
        >>> flagged_band_count(bandmask).tolist()
        [[3]]
    """
    packed = np.asarray(bandmask)
    if packed.dtype != np.uint8:
        raise TypeError(
            f"flagged_band_count: bandmask must be uint8, got {packed.dtype}"
        )
    # bits set in each byte of each pixel
    flagged = _POPCOUNT[packed]
    # nᵢⱼ = ∑_k b_ijk
    return einx.sum("row col [byte]", flagged)

mask_from_band_count(count, *, valid=None, dilation=10)

Pixels with more flagged bands than their column's baseline, dilated.

satᵢⱼ = [nᵢⱼ - m_j > 0] with m_j = minᵢ nᵢⱼ over valid rows, grown by dilation pixels in city-block distance.

Algorithm
  1. Take each column's minimum count over its valid rows.
  2. Flag valid pixels above their column's minimum.
  3. Threshold the city-block distance to the flagged pixels.

EMIT is a push-broom instrument, so column j is one cross-track detector element in every row. A dead or hot element flags the same bands down its whole column, so the column minimum is the static part and what a pixel has above it is transient, in practice saturation. Compute the mask in swath geometry, before any orthorectification: on a map grid the columns no longer follow the detector. dilation=10 is SPIIRE's default, 600 m on EMIT's 60 m pixels.

Invalid pixels never set a baseline and are never flagged, not even by the dilation, and a column with no valid row is all False.

Parameters:

Name Type Description Default
count Int[ndarray, 'row col']

Flagged-band count nᵢⱼ, from :func:flagged_band_count.

required
valid Bool[ndarray, 'row col'] | None

Pixels to use; None uses all.

None
dilation int

Growth radius r in pixels.

10

Returns:

Type Description
Bool[ndarray, 'row col']

The mask; True means mask out.

Raises:

Type Description
ValueError

If dilation is negative, or valid does not match the shape of count.

Examples:

A column with three bands flagged in every row, and one pixel with two more:

>>> count = np.full((5, 5), 3)
>>> count[2, 2] = 5
>>> mask = mask_from_band_count(count, dilation=1)
>>> mask.astype(int).tolist()[1:4]
[[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]]
Source code in packages/geotoolz-ops/src/geoops/qa/_src/array.py
def mask_from_band_count(
    count: Int[np.ndarray, "row col"],
    *,
    valid: Bool[np.ndarray, "row col"] | None = None,
    dilation: int = 10,
) -> Bool[np.ndarray, "row col"]:
    """Pixels with more flagged bands than their column's baseline, dilated.

    satᵢⱼ = [nᵢⱼ - m_j > 0] with m_j = minᵢ nᵢⱼ over valid rows, grown by
    ``dilation`` pixels in city-block distance.

    Algorithm:
        1. Take each column's minimum count over its valid rows.
        2. Flag valid pixels above their column's minimum.
        3. Threshold the city-block distance to the flagged pixels.

    EMIT is a push-broom instrument, so column j is one cross-track detector
    element in every row. A dead or hot element flags the same bands down
    its whole column, so the column minimum is the static part and what a
    pixel has above it is transient, in practice saturation. Compute the
    mask in swath geometry, before any orthorectification: on a map grid
    the columns no longer follow the detector. ``dilation=10`` is SPIIRE's
    default, 600 m on EMIT's 60 m pixels.

    Invalid pixels never set a baseline and are never flagged, not even by
    the dilation, and a column with no valid row is all ``False``.

    Args:
        count: Flagged-band count nᵢⱼ, from :func:`flagged_band_count`.
        valid: Pixels to use; ``None`` uses all.
        dilation: Growth radius r in pixels.

    Returns:
        The mask; True means mask out.

    Raises:
        ValueError: If ``dilation`` is negative, or ``valid`` does not match
            the shape of ``count``.

    Examples:
        A column with three bands flagged in every row, and one pixel with
        two more:

        >>> count = np.full((5, 5), 3)
        >>> count[2, 2] = 5
        >>> mask = mask_from_band_count(count, dilation=1)
        >>> mask.astype(int).tolist()[1:4]
        [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]]
    """
    if dilation < 0:
        raise ValueError(f"mask_from_band_count: dilation must be >= 0, got {dilation}")
    counts = np.asarray(count)
    if valid is None:
        valid_mask = np.ones(counts.shape, dtype=bool)
    else:
        valid_mask = np.asarray(valid, dtype=bool)
        if valid_mask.shape != counts.shape:
            raise ValueError(
                "mask_from_band_count: valid has shape "
                f"{valid_mask.shape}, count has {counts.shape}"
            )
    # invalid pixels never set a baseline
    largest = np.iinfo(np.int64).max
    masked = np.where(valid_mask, counts.astype(np.int64), largest)
    # m_j = minᵢ nᵢⱼ over valid rows
    baseline = einx.min("[row] col", masked)
    # satᵢⱼ = [nᵢⱼ - m_j > 0], valid pixels only
    excess = einx.subtract("row col, col -> row col", masked, baseline)
    saturated = valid_mask & (excess > 0)
    if not bool(saturated.any()):
        return saturated
    # city-block distance to the nearest saturated pixel
    distance = ndimage.distance_transform_cdt(~saturated, metric="taxicab")
    # maskᵢⱼ = [d₁((i, j), sat) ≤ r], on valid pixels only
    return (distance <= dilation) & valid_mask

mask_from_bit_field(qa, bits, values, *, invert=False)

Decode a contiguous multi-bit QA field by value membership.

Several sensor QA layers pack a small categorical field into two or more adjacent bits — e.g. MODIS state_1km bits [0, 1] are a 2-bit "cloud state" field (00 clear, 01 cloudy, 10 mixed, 11 not-set/assumed-clear). OR-ing the bits independently (the standard Landsat semantics) is wrong here: a "mixed" pixel has bit 1 set but is not cloudy.

This helper extracts the bit field as an integer and returns True where its value is in values.

Parameters:

Name Type Description Default
qa Int[ndarray, '*batch h w']

Integer QA array.

required
bits Sequence[int]

Bit positions, ordered LSB → MSB. The field width is len(bits) and the bits must be contiguous and in ascending order.

required
values Sequence[int]

Integer field-values to match. For MODIS cloud, values=(1, 2) matches "cloudy" and "mixed".

required
invert bool

When True, flip the result.

False

Returns:

Type Description
Bool[ndarray, '*batch h w']

Boolean array of the same shape as qa.

Raises:

Type Description
ValueError

If bits is empty, not contiguous, not ascending, or if values is empty.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/array.py
def mask_from_bit_field(
    qa: Int[np.ndarray, "*batch h w"],
    bits: Sequence[int],
    values: Sequence[int],
    *,
    invert: bool = False,
) -> Bool[np.ndarray, "*batch h w"]:
    """Decode a contiguous multi-bit QA field by value membership.

    Several sensor QA layers pack a small categorical field into two or
    more adjacent bits — e.g. MODIS ``state_1km`` bits ``[0, 1]`` are a
    2-bit "cloud state" field (``00`` clear, ``01`` cloudy, ``10``
    mixed, ``11`` not-set/assumed-clear). OR-ing the bits independently
    (the standard Landsat semantics) is wrong here: a "mixed" pixel has
    bit 1 set but is not cloudy.

    This helper extracts the bit field as an integer and returns True
    where its value is in ``values``.

    Args:
        qa: Integer QA array.
        bits: Bit positions, ordered LSB → MSB. The field width is
            ``len(bits)`` and the bits must be contiguous and in
            ascending order.
        values: Integer field-values to match. For MODIS ``cloud``,
            ``values=(1, 2)`` matches "cloudy" and "mixed".
        invert: When True, flip the result.

    Returns:
        Boolean array of the same shape as ``qa``.

    Raises:
        ValueError: If ``bits`` is empty, not contiguous, not
            ascending, or if ``values`` is empty.
    """
    bits_tuple = tuple(int(b) for b in bits)
    if not bits_tuple:
        raise ValueError("mask_from_bit_field: `bits` must not be empty")
    for prev, nxt in pairwise(bits_tuple):
        if nxt != prev + 1:
            raise ValueError(
                "mask_from_bit_field: `bits` must be contiguous and ascending; "
                f"got {bits_tuple}"
            )
    if any(b < 0 for b in bits_tuple):
        raise ValueError("mask_from_bit_field: bit positions must be non-negative")
    values_tuple = tuple(int(v) for v in values)
    if not values_tuple:
        raise ValueError("mask_from_bit_field: `values` must not be empty")

    shift = bits_tuple[0]
    width = len(bits_tuple)
    field = (_as_int64(qa) >> shift) & ((1 << width) - 1)
    out = _isin(field, values_tuple)
    return ~out if invert else out

mask_from_qa_bits(qa, bits, *, invert=False)

Decode a Landsat-style bitmask QA band.

Returns a boolean array where any of the supplied bits is set in the QA value. For Landsat-8 QA_PIXEL the bit assignments (Collection-2 Level-2) are:

===== ========================== Bit Meaning ===== ========================== 0 Fill / no-data 1 Dilated Cloud 2 Cirrus (high confidence) 3 Cloud 4 Cloud Shadow 5 Snow 6 Clear 7 Water ===== ==========================

So mask_from_qa_bits(qa, bits=[3, 4]) returns True where the pixel is either cloudy or in cloud shadow.

The math is a single (qa & bitmask) != 0 per bit, OR-ed together — vectorised over the whole array.

Parameters:

Name Type Description Default
qa Int[ndarray, '*dims']

Integer QA array (any integer dtype). Typically (H, W); works for arbitrary shape.

required
bits Sequence[int]

Sequence of bit positions to test. The function returns True where ANY of these is set.

required
invert bool

When True, flip the result. Useful for "clear" masks (mask_from_qa_bits(qa, [3,4,5], invert=True)).

False

Returns:

Type Description
Bool[ndarray, '*dims']

Boolean array of the same shape as qa.

References

USGS, "Landsat 8-9 Collection 2 Level-2 Science Product Guide", LSDS-1619, 2022.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/array.py
def mask_from_qa_bits(
    qa: Int[np.ndarray, "*dims"],
    bits: Sequence[int],
    *,
    invert: bool = False,
) -> Bool[np.ndarray, "*dims"]:
    r"""Decode a Landsat-style bitmask QA band.

    Returns a boolean array where any of the supplied ``bits`` is set
    in the QA value. For Landsat-8 ``QA_PIXEL`` the bit assignments
    (Collection-2 Level-2) are:

    ===== ==========================
    Bit   Meaning
    ===== ==========================
    0     Fill / no-data
    1     Dilated Cloud
    2     Cirrus (high confidence)
    3     Cloud
    4     Cloud Shadow
    5     Snow
    6     Clear
    7     Water
    ===== ==========================

    So ``mask_from_qa_bits(qa, bits=[3, 4])`` returns True where the
    pixel is *either* cloudy *or* in cloud shadow.

    The math is a single ``(qa & bitmask) != 0`` per bit, OR-ed
    together — vectorised over the whole array.

    Args:
        qa: Integer QA array (any integer dtype). Typically
            ``(H, W)``; works for arbitrary shape.
        bits: Sequence of bit positions to test. The function returns
            True where ANY of these is set.
        invert: When True, flip the result. Useful for "clear" masks
            (``mask_from_qa_bits(qa, [3,4,5], invert=True)``).

    Returns:
        Boolean array of the same shape as ``qa``.

    References:
        USGS, "Landsat 8-9 Collection 2 Level-2 Science Product
        Guide", LSDS-1619, 2022.
    """
    bitmask = 0
    for b in bits:
        if b < 0:
            raise ValueError(f"bit position must be non-negative; got {b}")
        bitmask |= 1 << int(b)
    out = (_as_int64(qa) & bitmask) != 0
    return ~out if invert else out

mask_from_scl(scl, classes, *, invert=False)

Decode a Sentinel-2 SCL band by class membership.

Returns True where the SCL value equals any of the listed classes. With invert=True, returns True where the SCL value is not in the list — handy for "keep only these classes" masks.

SCL class IDs come from geoops.qa.SCL (an IntEnum). Mixing raw ints and enum members is fine — they're cast to int here.

Parameters:

Name Type Description Default
scl Int[ndarray, '*dims']

SCL band, integer dtype, typically (H, W) or (1, H, W).

required
classes Sequence[int]

SCL class IDs to match (raw ints or SCL members).

required
invert bool

When True, return True where SCL value is NOT in classes (keep-only-these mask).

False

Returns:

Type Description
Bool[ndarray, '*dims']

Boolean array of the same shape as scl.

Source code in packages/geotoolz-ops/src/geoops/qa/_src/array.py
def mask_from_scl(
    scl: Int[np.ndarray, "*dims"],
    classes: Sequence[int],
    *,
    invert: bool = False,
) -> Bool[np.ndarray, "*dims"]:
    """Decode a Sentinel-2 SCL band by class membership.

    Returns True where the SCL value equals any of the listed
    ``classes``. With ``invert=True``, returns True where the SCL value
    is *not* in the list — handy for "keep only these classes" masks.

    SCL class IDs come from `geoops.qa.SCL` (an IntEnum). Mixing raw
    ints and enum members is fine — they're cast to ``int`` here.

    Args:
        scl: SCL band, integer dtype, typically ``(H, W)`` or
            ``(1, H, W)``.
        classes: SCL class IDs to match (raw ints or `SCL` members).
        invert: When True, return True where SCL value is NOT in
            ``classes`` (keep-only-these mask).

    Returns:
        Boolean array of the same shape as ``scl``.
    """
    if len(classes) == 0:
        raise ValueError("mask_from_scl: `classes` must not be empty")
    out = _isin(scl, [int(c) for c in classes])
    return ~out if invert else out

Sensor registry

Preset QA source Default mask targets Reference
S2QA60 Sentinel-2 L1C QA60 bitmask (bit 10 cloud, 11 cirrus) cloud + cirrus ESA S2 L1C product spec
S2SCL Sentinel-2 L2A SCL classes (registry derived from SCL_TARGETS) every target except vegetation (4), soil (5), water (6) Sen2Cor product spec
LandsatQA_PIXEL (sensor=l89) Landsat 8/9 C2 QA_PIXEL cloud (bit 3), cloud shadow (bit 4), cirrus (bit 2) USGS LSDS-1619
LandsatQA_PIXEL (sensor=l7) Landsat 4-7 C2 QA_PIXEL (no cirrus bit) cloud (bit 3), cloud shadow (bit 4) USGS LSDS-1618
MODISStateQA MODIS state_1km / state_500m cloud (bits [0,1] field, values 1,2) + cloud shadow (bit 2) MOD09 User's Guide, Table 12
EMITL2AMask EMIT L2A mask, one flag per band (0 cloud, 1 cirrus, 2 water, 3 spacecraft, 4 dilated cloud, 7 aggregate; 5 and 6 are AOD and water vapour) cloud + cirrus + water EMIT L2A User Guide V1.0 (JPL D-107863), Table 3-4
EMITBandMask EMIT band_mask, one bit per spectral band in 36 bytes flagged bands above the column baseline, dilated by 10 pixels EMIT L2A User Guide V1.0, Table 3-3

All QA mask operators return boolean masks matching the input carrier: GeoArray in (CRS/transform preserved, fill_value=False), plain np.ndarray in, plain boolean array out. The convention is True means "mask this pixel out" (see Mask polarity).

MODIS bit-field semantics

MODIS state_1km packs categorical fields into multi-bit slots:

  • Bits [0, 1] (2 bits): cloud state — 0=clear, 1=cloudy, 2=mixed, 3=not-set.
  • Bit 2: cloud shadow.
  • Bits [8, 9] (2 bits): cirrus level — 0=none, 1=small, 2=average, 3=high.

OR-ing the bits individually (the standard Landsat semantics) would flag value 3 (not-set) as cloudy, which is wrong. MODISStateQA therefore decodes these as field values via mask_from_bit_field.

EMIT saturation

EMIT is a push-broom instrument, so each column of a swath is one cross-track detector element. A dead or hot element flags the same bands in every row of its column, so EMITBandMask takes each column's smallest flagged-band count as its static baseline and flags what a pixel has above it, which in practice is saturation (flares, glint, bright roofs). It then grows the mask by dilation pixels in city-block distance. Compute it in swath geometry, before orthorectifying, while the columns still follow the detector.