Skip to content

geoops.augment — RS-safe augmentations

Curated augmentation operators for training on remote-sensing GeoArray patches. Spatial operators preserve CRS and either preserve the existing transform or update it consistently; radiometric operators treat bands as physical measurements instead of generic RGB channels.

Quick pipeline

import geoops as gz

augment = gz.augment.Compose(
    augmentations=[
        gz.augment.RandomFlip(p_horizontal=0.5, p_vertical=0.5),
        gz.augment.RandomRotate90(p=0.75),
        gz.augment.BrightnessJitter(factor=(0.95, 1.05), per_band=True),
        gz.augment.GaussianNoise(sigma=0.01),
    ]
)

augmented_patch = augment(training_patch, seed=0)

Before / after samples

Family Before After
Geometry patch RandomFlip(p_horizontal=1)(patch) mirrors pixels and updates the affine transform.
Geometry patch RandomRotate90(p=1)(patch, seed=0) uses one of np.rot90(..., k=1..3) and updates transform orientation.
Geometry patch RandomCrop(size=(256, 256))(patch, seed=0) returns a smaller georeferenced chip.
Geometry patch RandomShift(max_shift=(8, 8))(patch, seed=0) reads a shifted fixed-size window with padding at edges.
Radiometric patch BrightnessJitter(per_band=True)(patch, seed=0) samples one gain per band.
Radiometric patch ContrastJitter(per_band=False)(patch, seed=0) applies one contrast factor to every band.
Noise patch GaussianNoise(sigma=0.01)(patch, seed=0) adds reproducible additive sensor noise.
Noise patch SpeckleNoise(sigma=0.05)(patch, seed=0) applies multiplicative SAR-style noise.
Band-level patch BandDropout(p=0.1, fill_value=0)(patch, seed=0) independently masks bands.
Band-level patch BandJitter(groups={"swir": ["B11", "B12"]})(patch, seed=0) only permutes configured band groups.
RS-specific patch SunAngleJitter(delta_sza_deg=(-3, 3))(patch, seed=0) rescales reflectance for a simulated SZA shift.
RS-specific patch AtmosphericHaze(intensity=(0, 0.05))(patch, seed=0) adds stronger haze to shorter wavelengths.
RS-specific patch SimulatedClouds(coverage=(0, 0.2))(patch, seed=0) blends in a smooth synthetic cloud field.
Mixing patch, *pool CutMix(p=0.5)(patch, other_patch, seed=0) pastes a rectangle from a donor drawn from the positional pool, every donor on the same pixel grid (shape, CRS and transform).

Seeding contract

Every random operator accepts a constructor seed and a per-call seed override. The constructor seed starts a stream held on the instance: each call draws the next augmentation, so a seeded operator varies from sample to sample while two operators built with the same seed replay the same sequence. A per-call seed is a deterministic one-off draw that leaves the stream untouched:

import geoops as gz

op = gz.augment.GaussianNoise(sigma=0.01, seed=1)
a, b = op(patch), op(patch)          # different noise, reproducible sequence
same_a = op(patch, seed=42)
same_b = op(patch, seed=42)          # identical to same_a

get_config only records the constructor seed, so a reloaded operator restarts its stream. A seeded Compose owns its children's draws (it forwards a derived per-call seed to each child whose _apply accepts a seed); an unseeded one lets each child use its own stream.

Compose is a probability-gated pipekit_ops.Sequential. It lives only at gz.augment.Compose (not gz.Compose, which would read as pipekit's right-to-left compose). compose | op keeps the gate, but pipekit flattens a Sequential on the right of |, so write gz.Sequential([op, compose]) rather than op | compose.

Use the same seed for multiple geometric pipelines when different modalities must receive identical spatial transforms (call them in lockstep).

Composer

geoops.augment._src.operators.Compose

Bases: Sequential

Apply augmentations sequentially behind a pipeline probability gate.

A :class:pipekit_ops.Sequential whose whole chain runs with probability p and whose children can be seeded from one top-level seed.

Seeding follows the module contract. When Compose is seeded — by a per-call seed (one-off) or a constructor seed (its own stream, advancing each call) — it owns the randomness of the whole chain: it draws one child seed per augmentation and forwards it as that child's per-call seed, so the same top-level seed always reproduces the same chain of inner draws and the children's own streams are left untouched. An unseeded Compose forwards nothing, so each child draws from its own stream (honouring any child seed). A child receives a seed only when its _apply accepts one (the per-call seed goes to _apply, not __init__), so deterministic operators and samplers whose seed is constructor-only are called plainly.

get_config emits the children's nested configs (via :class:~pipekit_ops.Sequential) under augmentations. Compose is a container, so it is not forbid_in_yaml itself; a flagged child is found structurally by pipekit's walker.

Composition: compose | op keeps the gate (Sequential([compose, op])), but pipekit flattens a Sequential on the right of |, so op | compose would splice the children in without the gate — write Sequential([op, compose]) instead. Slicing (compose[1:]) likewise returns an ungated Sequential of the children.

The carrier is whatever the children accept: a plain np.ndarray input passes through unchanged when the probability check skips the pipeline, and is otherwise handed to the children as-is.

Parameters:

Name Type Description Default
augmentations list[Operator]

Operators applied in order.

required
p float

Probability of applying the whole pipeline. Default 1.0.

1.0
seed int | None

Seed of the pipeline's own stream (see above); None leaves each child to its own stream.

None

Raises:

Type Description
TypeError

If a child is not an Operator (e.g. a reloaded nested-config dict) or is a stateful operator.

Examples:

>>> import geoops as gz
>>> pipe = gz.augment.Compose(
...     augmentations=[
...         gz.augment.RandomFlip(),
...         gz.augment.GaussianNoise(sigma=0.01),
...     ],
...     p=1.0,
...     seed=0,
... )
>>> out = pipe(patch)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class Compose(Sequential):
    """Apply augmentations sequentially behind a pipeline probability gate.

    A :class:`pipekit_ops.Sequential` whose whole chain runs with probability
    ``p`` and whose children can be seeded from one top-level seed.

    Seeding follows the module contract. When ``Compose`` is seeded — by
    a per-call ``seed`` (one-off) or a constructor ``seed`` (its own
    stream, advancing each call) — it owns the randomness of the whole
    chain: it draws one child seed per augmentation and forwards it as
    that child's per-call ``seed``, so the same top-level seed always
    reproduces the same chain of inner draws and the children's own
    streams are left untouched. An unseeded ``Compose`` forwards nothing,
    so each child draws from its own stream (honouring any child
    ``seed``). A child receives a ``seed`` only when its ``_apply``
    accepts one (the per-call ``seed`` goes to ``_apply``, not
    ``__init__``), so deterministic operators and samplers whose seed is
    constructor-only are called plainly.

    ``get_config`` emits the children's nested configs (via
    :class:`~pipekit_ops.Sequential`) under ``augmentations``. ``Compose`` is
    a container, so it is not ``forbid_in_yaml`` itself; a flagged child
    is found structurally by pipekit's walker.

    Composition: ``compose | op`` keeps the gate (``Sequential([compose,
    op])``), but pipekit flattens a ``Sequential`` on the right of ``|``,
    so ``op | compose`` would splice the children in *without* the gate —
    write ``Sequential([op, compose])`` instead. Slicing (``compose[1:]``)
    likewise returns an ungated ``Sequential`` of the children.

    The carrier is whatever the children accept: a plain ``np.ndarray``
    input passes through unchanged when the probability check skips the
    pipeline, and is otherwise handed to the children as-is.

    Args:
        augmentations: Operators applied in order.
        p: Probability of applying the whole pipeline. Default ``1.0``.
        seed: Seed of the pipeline's own stream (see above); ``None``
            leaves each child to its own stream.

    Raises:
        TypeError: If a child is not an ``Operator`` (e.g. a reloaded
            nested-config dict) or is a stateful operator.

    Examples:
        >>> import geoops as gz
        >>> pipe = gz.augment.Compose(
        ...     augmentations=[
        ...         gz.augment.RandomFlip(),
        ...         gz.augment.GaussianNoise(sigma=0.01),
        ...     ],
        ...     p=1.0,
        ...     seed=0,
        ... )
        >>> out = pipe(patch)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the widest of its members: crops and flips regrid,
    # ContrastJitter and SimulatedClouds read the whole scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    def __init__(
        self,
        *,
        augmentations: list[Operator],
        p: float = 1.0,
        seed: int | None = None,
    ) -> None:
        _check_probability(p, "p")
        for i, op in enumerate(augmentations):
            # A YAML / Hydra loader hands back the nested {"class", "config"}
            # payloads as dicts; fail here rather than at apply time.
            require_operator(op, "Compose", f"augmentations[{i}]")
            if getattr(op, "_is_stateful", False):
                raise TypeError(
                    f"Compose.augmentations[{i}] is a stateful operator "
                    f"({type(op).__name__}); Compose does not thread state."
                )
        super().__init__(list(augmentations))
        self.p = p
        self.seed = seed

    @property
    def augmentations(self) -> list[Operator]:
        """The child operators, in application order."""
        return self.operators

    def _apply(  # ty: ignore[invalid-method-override]
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        seeded = seed is not None or self.seed is not None
        rng = _call_rng(self, seed)
        if rng.random() >= self.p:
            return gt

        out = gt
        child_seeds = rng.integers(0, np.iinfo(np.int64).max, len(self.operators))
        for op, child_seed in zip(self.operators, child_seeds, strict=True):
            if seeded and _apply_accepts_seed(op):
                out = op(out, seed=int(child_seed))
            else:
                out = op(out)
        return out

    def get_config(self) -> dict[str, Any]:
        return {
            "augmentations": super().get_config()["operators"],
            "p": self.p,
            "seed": self.seed,
        }

    def __or__(self, other: Operator) -> Sequential:
        """``compose | op`` -> ``Sequential([compose, op])`` (the gate is kept)."""
        if not isinstance(other, Operator):
            return NotImplemented
        if isinstance(other, Sequential) and not isinstance(other, Compose):
            return Sequential([self, *other.operators])
        return Sequential([self, other])

    def __repr__(self) -> str:
        inner = ", ".join(repr(op) for op in self.operators)
        return f"Compose(augmentations=[{inner}], p={self.p!r}, seed={self.seed!r})"

    def describe(self, indent: int = 0) -> str:
        pad = "  " * indent
        body = super().describe(indent).split("\n", 1)
        head = f"{pad}Compose(p={self.p!r}, seed={self.seed!r}, ["
        return "\n".join([head, *body[1:]]) if len(body) > 1 else f"{pad}{self!r}"

augmentations: list[Operator] property

The child operators, in application order.

__or__(other: Operator) -> Sequential

compose | op -> Sequential([compose, op]) (the gate is kept).

Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
def __or__(self, other: Operator) -> Sequential:
    """``compose | op`` -> ``Sequential([compose, op])`` (the gate is kept)."""
    if not isinstance(other, Operator):
        return NotImplemented
    if isinstance(other, Sequential) and not isinstance(other, Compose):
        return Sequential([self, *other.operators])
    return Sequential([self, other])

Geometry

geoops.augment._src.operators.RandomFlip

Bases: Operator

Randomly flip a GeoArray horizontally and/or vertically.

Preserves the CRS and updates the affine transform so the output pixel grid still maps to the same physical extent (identical bounds/footprint; the mirrored axis is anchored at the far pixel edge). Each axis flips independently with probability p_horizontal / p_vertical.

The pixel math is metadata-free, so a plain np.ndarray input is also accepted and returns the flipped plain array (no transform bookkeeping).

Parameters:

Name Type Description Default
p_horizontal float

Probability of flipping the last (x) axis.

0.5
p_vertical float

Probability of flipping the second-to-last (y) axis.

0.5
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None

Examples:

>>> import geoops as gz
>>> op = gz.augment.RandomFlip(p_horizontal=1.0, p_vertical=0.0, seed=0)
>>> out = op(patch)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class RandomFlip(Operator):
    """Randomly flip a GeoArray horizontally and/or vertically.

    Preserves the CRS and updates the affine ``transform`` so the output
    pixel grid still maps to the same physical extent (identical
    ``bounds``/footprint; the mirrored axis is anchored at the far pixel
    edge). Each axis flips independently with probability
    ``p_horizontal`` / ``p_vertical``.

    The pixel math is metadata-free, so a plain ``np.ndarray`` input is
    also accepted and returns the flipped plain array (no transform
    bookkeeping).

    Args:
        p_horizontal: Probability of flipping the last (x) axis.
        p_vertical: Probability of flipping the second-to-last (y) axis.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.

    Examples:
        >>> import geoops as gz
        >>> op = gz.augment.RandomFlip(p_horizontal=1.0, p_vertical=0.0, seed=0)
        >>> out = op(patch)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(
        self,
        *,
        p_horizontal: float = 0.5,
        p_vertical: float = 0.5,
        seed: int | None = None,
    ) -> None:
        _check_probability(p_horizontal, "p_horizontal")
        _check_probability(p_vertical, "p_vertical")
        self.p_horizontal = p_horizontal
        self.p_vertical = p_vertical
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "RandomFlip")
        rng = _call_rng(self, seed)
        arr = np.asarray(gt)
        out = arr
        transform = affine_of(gt) if isinstance(gt, GeoArray) else None
        height, width = arr.shape[-2], arr.shape[-1]

        if rng.random() < self.p_horizontal:
            out = np.flip(out, axis=-1)
            if transform is not None:
                transform = (
                    transform * Affine.translation(width, 0) * Affine.scale(-1, 1)
                )

        if rng.random() < self.p_vertical:
            out = np.flip(out, axis=-2)
            if transform is not None:
                transform = (
                    transform * Affine.translation(0, height) * Affine.scale(1, -1)
                )

        if out is arr:
            return gt
        # np.flip returns a view; copy so the output never aliases the input.
        out = out.copy()
        if transform is None:
            return out
        return _new_geoarray(gt, out, transform)

geoops.augment._src.operators.RandomRotate90

Bases: Operator

Randomly rotate by 90, 180, or 270 degrees.

Uses np.rot90 over the trailing two axes and composes the input transform with the matching rigid rotation so every output pixel still maps to its world location and the footprint is unchanged.

The pixel math is metadata-free, so a plain np.ndarray input is also accepted and returns the rotated plain array (no transform bookkeeping).

Parameters:

Name Type Description Default
p float

Probability of rotating; when triggered, k is drawn uniformly from {1, 2, 3} quarter-turns.

0.75
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None

Examples:

>>> import geoops as gz
>>> op = gz.augment.RandomRotate90(p=1.0, seed=0)
>>> out = op(patch)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class RandomRotate90(Operator):
    """Randomly rotate by 90, 180, or 270 degrees.

    Uses ``np.rot90`` over the trailing two axes and composes the input
    ``transform`` with the matching rigid rotation so every output pixel
    still maps to its world location and the footprint is unchanged.

    The pixel math is metadata-free, so a plain ``np.ndarray`` input is
    also accepted and returns the rotated plain array (no transform
    bookkeeping).

    Args:
        p: Probability of rotating; when triggered, k is drawn uniformly
            from {1, 2, 3} quarter-turns.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.

    Examples:
        >>> import geoops as gz
        >>> op = gz.augment.RandomRotate90(p=1.0, seed=0)
        >>> out = op(patch)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self, *, p: float = 0.75, seed: int | None = None) -> None:
        _check_probability(p, "p")
        self.p = p
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "RandomRotate90")
        rng = _call_rng(self, seed)
        if rng.random() >= self.p:
            return gt

        k = int(rng.integers(1, 4))
        arr = np.asarray(gt)
        # np.rot90 returns a view; copy so the output never aliases the input.
        out = np.rot90(arr, k=k, axes=(-2, -1)).copy()
        if not isinstance(gt, GeoArray):
            return out
        height, width = arr.shape[-2], arr.shape[-1]
        transform = rot90_transform(affine_of(gt), height, width, k)
        return _new_geoarray(gt, out, transform)

geoops.augment._src.operators.RandomCrop

Bases: Operator

Randomly crop a spatial window and update the transform.

Slices the GeoArray (gt[..., rows, cols]), so the output transform's translation reflects the crop origin (affine_of(gt) * (left, top) is the new upper-left world coordinate). CRS, dtype and band metadata are preserved.

The crop itself is pixel-space math, so a plain np.ndarray input is also accepted and returns the cropped plain array.

Parameters:

Name Type Description Default
size tuple[int, int]

(height, width) of the cropped window in pixels.

required
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None

Examples:

>>> import geoops as gz
>>> op = gz.augment.RandomCrop(size=(3, 4), seed=0)
>>> out = op(patch)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class RandomCrop(Operator):
    """Randomly crop a spatial window and update the transform.

    Slices the GeoArray (``gt[..., rows, cols]``), so the output
    transform's translation reflects the crop origin (``affine_of(gt) *
    (left, top)`` is the new upper-left world coordinate). CRS, dtype and
    band metadata are preserved.

    The crop itself is pixel-space math, so a plain ``np.ndarray`` input
    is also accepted and returns the cropped plain array.

    Args:
        size: ``(height, width)`` of the cropped window in pixels.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.

    Examples:
        >>> import geoops as gz
        >>> op = gz.augment.RandomCrop(size=(3, 4), seed=0)
        >>> out = op(patch)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self, *, size: tuple[int, int], seed: int | None = None) -> None:
        if size[0] <= 0 or size[1] <= 0:
            raise ValueError("size entries must be positive.")
        self.size = size
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "RandomCrop")
        crop_h, crop_w = self.size
        height, width = gt.shape[-2], gt.shape[-1]
        if crop_h > height or crop_w > width:
            raise ValueError("size must fit within the GeoArray spatial shape.")

        rng = _call_rng(self, seed)
        top = int(rng.integers(0, height - crop_h + 1))
        left = int(rng.integers(0, width - crop_w + 1))
        rows, cols = slice(top, top + crop_h), slice(left, left + crop_w)
        if isinstance(gt, GeoArray):
            # Slicing moves the transform to the crop origin; copy the data
            # so the output never aliases the input.
            cropped = gt[..., rows, cols]
            return cropped.replace(data=np.array(cropped.data, copy=True))
        return np.array(np.asarray(gt)[..., rows, cols], copy=True)

    def get_config(self) -> dict[str, Any]:
        return {"size": jsonable(self.size), "seed": self.seed}

geoops.augment._src.operators.RandomShift

Bases: Operator

Randomly shift a fixed-size spatial window in pixel units.

Reads a boundless window (gt.read_window(..., boundless=True)), so pixels shifted in from outside the original extent are padded with the carrier's fill_value and the transform tracks the new window origin. Geo-dependent: requires a georeferenced GeoArray input; a plain array raises TypeError, and a carrier without a fill_value raises ValueError when padding is needed.

Parameters:

Name Type Description Default
max_shift tuple[int, int]

(max_dy, max_dx) maximum absolute shift per axis, in pixels. Each shift is drawn uniformly from [-max, +max].

required
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class RandomShift(Operator):
    """Randomly shift a fixed-size spatial window in pixel units.

    Reads a boundless window (``gt.read_window(..., boundless=True)``), so
    pixels shifted in from outside the original extent are padded with the
    carrier's ``fill_value`` and the transform tracks the new window
    origin. Geo-dependent: requires a georeferenced ``GeoArray`` input; a
    plain array raises ``TypeError``, and a carrier without a
    ``fill_value`` raises ``ValueError`` when padding is needed.

    Args:
        max_shift: ``(max_dy, max_dx)`` maximum absolute shift per axis,
            in pixels. Each shift is drawn uniformly from
            ``[-max, +max]``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self, *, max_shift: tuple[int, int], seed: int | None = None) -> None:
        if max_shift[0] < 0 or max_shift[1] < 0:
            raise ValueError("max_shift entries must be non-negative.")
        self.max_shift = max_shift
        self.seed = seed

    def _apply(self, gt: GeoArray, *, seed: int | None = None) -> GeoArray:
        require_geoarray(gt, "RandomShift")
        max_y, max_x = self.max_shift
        rng = _call_rng(self, seed)
        dy = int(rng.integers(-max_y, max_y + 1)) if max_y else 0
        dx = int(rng.integers(-max_x, max_x + 1)) if max_x else 0
        if dx == 0 and dy == 0:
            return gt
        window = PixelWindow(col_off=dx, row_off=dy, width=gt.width, height=gt.height)
        return gt.read_window(window, boundless=True)

    def get_config(self) -> dict[str, Any]:
        return {"max_shift": jsonable(self.max_shift), "seed": self.seed}

Radiometric

geoops.augment._src.operators.BrightnessJitter

Bases: Operator

Scale reflectance values by a sampled scalar or per-band factor.

Pure per-pixel math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind, cast back to the input dtype.

Nodata: fill / non-finite pixels are left untouched and hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
factor Range

(lo, hi) range the multiplicative factor is drawn from. Default (0.9, 1.1).

(0.9, 1.1)
per_band bool

Draw an independent factor per band (the band axis, -3) instead of one shared factor. Default True.

True
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class BrightnessJitter(Operator):
    """Scale reflectance values by a sampled scalar or per-band factor.

    Pure per-pixel math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind, cast back to the
    input dtype.

    Nodata: fill / non-finite pixels are left untouched and hold the
    output's fill value (see the module docstring).

    Args:
        factor: ``(lo, hi)`` range the multiplicative factor is drawn
            from. Default ``(0.9, 1.1)``.
        per_band: Draw an independent factor per band (the band
            axis, ``-3``) instead of one shared factor. Default ``True``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(
        self,
        *,
        factor: Range = (0.9, 1.1),
        per_band: bool = True,
        seed: int | None = None,
    ) -> None:
        factor = as_tuple(factor)
        _validate_range(factor, "factor")
        self.factor = factor
        self.per_band = per_band
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        rng = _call_rng(self, seed)
        arr = np.asarray(gt)
        if self.per_band:
            factors = rng.uniform(self.factor[0], self.factor[1], _band_count(arr))
            factors = factors.reshape(_band_shape(arr))
        else:
            factors = _sample_uniform(rng, self.factor, "factor")
        return _cast_and_wrap(
            gt, arr.astype(np.float64, copy=False) * factors, _valid(arr, gt)
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "factor": jsonable(self.factor),
            "per_band": self.per_band,
            "seed": self.seed,
        }

geoops.augment._src.operators.ContrastJitter

Bases: Operator

Scale deviations from the per-band spatial mean.

Pure per-pixel math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind, cast back to the input dtype.

Nodata: the per-band mean is taken over valid pixels only, and fill / non-finite pixels hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
factor Range

(lo, hi) range the contrast factor is drawn from. Default (0.9, 1.1).

(0.9, 1.1)
per_band bool

Draw an independent factor per band (the band axis, -3) instead of one shared factor. Default True.

True
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class ContrastJitter(Operator):
    """Scale deviations from the per-band spatial mean.

    Pure per-pixel math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind, cast back to the
    input dtype.

    Nodata: the per-band mean is taken over valid pixels only, and fill /
    non-finite pixels hold the output's fill value (see the module
    docstring).

    Args:
        factor: ``(lo, hi)`` range the contrast factor is drawn from.
            Default ``(0.9, 1.1)``.
        per_band: Draw an independent factor per band (the band
            axis, ``-3``) instead of one shared factor. Default ``True``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # deviations from each band's mean over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        factor: Range = (0.9, 1.1),
        per_band: bool = True,
        seed: int | None = None,
    ) -> None:
        factor = as_tuple(factor)
        _validate_range(factor, "factor")
        self.factor = factor
        self.per_band = per_band
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        rng = _call_rng(self, seed)
        arr = np.asarray(gt)
        data = arr.astype(np.float64, copy=False)
        valid = _valid(arr, gt)
        if valid is None:
            mean = np.mean(data, axis=(-2, -1), keepdims=True)
        else:
            masked = np.where(_broadcast_valid(valid, data.shape), data, np.nan)
            with warnings.catch_warnings():
                # An all-nodata band has no mean; its pixels are all refilled.
                warnings.simplefilter("ignore", RuntimeWarning)
                mean = np.nanmean(masked, axis=(-2, -1), keepdims=True)
        if self.per_band:
            factors = rng.uniform(self.factor[0], self.factor[1], _band_count(arr))
            factors = factors.reshape(_band_shape(arr))
        else:
            factors = _sample_uniform(rng, self.factor, "factor")
        return _cast_and_wrap(gt, (data - mean) * factors + mean, valid)

    def get_config(self) -> dict[str, Any]:
        return {
            "factor": jsonable(self.factor),
            "per_band": self.per_band,
            "seed": self.seed,
        }

geoops.augment._src.operators.GaussianNoise

Bases: Operator

Add zero-mean Gaussian sensor noise.

Pure per-pixel math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind, cast back to the input dtype.

Nodata: fill / non-finite pixels are left untouched and hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
sigma ScalarOrRange

Noise standard deviation, either a scalar or a (lo, hi) range to sample from. Default 0.01.

0.01
per_band bool

Draw an independent sigma per band (the band axis, -3) instead of one shared sigma. Default True.

True
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class GaussianNoise(Operator):
    """Add zero-mean Gaussian sensor noise.

    Pure per-pixel math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind, cast back to the
    input dtype.

    Nodata: fill / non-finite pixels are left untouched and hold the
    output's fill value (see the module docstring).

    Args:
        sigma: Noise standard deviation, either a scalar or a
            ``(lo, hi)`` range to sample from. Default ``0.01``.
        per_band: Draw an independent sigma per band (the band
            axis, ``-3``) instead of one shared sigma. Default ``True``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(
        self,
        *,
        sigma: ScalarOrRange = 0.01,
        per_band: bool = True,
        seed: int | None = None,
    ) -> None:
        sigma = as_tuple(sigma)
        _validate_range(sigma, "sigma")
        self.sigma = sigma
        self.per_band = per_band
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        rng = _call_rng(self, seed)
        arr = np.asarray(gt)
        if self.per_band:
            sigmas = np.array(
                [
                    _sample_nonnegative(rng, self.sigma, "sigma")
                    for _ in range(_band_count(arr))
                ]
            ).reshape(_band_shape(arr))
        else:
            sigmas = _sample_nonnegative(rng, self.sigma, "sigma")
        noise = rng.normal(0.0, sigmas, size=arr.shape)
        return _cast_and_wrap(
            gt, arr.astype(np.float64, copy=False) + noise, _valid(arr, gt)
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "sigma": jsonable(self.sigma),
            "per_band": self.per_band,
            "seed": self.seed,
        }

geoops.augment._src.operators.SpeckleNoise

Bases: Operator

Apply multiplicative Gaussian speckle noise, useful for SAR.

Pure per-pixel math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind, cast back to the input dtype.

Nodata: fill / non-finite pixels are left untouched and hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
sigma ScalarOrRange

Speckle standard deviation, either a scalar or a (lo, hi) range to sample from. Default 0.05.

0.05
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class SpeckleNoise(Operator):
    """Apply multiplicative Gaussian speckle noise, useful for SAR.

    Pure per-pixel math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind, cast back to the
    input dtype.

    Nodata: fill / non-finite pixels are left untouched and hold the
    output's fill value (see the module docstring).

    Args:
        sigma: Speckle standard deviation, either a scalar or a
            ``(lo, hi)`` range to sample from. Default ``0.05``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(self, *, sigma: ScalarOrRange = 0.05, seed: int | None = None) -> None:
        sigma = as_tuple(sigma)
        _validate_range(sigma, "sigma")
        self.sigma = sigma
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        rng = _call_rng(self, seed)
        sigma = _sample_nonnegative(rng, self.sigma, "sigma")
        arr = np.asarray(gt)
        noise = rng.normal(0.0, sigma, size=arr.shape)
        return _cast_and_wrap(
            gt, arr.astype(np.float64, copy=False) * (1.0 + noise), _valid(arr, gt)
        )

    def get_config(self) -> dict[str, Any]:
        return {"sigma": jsonable(self.sigma), "seed": self.seed}

Band-level

geoops.augment._src.operators.BandDropout

Bases: Operator

Fill each band independently with probability p.

Pure per-band math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind. A 2-D input is treated as a single band.

Nodata: pixels that were fill / non-finite on input keep the output's fill value rather than fill_value (see the module docstring).

Parameters:

Name Type Description Default
p float

Per-band dropout probability. Default 0.1.

0.1
fill_value float

Value written into dropped bands. Default 0.0.

0.0
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class BandDropout(Operator):
    """Fill each band independently with probability ``p``.

    Pure per-band math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind. A 2-D input is
    treated as a single band.

    Nodata: pixels that were fill / non-finite on input keep the output's
    fill value rather than ``fill_value`` (see the module docstring).

    Args:
        p: Per-band dropout probability. Default ``0.1``.
        fill_value: Value written into dropped bands. Default ``0.0``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(
        self, *, p: float = 0.1, fill_value: float = 0.0, seed: int | None = None
    ) -> None:
        _check_probability(p, "p")
        self.p = p
        self.fill_value = fill_value
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        rng = _call_rng(self, seed)
        arr = np.asarray(gt)
        out = np.array(arr, copy=True)
        if arr.ndim < 3:
            if rng.random() < self.p:
                out[...] = self.fill_value
            return _cast_and_wrap(gt, out, _valid(arr, gt))

        mask = rng.random(arr.shape[BAND_AXIS]) < self.p
        out[..., mask, :, :] = self.fill_value
        return _cast_and_wrap(gt, out, _valid(arr, gt))

geoops.augment._src.operators.BandJitter

Bases: Operator

Permute bands within explicitly configured groups.

Metadata-dependent: band names are resolved through the carrier's attrs by the package-wide resolver (band_names, then descriptions, then bands), so named groups on a plain np.ndarray raise TypeError and on a GeoArray without those names raise ValueError. Integer indices work on any carrier.

Parameters:

Name Type Description Default
groups dict[str, list[str]] | list[list[Any]] | None

Mapping of group label to the band names (or integer indices) permuted within that group, or the equivalent [[label, names], ...] pairs that get_config emits. None or empty disables the op (identity).

None
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class BandJitter(Operator):
    """Permute bands within explicitly configured groups.

    Metadata-dependent: band names are resolved through the carrier's
    ``attrs`` by the package-wide resolver (``band_names``, then
    ``descriptions``, then ``bands``), so named groups on a plain
    ``np.ndarray`` raise ``TypeError`` and on a GeoArray without those
    names raise ``ValueError``. Integer indices work on any carrier.

    Args:
        groups: Mapping of group label to the band names (or integer
            indices) permuted within that group, or the equivalent
            ``[[label, names], ...]`` pairs that ``get_config`` emits.
            ``None`` or empty disables the op (identity).
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # bands permuted within groups: moved, not mixed
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    def __init__(
        self,
        *,
        groups: dict[str, list[str]] | list[list[Any]] | None = None,
        seed: int | None = None,
    ) -> None:
        self.groups = mapping_from_pairs(groups)
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "BandJitter")
        if not self.groups:
            return gt

        arr = np.asarray(gt)
        if arr.ndim < 3:
            return gt

        n_bands = arr.shape[BAND_AXIS]
        groups = [resolve_bands(gt, group) for group in self.groups.values()]
        rng = _call_rng(self, seed)
        out = np.array(arr, copy=True)
        for indices in groups:
            for index in indices:
                if not 0 <= index < n_bands:
                    raise ValueError(f"Band index {index} is outside [0, {n_bands}).")
            if len(indices) > 1:
                out[..., indices, :, :] = arr[..., rng.permutation(indices), :, :]
        return _cast_and_wrap(gt, out)

    def get_config(self) -> dict[str, Any]:
        return {"groups": mapping_to_pairs(self.groups), "seed": self.seed}

RS-specific

geoops.augment._src.operators.SunAngleJitter

Bases: Operator

Rescale TOA reflectance for a simulated solar-zenith change.

Metadata-dependent: the base solar zenith angle is read from the carrier's attrs (solar_zenith_angle or sza_deg), so a plain np.ndarray input (or a GeoArray without those attrs) raises ValueError.

Nodata: fill / non-finite pixels are left untouched and hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
delta_sza_deg ScalarOrRange

Solar-zenith perturbation in degrees, either a scalar or a (lo, hi) range to sample from. Default (-5.0, 5.0).

(-5.0, 5.0)
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class SunAngleJitter(Operator):
    """Rescale TOA reflectance for a simulated solar-zenith change.

    Metadata-dependent: the base solar zenith angle is read from the
    carrier's ``attrs`` (``solar_zenith_angle`` or ``sza_deg``), so a
    plain ``np.ndarray`` input (or a GeoArray without those attrs)
    raises ``ValueError``.

    Nodata: fill / non-finite pixels are left untouched and hold the
    output's fill value (see the module docstring).

    Args:
        delta_sza_deg: Solar-zenith perturbation in degrees, either a
            scalar or a ``(lo, hi)`` range to sample from. Default
            ``(-5.0, 5.0)``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(
        self,
        *,
        delta_sza_deg: ScalarOrRange = (-5.0, 5.0),
        seed: int | None = None,
    ) -> None:
        self.delta_sza_deg = as_tuple(delta_sza_deg)
        self.seed = seed

    def _apply(self, gt: GeoArray, *, seed: int | None = None) -> GeoArray:
        rng = _call_rng(self, seed)
        delta = _sample_uniform(rng, self.delta_sza_deg, "delta_sza_deg")
        attrs = getattr(gt, "attrs", None) or {}
        sza_value = attrs.get("solar_zenith_angle", attrs.get("sza_deg"))
        if sza_value is None:
            raise ValueError(
                "SunAngleJitter requires `solar_zenith_angle` or `sza_deg` in "
                "gt.attrs; got neither."
            )
        scale = sun_angle_scale(float(sza_value), delta)
        arr = np.asarray(gt)
        return _cast_and_wrap(
            gt, arr.astype(np.float64, copy=False) * scale, _valid(arr, gt)
        )

    def get_config(self) -> dict[str, Any]:
        return {"delta_sza_deg": jsonable(self.delta_sza_deg), "seed": self.seed}

geoops.augment._src.operators.AtmosphericHaze

Bases: Operator

Add a sampled haze term following an inverse fourth-power spectrum.

Wavelengths are read from attrs["wavelengths"] (the package-wide key, in nanometers; values below 10 are treated as micrometers and converted to nanometers). Accepts a GeoArray or a plain np.ndarray; when the carrier has no wavelengths attr, a default 450-850 nm linspace is assumed.

Nodata: fill / non-finite pixels are left untouched and hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
intensity ScalarOrRange

Haze amplitude added to the shortest wavelength, either a scalar or a (lo, hi) range to sample from. Default (0.0, 0.05).

(0.0, 0.05)
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class AtmosphericHaze(Operator):
    """Add a sampled haze term following an inverse fourth-power spectrum.

    Wavelengths are read from ``attrs["wavelengths"]`` (the package-wide
    key, in nanometers; values below ``10`` are treated as micrometers and
    converted to nanometers). Accepts a ``GeoArray`` or a plain
    ``np.ndarray``; when the carrier has no ``wavelengths`` attr, a
    default 450-850 nm linspace is assumed.

    Nodata: fill / non-finite pixels are left untouched and hold the
    output's fill value (see the module docstring).

    Args:
        intensity: Haze amplitude added to the shortest wavelength,
            either a scalar or a ``(lo, hi)`` range to sample from.
            Default ``(0.0, 0.05)``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

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

    def __init__(
        self, *, intensity: ScalarOrRange = (0.0, 0.05), seed: int | None = None
    ) -> None:
        self.intensity = as_tuple(intensity)
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "AtmosphericHaze")
        rng = _call_rng(self, seed)
        intensity = _sample_nonnegative(rng, self.intensity, "intensity")
        if intensity == 0.0:
            return gt

        arr = np.asarray(gt)
        attrs = getattr(gt, "attrs", None) or {}
        wavelengths = attrs.get("wavelengths")
        weights = rayleigh_weights(wavelengths, _band_count(arr)).reshape(
            _band_shape(arr)
        )
        return _cast_and_wrap(
            gt,
            arr.astype(np.float64, copy=False) + intensity * weights,
            _valid(arr, gt),
        )

    def get_config(self) -> dict[str, Any]:
        return {"intensity": jsonable(self.intensity), "seed": self.seed}

geoops.augment._src.operators.SimulatedClouds

Bases: Operator

Overlay a smooth synthetic cloud field onto reflectance imagery.

Pure per-pixel math: accepts a GeoArray or a plain np.ndarray and returns the same carrier kind, cast back to the input dtype.

Nodata: the cloud brightness (max / percentile of the scene) is taken over valid pixels only, and fill / non-finite pixels hold the output's fill value (see the module docstring).

Parameters:

Name Type Description Default
coverage ScalarOrRange

Fraction of pixels covered by cloud, either a scalar or a (lo, hi) range in [0, 1]. Default (0.0, 0.3).

(0.0, 0.3)
feather int

Gaussian smoothing sigma (pixels) applied to the random cloud field; 0 disables smoothing. Default 5.

5
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class SimulatedClouds(Operator):
    """Overlay a smooth synthetic cloud field onto reflectance imagery.

    Pure per-pixel math: accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns the same carrier kind, cast back to the
    input dtype.

    Nodata: the cloud brightness (max / percentile of the scene) is taken
    over valid pixels only, and fill / non-finite pixels hold the output's
    fill value (see the module docstring).

    Args:
        coverage: Fraction of pixels covered by cloud, either a scalar
            or a ``(lo, hi)`` range in ``[0, 1]``. Default ``(0.0, 0.3)``.
        feather: Gaussian smoothing sigma (pixels) applied to the random
            cloud field; ``0`` disables smoothing. Default ``5``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # cloud brightness from the scene (pooled over a stack); a smooth cloud field
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(
        self,
        *,
        coverage: ScalarOrRange = (0.0, 0.3),
        feather: int = 5,
        seed: int | None = None,
    ) -> None:
        if feather < 0:
            raise ValueError("feather must be non-negative.")
        coverage = as_tuple(coverage)
        _validate_probability_range(coverage, "coverage")
        self.coverage = coverage
        self.feather = feather
        self.seed = seed

    def _apply(
        self, gt: GeoArray | np.ndarray, *, seed: int | None = None
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "SimulatedClouds")
        rng = _call_rng(self, seed)
        coverage = _sample_uniform(rng, self.coverage, "coverage")
        if coverage == 0.0:
            return gt

        arr = np.asarray(gt)
        alpha = cloud_alpha(
            rng.normal(size=arr.shape[-2:]), coverage, feather=self.feather
        )
        alpha = alpha.reshape((1,) * (arr.ndim - 2) + alpha.shape)
        valid = _valid(arr, gt)
        scene = arr if valid is None else arr[_broadcast_valid(valid, arr.shape)]
        # Assume [0, 1] reflectance if max <= 1; otherwise approximate bright clouds.
        cloud_value = (
            1.0
            if scene.size == 0 or np.nanmax(scene) <= 1.0
            else np.nanpercentile(scene, BRIGHT_CLOUD_PERCENTILE)
        )
        out = arr.astype(np.float64, copy=False) * (1.0 - alpha) + cloud_value * alpha
        return _cast_and_wrap(gt, out, valid)

    def get_config(self) -> dict[str, Any]:
        return {
            "coverage": jsonable(self.coverage),
            "feather": self.feather,
            "seed": self.seed,
        }

geoops.augment._src.operators.CutMix

Bases: Operator

Paste a random rectangle from a pool donor on the input's pixel grid.

Called as op(gt, *pool) -- the donors are positional carriers after the input (or one list of them, op(gt, [d1, d2])), so the operator wires into a pipekit_ops.Graph as CutMix()(Input("x"), Input("d1"), Input("d2")). With no donors the input passes through unchanged.

Every donor must share the input's pixel grid exactly (:func:geoops._src.geo.grid_matches with spatial_only=False: the full shape, and -- when both carry georeferencing -- the CRS and every transform coefficient, origin included). The paste is pixel-space math: pixel (i, j) of the donor lands on pixel (i, j) of the input, so requiring the same grid keeps the result geographically coherent (e.g. a donor from another acquisition date or sensor over the same tile). A donor at a different origin, scale or CRS is rejected rather than pasted at the wrong location.

Plain np.ndarray carriers (input and/or donors) are accepted: the georeferencing check applies only when both the input and the drawn donor carry a transform; plain arrays are compared by shape.

Sampling: with probability p one donor is drawn uniformly from the pool; the rectangle's height and width are drawn independently and uniformly from [1, H] and [1, W], and its top-left corner uniformly among the positions that keep it inside the raster. This is not the Beta(alpha, alpha) area-ratio convention of Yun et al. (2019) and no label-mixing ratio is returned (see #141).

Nodata: donor pixels that are fill / non-finite under the donor's fill value are written as the input's fill value, so a pasted hole stays a hole for the output carrier.

Parameters:

Name Type Description Default
p float

Probability of applying the paste. Default 0.5.

0.5
seed int | None

Seed of the operator's own draw stream, which advances on every call; a per-call seed makes a one-off draw instead.

None

Raises:

Type Description
ValueError

At apply time, if any donor is not on the input's pixel grid.

Examples:

>>> import geoops as gz
>>> op = gz.augment.CutMix(p=1.0, seed=0)
>>> out = op(patch, donor)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/operators.py
class CutMix(Operator):
    """Paste a random rectangle from a pool donor on the input's pixel grid.

    Called as ``op(gt, *pool)`` -- the donors are positional carriers after
    the input (or one list of them, ``op(gt, [d1, d2])``), so the operator
    wires into a ``pipekit_ops.Graph`` as ``CutMix()(Input("x"), Input("d1"),
    Input("d2"))``. With no donors the input passes through unchanged.

    Every donor must share the input's pixel grid exactly
    (:func:`geoops._src.geo.grid_matches` with ``spatial_only=False``:
    the full shape, and -- when both carry georeferencing -- the CRS and
    every ``transform`` coefficient, origin included). The paste is
    pixel-space math: pixel ``(i, j)`` of the donor lands on pixel
    ``(i, j)`` of the input, so requiring the same grid keeps the result
    geographically coherent (e.g. a donor from another acquisition date
    or sensor over the same tile). A donor at a different origin, scale
    or CRS is rejected rather than pasted at the wrong location.

    Plain ``np.ndarray`` carriers (input and/or donors) are accepted:
    the georeferencing check applies only when both the input and the
    drawn donor carry a ``transform``; plain arrays are compared by shape.

    Sampling: with probability ``p`` one donor is drawn uniformly from
    the pool; the rectangle's height and width are drawn independently
    and uniformly from ``[1, H]`` and ``[1, W]``, and its top-left corner
    uniformly among the positions that keep it inside the raster. This
    is *not* the Beta(alpha, alpha) area-ratio convention of Yun et al.
    (2019) and no label-mixing ratio is returned (see #141).

    Nodata: donor pixels that are fill / non-finite under the *donor's*
    fill value are written as the input's fill value, so a pasted hole
    stays a hole for the output carrier.

    Args:
        p: Probability of applying the paste. Default ``0.5``.
        seed: Seed of the operator's own draw stream, which advances on
            every call; a per-call ``seed`` makes a one-off draw instead.

    Raises:
        ValueError: At apply time, if any donor is not on the input's
            pixel grid.

    Examples:
        >>> import geoops as gz
        >>> op = gz.augment.CutMix(p=1.0, seed=0)
        >>> out = op(patch, donor)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each pixel from the input or the donor
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(
        self,
        *,
        p: float = 0.5,
        seed: int | None = None,
    ) -> None:
        _check_probability(p, "p")
        self.p = p
        self.seed = seed

    def _apply(
        self,
        gt: GeoArray | np.ndarray,
        *pool: GeoArray | np.ndarray,
        seed: int | None = None,
    ) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "CutMix")
        donors = gather_inputs(pool, "CutMix") if pool else []
        for idx, candidate in enumerate(donors):
            require_grid_match(
                gt,
                candidate,
                "CutMix",
                names=("input", f"donor {idx}"),
                spatial_only=False,
            )
        rng = _call_rng(self, seed)
        if not donors or rng.random() >= self.p:
            return gt

        donor = donors[int(rng.integers(0, len(donors)))]
        arr = np.asarray(gt)
        donor_arr = np.asarray(donor)

        height, width = arr.shape[-2], arr.shape[-1]
        cut_h = int(rng.integers(1, height + 1))
        cut_w = int(rng.integers(1, width + 1))
        top = int(rng.integers(0, height - cut_h + 1))
        left = int(rng.integers(0, width - cut_w + 1))

        out = np.array(arr, copy=True)
        region = (slice(top, top + cut_h), slice(left, left + cut_w))
        out[..., region[0], region[1]] = donor_arr[..., region[0], region[1]]
        donor_valid = _valid(donor_arr, donor)
        valid = None
        if donor_valid is not None:
            # Input pixels outside the rectangle keep their own values
            # (fills included); only donor holes need the input's fill.
            valid = np.ones(donor_valid.shape, dtype=bool)
            valid[..., region[0], region[1]] = donor_valid[..., region[0], region[1]]
        return _cast_and_wrap(gt, out, valid)

Tier-A primitives

geoops.augment._src.array.rot90_transform(transform: Affine, height: int, width: int, k: int) -> Affine

Compose transform with the pixel map of np.rot90(..., k).

The affine maps pixel corners, so the mirrored axes are anchored at the far edge (width / height), not the last pixel index; the rotated grid then covers exactly the input footprint.

Parameters:

Name Type Description Default
transform Affine

Affine of the input grid.

required
height int

Input height in pixels.

required
width int

Input width in pixels.

required
k int

Number of counter-clockwise quarter turns (any integer).

required

Returns:

Type Description
Affine

The affine of np.rot90(arr, k, axes=(-2, -1)).

Examples:

>>> rot90_transform(Affine.identity(), 4, 6, 2)
Affine(-1.0, 0.0, 6.0,
       0.0, -1.0, 4.0)
Source code in packages/geotoolz-ops/src/geoops/augment/_src/array.py
def rot90_transform(transform: Affine, height: int, width: int, k: int) -> Affine:
    """Compose ``transform`` with the pixel map of ``np.rot90(..., k)``.

    The affine maps pixel *corners*, so the mirrored axes are anchored at
    the far edge (``width`` / ``height``), not the last pixel index; the
    rotated grid then covers exactly the input footprint.

    Args:
        transform: Affine of the input grid.
        height: Input height in pixels.
        width: Input width in pixels.
        k: Number of counter-clockwise quarter turns (any integer).

    Returns:
        The affine of ``np.rot90(arr, k, axes=(-2, -1))``.

    Examples:
        >>> rot90_transform(Affine.identity(), 4, 6, 2)
        Affine(-1.0, 0.0, 6.0,
               0.0, -1.0, 4.0)
    """
    k %= 4
    if k == 1:
        return transform * Affine(0, -1, width, 1, 0, 0)
    if k == 2:
        return transform * Affine.translation(width, height) * Affine.scale(-1, -1)
    if k == 3:
        return transform * Affine(0, 1, 0, -1, 0, height)
    return transform

geoops.augment._src.array.sun_angle_scale(base_sza_deg: float, delta_deg: float) -> float

TOA-reflectance factor for a solar-zenith change.

s = cos(θ + Δθ) / cos(θ)

Parameters:

Name Type Description Default
base_sza_deg float

Solar zenith angle θ of the scene, degrees.

required
delta_deg float

Perturbation Δθ, degrees.

required

Returns:

Type Description
float

The multiplicative factor s.

Raises:

Type Description
ValueError

If θ is within floating-point tolerance of 90°.

Examples:

>>> round(sun_angle_scale(60.0, -60.0), 6)
2.0
Source code in packages/geotoolz-ops/src/geoops/augment/_src/array.py
def sun_angle_scale(base_sza_deg: float, delta_deg: float) -> float:
    """TOA-reflectance factor for a solar-zenith change.

        s = cos(θ + Δθ) / cos(θ)

    Args:
        base_sza_deg: Solar zenith angle ``θ`` of the scene, degrees.
        delta_deg: Perturbation ``Δθ``, degrees.

    Returns:
        The multiplicative factor ``s``.

    Raises:
        ValueError: If ``θ`` is within floating-point tolerance of 90°.

    Examples:
        >>> round(sun_angle_scale(60.0, -60.0), 6)
        2.0
    """
    denom = np.cos(np.deg2rad(base_sza_deg))
    if np.isclose(denom, 0.0):
        raise ValueError(
            f"solar zenith angle ({base_sza_deg:.2f} deg) is too close to 90 degrees."
        )
    return float(np.cos(np.deg2rad(base_sza_deg + delta_deg)) / denom)

geoops.augment._src.array.rayleigh_weights(wavelengths: Float[np.ndarray, ' c'] | None, n_bands: int) -> Float[np.ndarray, ' c']

Per-band inverse-fourth-power haze weights, peak-normalised.

w_c = λ_c⁻⁴ / max_c λ_c⁻⁴

Wavelengths are nanometres; values below 10 are taken as micrometres and converted. None assumes a 450-850 nm linspace.

Parameters:

Name Type Description Default
wavelengths Float[ndarray, ' c'] | None

Band-centre wavelengths, or None.

required
n_bands int

Number of bands.

required

Returns:

Type Description
Float[ndarray, ' c']

(n_bands,) weights in (0, 1]; the shortest band is 1.

Raises:

Type Description
ValueError

If wavelengths does not have n_bands values.

Examples:

>>> rayleigh_weights(np.array([0.5, 1.0]), 2)
array([1.    , 0.0625])
Source code in packages/geotoolz-ops/src/geoops/augment/_src/array.py
def rayleigh_weights(
    wavelengths: Float[np.ndarray, " c"] | None, n_bands: int
) -> Float[np.ndarray, " c"]:
    """Per-band inverse-fourth-power haze weights, peak-normalised.

        w_c = λ_c⁻⁴ / max_c λ_c⁻⁴

    Wavelengths are nanometres; values below ``10`` are taken as
    micrometres and converted. ``None`` assumes a 450-850 nm linspace.

    Args:
        wavelengths: Band-centre wavelengths, or ``None``.
        n_bands: Number of bands.

    Returns:
        ``(n_bands,)`` weights in ``(0, 1]``; the shortest band is ``1``.

    Raises:
        ValueError: If ``wavelengths`` does not have ``n_bands`` values.

    Examples:
        >>> rayleigh_weights(np.array([0.5, 1.0]), 2)
        array([1.    , 0.0625])
    """
    if wavelengths is None:
        wavelengths = np.linspace(
            DEFAULT_MIN_WAVELENGTH_NM, DEFAULT_MAX_WAVELENGTH_NM, n_bands
        )
    wavelengths = np.asarray(wavelengths, dtype=np.float64)
    if wavelengths.size != n_bands:
        raise ValueError("wavelength metadata must have one value per band.")
    if np.nanmax(wavelengths) < 10.0:
        # Convert micrometers to nanometers; RS visible/NIR values are never <10 nm.
        wavelengths = wavelengths * 1000.0
    weights = 1.0 / np.power(wavelengths, 4)
    return weights / np.nanmax(weights)

geoops.augment._src.array.cloud_alpha(field: Float[np.ndarray, 'h w'], coverage: float, *, feather: float = 0.0) -> Float[np.ndarray, 'h w']

Cloud opacity map covering coverage of the pixels.

The (random) field is Gaussian-smoothed with feather, min-max normalised to f ∈ [0, 1] and thresholded at its 1 − coverage quantile q; opacity ramps linearly above it:

α = clip((f − q) / (max f − q), 0, 1)

Parameters:

Name Type Description Default
field Float[ndarray, 'h w']

(H, W) noise field, e.g. rng.normal(size=(H, W)).

required
coverage float

Fraction of pixels with α > 0, in [0, 1].

required
feather float

Gaussian smoothing sigma in pixels; 0 disables it.

0.0

Returns:

Type Description
Float[ndarray, 'h w']

(H, W) opacity in [0, 1].

Examples:

>>> alpha = cloud_alpha(np.random.default_rng(0).normal(size=(64, 64)), 0.25)
>>> 0.2 < float((alpha > 0).mean()) < 0.3
True
Source code in packages/geotoolz-ops/src/geoops/augment/_src/array.py
def cloud_alpha(
    field: Float[np.ndarray, "h w"], coverage: float, *, feather: float = 0.0
) -> Float[np.ndarray, "h w"]:
    """Cloud opacity map covering ``coverage`` of the pixels.

    The (random) ``field`` is Gaussian-smoothed with ``feather``,
    min-max normalised to ``f ∈ [0, 1]`` and thresholded at its
    ``1 − coverage`` quantile ``q``; opacity ramps linearly above it:

        α = clip((f − q) / (max f − q), 0, 1)

    Args:
        field: ``(H, W)`` noise field, e.g. ``rng.normal(size=(H, W))``.
        coverage: Fraction of pixels with ``α > 0``, in ``[0, 1]``.
        feather: Gaussian smoothing sigma in pixels; ``0`` disables it.

    Returns:
        ``(H, W)`` opacity in ``[0, 1]``.

    Examples:
        >>> alpha = cloud_alpha(np.random.default_rng(0).normal(size=(64, 64)), 0.25)
        >>> 0.2 < float((alpha > 0).mean()) < 0.3
        True
    """
    if feather:
        field = gaussian_filter(field, sigma=feather, mode="reflect")
    field = (field - field.min()) / (np.ptp(field) + np.finfo(np.float64).eps)
    threshold = np.quantile(field, 1.0 - coverage)
    return np.clip(
        (field - threshold) / (field.max() - threshold + CLOUD_ALPHA_EPSILON),
        0,
        1,
    )