Skip to content

Restore

Denoising, despeckling, destriping, gap-fill, and inpainting operators.

  • Denoising: BilateralDenoise, GaussianDenoise, MedianDenoise, NLMeans, DenoisePCA, MNF (minimum noise fraction, Green et al. 1988; fit / transform / inverse)
  • SAR despeckle: DespeckleLee (Lee 1980), DespeckleRefinedLee, DespeckleFrost (Frost 1982)
  • Destripe: DestripeColumn, MomentMatching (per-column gain + offset, Gadallah et al. 2000)
  • Gap fill: GapFillNearest, GapFillIDW, GapFillInpaintBiharmonic, GapFillLaplacian
  • Outlier handling: OutlierMask, ReplaceOutliers (saturation flags: geoops.qa.MaskSaturated)
  • Tier-A primitives: bilateral_denoise, gaussian_denoise, median_denoise, nl_means, pca_denoise, despeckle_lee, despeckle_refined_lee, despeckle_frost, destripe_column, gap_fill_nearest, gap_fill_idw, gap_fill_biharmonic, gap_fill_laplacian, outlier_mask, replace_outliers

geoops.restore

Restoration primitives and Operators for imperfect remote-sensing data.

BilateralDenoise

Bases: Operator

Edge-aware denoise using a range-weighted Gaussian.

Wraps :func:~geoops.restore._src.array.bilateral_denoise. Use sigma_color to control how aggressively edges are preserved (smaller = stronger preservation) and sigma_space for the spatial smoothing scale.

Caveat: this is a single-pass approximation of a full bilateral filter, not the canonical per-pixel-neighbourhood form. Nodata (fill / non-finite) pixels are excluded from the smoothing and hold the output fill.

Examples:

>>> gz.restore.BilateralDenoise(sigma_color=0.1, sigma_space=5.0)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class BilateralDenoise(Operator):
    """Edge-aware denoise using a range-weighted Gaussian.

    Wraps :func:`~geoops.restore._src.array.bilateral_denoise`. Use
    ``sigma_color`` to control how aggressively edges are preserved
    (smaller = stronger preservation) and ``sigma_space`` for the
    spatial smoothing scale.

    Caveat: this is a single-pass approximation of a full bilateral
    filter, not the canonical per-pixel-neighbourhood form. Nodata (fill
    / non-finite) pixels are excluded from the smoothing and hold the
    output fill.

    Examples:
        >>> gz.restore.BilateralDenoise(sigma_color=0.1, sigma_space=5.0)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # range weights scaled by the scene's value range
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(self, *, sigma_color: float = 0.1, sigma_space: float = 5.0) -> None:
        self.sigma_color = sigma_color
        self.sigma_space = sigma_space

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(
            gt,
            lambda a: bilateral_denoise(
                a, sigma_color=self.sigma_color, sigma_space=self.sigma_space
            ),
        )

DenoisePCA

Bases: Operator

Reconstruct a multi-band raster from its top PCA components.

Projects the carrier onto its leading n_components principal directions and reconstructs in the original space. Effective at suppressing band-uncorrelated noise; can soften sharp band-localised features. The components are fitted on valid pixels only (a pixel invalid in any band is excluded); invalid pixels hold the output fill.

Parameters:

Name Type Description Default
n_components int

Number of principal components to keep. n_components < bands performs noise reduction.

required
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

Inputs are (C, H, W) cubes or (T, C, H, W) stacks; a stack is fitted once over the pixels of every frame (one PCA basis for the time series). A 2-D (H, W) map has no band axis and raises ValueError -- its rows are never treated as bands.

Examples:

>>> gz.restore.DenoisePCA(n_components=10)(hyperspectral_scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class DenoisePCA(Operator):
    """Reconstruct a multi-band raster from its top PCA components.

    Projects the carrier onto its leading ``n_components`` principal
    directions and reconstructs in the original space. Effective at
    suppressing band-uncorrelated noise; can soften sharp
    band-localised features. The components are fitted on valid pixels
    only (a pixel invalid in any band is excluded); invalid pixels hold
    the output fill.

    Args:
        n_components: Number of principal components to keep.
            ``n_components < bands`` performs noise reduction.
        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.

    Inputs are ``(C, H, W)`` cubes or ``(T, C, H, W)`` stacks; a stack is
    fitted once over the pixels of every frame (one PCA basis for the
    time series). A 2-D ``(H, W)`` map has no band axis and raises
    ``ValueError`` -- its rows are never treated as bands.

    Examples:
        >>> gz.restore.DenoisePCA(n_components=10)(hyperspectral_scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # principal components fitted on every call
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"}, effects={"band": "mix"}, reach=None
    )

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

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="DenoisePCA")
        require_ndim(gt, (3, 4), type(self).__name__)
        out = pca_denoise(
            _band_masked(gt, axis), n_components=self.n_components, axis=axis
        )
        return _rewrap_finite(gt, out)

DespeckleFrost

Bases: Operator

Frost (1982) adaptive exponential-kernel speckle filter.

Wraps :func:~geoops.restore._src.array.despeckle_frost: a normalised weighted window mean with kernel m(t) = exp(−K·Cᵥ²·|t|), where Cᵥ² = σ_z²/z̄² is the local squared coefficient of variation and |t| the distance from the centre pixel. The kernel is wide on homogeneous speckle and narrows onto the centre pixel at edges. Nodata (fill / non-finite) pixels get zero weight and hold the output fill.

Parameters:

Name Type Description Default
window int

Side length of the kernel window in pixels.

7
damping float

Damping factor K; larger values keep more edge contrast, 0 is the box mean.

2.0

Examples:

>>> gz.restore.DespeckleFrost(window=7, damping=2.0)(sar_geoarray)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class DespeckleFrost(Operator):
    """Frost (1982) adaptive exponential-kernel speckle filter.

    Wraps :func:`~geoops.restore._src.array.despeckle_frost`: a
    normalised weighted window mean with kernel
    ``m(t) = exp(−K·Cᵥ²·|t|)``, where ``Cᵥ² = σ_z²/z̄²`` is the local
    squared coefficient of variation and ``|t|`` the distance from the
    centre pixel. The kernel is wide on homogeneous speckle and narrows
    onto the centre pixel at edges. Nodata (fill / non-finite) pixels
    get zero weight and hold the output fill.

    Args:
        window: Side length of the kernel window in pixels.
        damping: Damping factor ``K``; larger values keep more edge
            contrast, ``0`` is the box mean.

    Examples:
        >>> gz.restore.DespeckleFrost(window=7, damping=2.0)(sar_geoarray)
    """

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

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: half the window."""
        return self.window // 2

    def __init__(self, *, window: int = 7, damping: float = 2.0) -> None:
        self.window = window
        self.damping = damping

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(
            gt, lambda a: despeckle_frost(a, window=self.window, damping=self.damping)
        )

spatial_reach()

The spatial reach in pixels: half the window.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: half the window."""
    return self.window // 2

DespeckleLee

Bases: Operator

Lee (1980) local-statistics speckle filter.

Carrier-aware wrapper around :func:~geoops.restore._src.array.despeckle_lee: x̂ = z̄ + k·(z − z̄) with the MMSE gain k = σ_x² / (σ_x² + Cᵤ²·z̄²), σ_x² = (σ_z² − Cᵤ²·z̄²) / (1 + Cᵤ²) clipped at 0 -- the local mean on homogeneous speckle, k → 1 (pass-through) at edges. Best suited to multiplicative speckle in SAR imagery. Nodata (fill / non-finite) pixels are excluded from the window statistics and hold the output fill.

Parameters:

Name Type Description Default
window int

Side length of the local window in pixels.

7
cu float

Noise coefficient of variation Cᵤ. 0.523 is the single-look amplitude value; use 1/√L for L-look intensity.

0.523

Examples:

>>> import geoops as gz
>>> pipe = gz.restore.DespeckleLee(window=7) | gz.restore.MedianDenoise(window=3)
>>> clean = pipe(sar_geoarray)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class DespeckleLee(Operator):
    """Lee (1980) local-statistics speckle filter.

    Carrier-aware wrapper around
    :func:`~geoops.restore._src.array.despeckle_lee`:
    ``x̂ = z̄ + k·(z − z̄)`` with the MMSE gain
    ``k = σ_x² / (σ_x² + Cᵤ²·z̄²)``, ``σ_x² = (σ_z² − Cᵤ²·z̄²) / (1 + Cᵤ²)``
    clipped at ``0`` -- the local mean on homogeneous speckle, ``k → 1``
    (pass-through) at edges. Best suited to multiplicative speckle in SAR
    imagery. Nodata (fill / non-finite) pixels are excluded from the
    window statistics and hold the output fill.

    Args:
        window: Side length of the local window in pixels.
        cu: Noise coefficient of variation ``Cᵤ``. ``0.523`` is the
            single-look amplitude value; use ``1/√L`` for ``L``-look
            intensity.

    Examples:
        >>> import geoops as gz
        >>> pipe = gz.restore.DespeckleLee(window=7) | gz.restore.MedianDenoise(window=3)
        >>> clean = pipe(sar_geoarray)
    """

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

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: half the window."""
        return self.window // 2

    def __init__(self, *, window: int = 7, cu: float = 0.523) -> None:
        self.window = window
        self.cu = cu

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(gt, lambda a: despeckle_lee(a, window=self.window, cu=self.cu))

spatial_reach()

The spatial reach in pixels: half the window.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: half the window."""
    return self.window // 2

DespeckleRefinedLee

Bases: Operator

Refined-Lee speckle filter approximation.

Wraps :func:~geoops.restore._src.array.despeckle_refined_lee. This is currently a dependency-light alias for :class:DespeckleLee (Lee 1980 gain) with default cu; the eight-direction sub-window selection of the canonical Refined-Lee is not yet implemented. Nodata pixels are handled as in :class:DespeckleLee.

Parameters:

Name Type Description Default
window int

Side length of the local window in pixels.

7

Examples:

>>> gz.restore.DespeckleRefinedLee(window=7)(sar_geoarray)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class DespeckleRefinedLee(Operator):
    """Refined-Lee speckle filter approximation.

    Wraps :func:`~geoops.restore._src.array.despeckle_refined_lee`.
    This is currently a dependency-light alias for :class:`DespeckleLee`
    (Lee 1980 gain) with default ``cu``; the eight-direction sub-window selection of the
    canonical Refined-Lee is not yet implemented. Nodata pixels are
    handled as in :class:`DespeckleLee`.

    Args:
        window: Side length of the local window in pixels.

    Examples:
        >>> gz.restore.DespeckleRefinedLee(window=7)(sar_geoarray)
    """

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

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: half the window."""
        return self.window // 2

    def __init__(self, *, window: int = 7) -> None:
        self.window = window

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(gt, lambda a: despeckle_refined_lee(a, window=self.window))

spatial_reach()

The spatial reach in pixels: half the window.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: half the window."""
    return self.window // 2

DestripeColumn

Bases: Operator

Subtract per-column (or per-row) offsets from striped imagery.

Wraps :func:~geoops.restore._src.array.destripe_column. Use method="mean" for additive stripes, "median" for stripes with outlier contamination, and "moment_matching" for stripes with a per-detector gain and offset: every column is linearly rescaled so its mean and standard deviation match a reference ((z − μ_j)·σᵣ/σ_j + μᵣ; the moving average of the column moments over window columns, or global with window=None). Nodata (fill / non-finite) pixels are excluded from the column / row statistics and hold the output fill.

Parameters:

Name Type Description Default
method Literal['mean', 'median', 'moment_matching']

"mean", "median" (offset only) or "moment_matching" (gain and offset).

'mean'
direction Literal['column', 'row']

Striping direction. "column" removes vertical stripes, "row" removes horizontal stripes.

'column'
window int | None

Reference window (in columns / rows) for method="moment_matching"; None uses a global reference. Ignored for the other methods but accepted for hydra-zen round-trip uniformity.

21

Examples:

>>> gz.restore.DestripeColumn(method="median", direction="column")(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class DestripeColumn(Operator):
    """Subtract per-column (or per-row) offsets from striped imagery.

    Wraps :func:`~geoops.restore._src.array.destripe_column`. Use
    ``method="mean"`` for additive stripes, ``"median"`` for stripes
    with outlier contamination, and ``"moment_matching"`` for stripes
    with a per-detector gain *and* offset: every column is linearly
    rescaled so its mean and standard deviation match a reference
    (``(z − μ_j)·σᵣ/σ_j + μᵣ``; the moving average of the column moments
    over ``window`` columns, or global with ``window=None``). Nodata
    (fill / non-finite) pixels are excluded from the column / row
    statistics and hold the output fill.

    Args:
        method: ``"mean"``, ``"median"`` (offset only) or
            ``"moment_matching"`` (gain and offset).
        direction: Striping direction. ``"column"`` removes vertical
            stripes, ``"row"`` removes horizontal stripes.
        window: Reference window (in columns / rows) for
            ``method="moment_matching"``; ``None`` uses a global
            reference. Ignored for the other methods but accepted for
            hydra-zen round-trip uniformity.

    Examples:
        >>> gz.restore.DestripeColumn(method="median", direction="column")(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # statistics of whole columns (or rows)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        method: Literal["mean", "median", "moment_matching"] = "mean",
        direction: Literal["column", "row"] = "column",
        window: int | None = 21,
    ) -> None:
        self.method = method
        self.direction = direction
        self.window = window

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(
            gt,
            lambda a: destripe_column(
                a, method=self.method, direction=self.direction, window=self.window
            ),
        )

GapFillIDW

Bases: Operator

Fill NaNs with inverse-distance weighted finite neighbours.

Wraps :func:~geoops.restore._src.array.gap_fill_idw (functax plans, the [interp] extra). NaNs whose neighbourhood within radius contains no finite pixels are left unfilled — chain with :class:GapFillNearest for unconditional fill. Nodata elements (fill value or non-finite) are the gaps: the output there is the filled value, not the fill value; only gaps left unfilled hold the output fill.

Parameters:

Name Type Description Default
power float

IDW exponent. 2.0 is the standard choice.

2.0
radius int

Search radius in pixels.

5

Examples:

>>> gz.restore.GapFillIDW(power=2.0, radius=5)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class GapFillIDW(Operator):
    """Fill NaNs with inverse-distance weighted finite neighbours.

    Wraps :func:`~geoops.restore._src.array.gap_fill_idw` (functax plans,
    the ``[interp]`` extra). NaNs whose
    neighbourhood within ``radius`` contains no finite pixels are left
    unfilled — chain with :class:`GapFillNearest` for unconditional fill.
    Nodata elements (fill value or non-finite) are the gaps: the output
    there is the filled value, *not* the fill value; only gaps left
    unfilled hold the output fill.

    Args:
        power: IDW exponent. ``2.0`` is the standard choice.
        radius: Search radius in pixels.

    Examples:
        >>> gz.restore.GapFillIDW(power=2.0, radius=5)(scene)
    """

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

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: the search radius."""
        return int(np.ceil(self.radius))

    def __init__(self, *, power: float = 2.0, radius: int = 5) -> None:
        self.power = power
        self.radius = radius

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _gap_fill(
            gt, lambda a: gap_fill_idw(a, power=self.power, radius=self.radius)
        )

spatial_reach()

The spatial reach in pixels: the search radius.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: the search radius."""
    return int(np.ceil(self.radius))

GapFillInpaintBiharmonic

Bases: Operator

Smoothly inpaint NaN gaps with a biharmonic fill (Δ²u = 0).

Wraps :func:~geoops.restore._src.array.gap_fill_biharmonic (functax.project.fill_gaps, the [interp] extra), which solves Δ²u = 0 in the holes and preserves the original finite pixels — the operator just round-trips carrier metadata. Nodata elements (fill value or non-finite) are the gaps: the output there is the filled value, not the fill value; only gaps left unfilled hold the output fill.

Examples:

>>> gz.restore.GapFillInpaintBiharmonic()(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class GapFillInpaintBiharmonic(Operator):
    """Smoothly inpaint NaN gaps with a biharmonic fill (Δ²u = 0).

    Wraps :func:`~geoops.restore._src.array.gap_fill_biharmonic`
    (``functax.project.fill_gaps``, the ``[interp]`` extra), which solves
    Δ²u = 0 in the holes and preserves the original finite pixels — the
    operator just round-trips carrier metadata.
    Nodata elements (fill value or non-finite) are the gaps: the output
    there is the filled value, *not* the fill value; only gaps left
    unfilled hold the output fill.

    Examples:
        >>> gz.restore.GapFillInpaintBiharmonic()(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a smooth fill across each hole
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _gap_fill(gt, gap_fill_biharmonic)

GapFillLaplacian

Bases: Operator

Fill NaNs by solving a discrete Laplace equation.

Wraps :func:~geoops.restore._src.array.gap_fill_laplacian (functax.project.fill_gaps, the [interp] extra). The harmonic interpolant, solved exactly — smooth, but linearly biased toward the mean of the boundary. Pair with :class:GaussianDenoise for a smoother transition near the mask edge. Nodata elements (fill value or non-finite) are the gaps: the output there is the filled value, not the fill value; only gaps left unfilled hold the output fill.

Parameters:

Name Type Description Default
iterations int | None

Deprecated and ignored: the fill is an exact solve, not a fixed number of Jacobi sweeps. Passing it warns.

None

Examples:

>>> gz.restore.GapFillLaplacian()(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class GapFillLaplacian(Operator):
    """Fill NaNs by solving a discrete Laplace equation.

    Wraps :func:`~geoops.restore._src.array.gap_fill_laplacian`
    (``functax.project.fill_gaps``, the ``[interp]`` extra). The
    harmonic interpolant, solved exactly — smooth, but linearly biased
    toward the mean of the boundary. Pair with :class:`GaussianDenoise`
    for a smoother transition near the mask edge.
    Nodata elements (fill value or non-finite) are the gaps: the output
    there is the filled value, *not* the fill value; only gaps left
    unfilled hold the output fill.

    Args:
        iterations: Deprecated and ignored: the fill is an exact solve,
            not a fixed number of Jacobi sweeps. Passing it warns.

    Examples:
        >>> gz.restore.GapFillLaplacian()(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a diffusion across each hole
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(self, *, iterations: int | None = None) -> None:
        if iterations is not None:
            warnings.warn(
                "GapFillLaplacian(iterations=...) is deprecated and has no "
                "effect: the Laplace fill is now solved exactly by "
                "functax.project.fill_gaps. Drop the argument.",
                DeprecationWarning,
                stacklevel=2,
            )
        self.iterations = iterations

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _gap_fill(gt, gap_fill_laplacian)

GapFillNearest

Bases: Operator

Fill NaNs from the nearest finite neighbour.

Wraps :func:~geoops.restore._src.array.gap_fill_nearest (functax plans, the [interp] extra). Unconditional unless max_distance is set. Nodata elements (fill value or non-finite) are the gaps: the output there is the filled value, not the fill value; only gaps left unfilled hold the output fill.

Parameters:

Name Type Description Default
max_distance int | None

Maximum Euclidean fill radius in pixels. None (default) fills every NaN with a finite neighbour anywhere in its 2-D plane.

None

Examples:

>>> gz.restore.GapFillNearest(max_distance=3)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class GapFillNearest(Operator):
    """Fill NaNs from the nearest finite neighbour.

    Wraps :func:`~geoops.restore._src.array.gap_fill_nearest` (functax
    plans, the ``[interp]`` extra). Unconditional unless ``max_distance``
    is set.
    Nodata elements (fill value or non-finite) are the gaps: the output
    there is the filled value, *not* the fill value; only gaps left
    unfilled hold the output fill.

    Args:
        max_distance: Maximum Euclidean fill radius in pixels. ``None``
            (default) fills every NaN with a finite neighbour anywhere
            in its 2-D plane.

    Examples:
        >>> gz.restore.GapFillNearest(max_distance=3)(scene)
    """

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

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: unbounded unless a maximum distance is set."""
        return None if self.max_distance is None else int(np.ceil(self.max_distance))

    def __init__(self, *, max_distance: int | None = None) -> None:
        self.max_distance = max_distance

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _gap_fill(
            gt, lambda a: gap_fill_nearest(a, max_distance=self.max_distance)
        )

spatial_reach()

The spatial reach in pixels: unbounded unless a maximum distance is set.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: unbounded unless a maximum distance is set."""
    return None if self.max_distance is None else int(np.ceil(self.max_distance))

GaussianDenoise

Bases: Operator

Gaussian smoother over the trailing two spatial axes.

Normalized convolution: nodata (fill / non-finite) pixels are excluded from both the numerator and the normalising weight, so they never smear into their neighbours, and hold the output fill. Non-spatial axes (e.g. bands) are not filtered.

Parameters:

Name Type Description Default
sigma float

Gaussian standard deviation in pixels.

1.0

Examples:

>>> gz.restore.GaussianDenoise(sigma=1.0)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class GaussianDenoise(Operator):
    """Gaussian smoother over the trailing two spatial axes.

    Normalized convolution: nodata (fill / non-finite) pixels are
    excluded from both the numerator and the normalising weight, so
    they never smear into their neighbours, and hold the output fill.
    Non-spatial axes (e.g. bands) are not filtered.

    Args:
        sigma: Gaussian standard deviation in pixels.

    Examples:
        >>> gz.restore.GaussianDenoise(sigma=1.0)(scene)
    """

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

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: ⌈4σ⌉, scipy's default truncation."""
        return int(np.ceil(4 * self.sigma))

    def __init__(self, *, sigma: float = 1.0) -> None:
        self.sigma = sigma

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(gt, lambda a: gaussian_denoise(a, sigma=self.sigma))

spatial_reach()

The spatial reach in pixels: ⌈4σ⌉, scipy's default truncation.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: ⌈4σ⌉, scipy's default truncation."""
    return int(np.ceil(4 * self.sigma))

MNF

Bases: Operator

Minimum Noise Fraction transform (Green et al. 1988), with its inverse.

Wraps :func:~geoops.restore._src.array.fit_mnf. The noise covariance Σ_N is estimated from horizontal shift differences (Σ_N = Cov(z(i, j) − z(i, j + 1)) / 2, see :func:~geoops.restore._src.array.shift_difference_noise_covariance); the data are noise-whitened with Σ_N^(−1/2) (Cholesky) and the whitened data are rotated onto their principal components. The output carrier holds the scores, ordered by decreasing SNR, and :meth:inverse maps scores back to band space with x̂ = Σ_N·A_k·y + x̄ -- keeping the first n_components and inverting is the classical MNF noise filter.

Fitted operator (see Fitted operators in the concepts guide): :meth:fit learns the basis, :meth:transform projects any cube with the same bands onto it and :meth:inverse reconstructs, neither mutating the operator. Calling an unfitted operator fits the basis on that first call (once, even under concurrent calls) and every later call reuses it; call :meth:fit explicitly to choose the scene, e.g. before parallel use. The basis is never part of get_config().

The covariance and noise covariance are estimated from valid pixels only (a pixel invalid in any band is excluded, and so is any neighbour pair touching it); invalid pixels hold NaN in the returned scores, and pixels with a non-finite score hold the output fill after :meth:inverse.

Inputs are (C, H, W) cubes or (T, C, H, W) stacks (one fit over every frame's pixels; noise pairs never cross frames); the scores keep the input layout with the band axis replaced by the component axis ((K, H, W) / (T, K, H, W)). A 2-D (H, W) map raises ValueError.

Parameters:

Name Type Description Default
n_components int | None

Number of components to keep. None keeps all.

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

Attributes:

Name Type Description
state_ dict[str, ndarray] | None

The fitted basis ("components" A_k, "loadings" Σ_N·A_k, "mean", "eigenvalues", "noise_covariance"), or None before :meth:fit.

eigenvalues_ ndarray | None

The generalised eigenvalues λᵢ of Σ·a = λ·Σ_N·a (descending) -- the variance of each MNF score in units of its noise variance, i.e. the inverse of the component's noise fraction. None before :meth:fit.

snr_ ndarray | None

Per-component signal-to-noise ratio λᵢ − 1 (signal variance over noise variance for signal uncorrelated with the noise), descending. None before :meth:fit.

Examples:

>>> mnf = gz.restore.MNF(n_components=3).fit(scene)
>>> scores = mnf(scene)
>>> denoised = mnf.inverse(scores)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class MNF(Operator):
    """Minimum Noise Fraction transform (Green et al. 1988), with its inverse.

    Wraps :func:`~geoops.restore._src.array.fit_mnf`. The noise
    covariance ``Σ_N`` is estimated from horizontal shift differences
    (``Σ_N = Cov(z(i, j) − z(i, j + 1)) / 2``, see
    :func:`~geoops.restore._src.array.shift_difference_noise_covariance`);
    the data are noise-whitened with ``Σ_N^(−1/2)`` (Cholesky) and the
    whitened data are rotated onto their principal components. The
    output carrier holds the scores, ordered by decreasing SNR, and
    :meth:`inverse` maps scores back to band space with
    ``x̂ = Σ_N·A_k·y + x̄`` -- keeping the first ``n_components`` and
    inverting is the classical MNF noise filter.

    Fitted operator (see *Fitted operators* in the concepts guide):
    :meth:`fit` learns the basis, :meth:`transform` projects any cube with
    the same bands onto it and :meth:`inverse` reconstructs, neither
    mutating the operator. Calling an unfitted operator fits the basis on
    that first call (once, even under concurrent calls) and every later
    call reuses it; call :meth:`fit` explicitly to choose the scene, e.g.
    before parallel use. The basis is never part of ``get_config()``.

    The covariance and noise covariance are estimated from valid pixels
    only (a pixel invalid in any band is excluded, and so is any
    neighbour pair touching it); invalid pixels hold ``NaN`` in the
    returned scores, and pixels with a non-finite score hold the output
    fill after :meth:`inverse`.

    Inputs are ``(C, H, W)`` cubes or ``(T, C, H, W)`` stacks (one fit
    over every frame's pixels; noise pairs never cross frames); the
    scores keep the input layout with the band axis replaced by the
    component axis (``(K, H, W)`` / ``(T, K, H, W)``). A 2-D ``(H, W)``
    map raises ``ValueError``.

    Args:
        n_components: Number of components to keep. ``None`` keeps all.
        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.

    Attributes:
        state_: The fitted basis (``"components"`` ``A_k``,
            ``"loadings"`` ``Σ_N·A_k``, ``"mean"``, ``"eigenvalues"``,
            ``"noise_covariance"``), or ``None`` before :meth:`fit`.
        eigenvalues_: The generalised eigenvalues ``λᵢ`` of
            ``Σ·a = λ·Σ_N·a`` (descending) -- the variance of each MNF
            score in units of its noise variance, i.e. the inverse of the
            component's noise fraction. ``None`` before :meth:`fit`.
        snr_: Per-component signal-to-noise ratio ``λᵢ − 1`` (signal
            variance over noise variance for signal uncorrelated with the
            noise), descending. ``None`` before :meth:`fit`.

    Examples:
        >>> mnf = gz.restore.MNF(n_components=3).fit(scene)
        >>> scores = mnf(scene)
        >>> denoised = mnf.inverse(scores)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the noise and signal covariances are fitted over the scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "mix"}, fit={"space", "time"}
    )

    def __init__(
        self,
        *,
        n_components: int | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.n_components = n_components
        self.dim = band_dim(dim, axis, "MNF")
        self.state_: dict[str, np.ndarray] | None = None
        self.eigenvalues_: np.ndarray | None = None
        self.snr_: np.ndarray | None = None

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Learn the MNF basis from the valid pixels of ``gt``.

        Returns:
            This operator, for chaining.
        """
        axis = dim_axis(gt, self.dim, name="MNF")
        require_ndim(gt, (3, 4), type(self).__name__)
        fitted = fit_mnf(
            _band_masked(gt, axis),
            n_components=self.n_components,
            axis=axis,
        )
        eigenvalues = np.asarray(fitted["eigenvalues"])
        self.eigenvalues_ = eigenvalues
        self.snr_ = eigenvalues - 1.0
        self.state_ = {  # published last: the fit-once check reads ``state_``
            key: np.asarray(fitted[key])
            for key in (
                "components",
                "loadings",
                "mean",
                "eigenvalues",
                "noise_covariance",
            )
        }
        return self

    def _fitted(self) -> dict[str, np.ndarray]:
        state = self.state_
        if state is None:
            raise ValueError("MNF must be fitted (fit() or a first call) first")
        return state

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Project ``gt`` onto the fitted MNF basis.

        Raises:
            ValueError: If the operator is not fitted, ``gt`` is not 3-D /
                4-D or has a different band count than the fit.
        """
        axis = dim_axis(gt, self.dim, name="MNF")
        require_ndim(gt, (3, 4), type(self).__name__)
        state = self._fitted()
        scores = project_bands(
            _band_masked(gt, axis),
            components=state["components"],
            mean=state["mean"],
            axis=axis,
        )
        # Scores are a new quantity: NaN marks nodata, never the input fill.
        return wrap_filled(gt, scores, fill_value=np.nan, valid=np.isfinite(scores))

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        fit_once(self, gt, lambda: self.state_ is not None)
        return self.transform(gt)

    def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Reconstruct band space from MNF scores (``x̂ = Σ_N·A_k·y + x̄``).

        With all components the reconstruction is exact; with fewer it
        removes the low-SNR components (the MNF noise filter).

        Args:
            gt: Scores as returned by :meth:`transform` (``(K, H, W)`` or
                ``(T, K, H, W)``).

        Returns:
            The reconstructed ``(C, H, W)`` / ``(T, C, H, W)`` carrier;
            pixels with a non-finite score hold the output fill.

        Raises:
            ValueError: If the operator is not fitted or ``gt`` has a
                different component count.
        """
        axis = dim_axis(gt, self.dim, name="MNF")
        require_ndim(gt, (3, 4), f"{type(self).__name__}.inverse")
        state = self._fitted()
        out = reconstruct_bands(
            _band_masked(gt, axis),
            loadings=state["loadings"],
            mean=state["mean"],
            axis=axis,
        )
        return _rewrap_finite(gt, out)

fit(gt)

Learn the MNF basis from the valid pixels of gt.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Learn the MNF basis from the valid pixels of ``gt``.

    Returns:
        This operator, for chaining.
    """
    axis = dim_axis(gt, self.dim, name="MNF")
    require_ndim(gt, (3, 4), type(self).__name__)
    fitted = fit_mnf(
        _band_masked(gt, axis),
        n_components=self.n_components,
        axis=axis,
    )
    eigenvalues = np.asarray(fitted["eigenvalues"])
    self.eigenvalues_ = eigenvalues
    self.snr_ = eigenvalues - 1.0
    self.state_ = {  # published last: the fit-once check reads ``state_``
        key: np.asarray(fitted[key])
        for key in (
            "components",
            "loadings",
            "mean",
            "eigenvalues",
            "noise_covariance",
        )
    }
    return self

inverse(gt)

Reconstruct band space from MNF scores (x̂ = Σ_N·A_k·y + x̄).

With all components the reconstruction is exact; with fewer it removes the low-SNR components (the MNF noise filter).

Parameters:

Name Type Description Default
gt GeoArray | ndarray

Scores as returned by :meth:transform ((K, H, W) or (T, K, H, W)).

required

Returns:

Type Description
GeoArray | ndarray

The reconstructed (C, H, W) / (T, C, H, W) carrier;

GeoArray | ndarray

pixels with a non-finite score hold the output fill.

Raises:

Type Description
ValueError

If the operator is not fitted or gt has a different component count.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Reconstruct band space from MNF scores (``x̂ = Σ_N·A_k·y + x̄``).

    With all components the reconstruction is exact; with fewer it
    removes the low-SNR components (the MNF noise filter).

    Args:
        gt: Scores as returned by :meth:`transform` (``(K, H, W)`` or
            ``(T, K, H, W)``).

    Returns:
        The reconstructed ``(C, H, W)`` / ``(T, C, H, W)`` carrier;
        pixels with a non-finite score hold the output fill.

    Raises:
        ValueError: If the operator is not fitted or ``gt`` has a
            different component count.
    """
    axis = dim_axis(gt, self.dim, name="MNF")
    require_ndim(gt, (3, 4), f"{type(self).__name__}.inverse")
    state = self._fitted()
    out = reconstruct_bands(
        _band_masked(gt, axis),
        loadings=state["loadings"],
        mean=state["mean"],
        axis=axis,
    )
    return _rewrap_finite(gt, out)

transform(gt)

Project gt onto the fitted MNF basis.

Raises:

Type Description
ValueError

If the operator is not fitted, gt is not 3-D / 4-D or has a different band count than the fit.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Project ``gt`` onto the fitted MNF basis.

    Raises:
        ValueError: If the operator is not fitted, ``gt`` is not 3-D /
            4-D or has a different band count than the fit.
    """
    axis = dim_axis(gt, self.dim, name="MNF")
    require_ndim(gt, (3, 4), type(self).__name__)
    state = self._fitted()
    scores = project_bands(
        _band_masked(gt, axis),
        components=state["components"],
        mean=state["mean"],
        axis=axis,
    )
    # Scores are a new quantity: NaN marks nodata, never the input fill.
    return wrap_filled(gt, scores, fill_value=np.nan, valid=np.isfinite(scores))

MedianDenoise

Bases: Operator

Median filter over the trailing two spatial axes.

Robust to impulse noise (salt-and-pepper, hot pixels). Larger window blurs sharper features. Nodata (fill / non-finite) pixels are replaced by the median of the valid pixels before filtering and hold the output fill.

Parameters:

Name Type Description Default
window int

Side length of the median window in pixels.

3

Examples:

>>> gz.restore.MedianDenoise(window=3)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class MedianDenoise(Operator):
    """Median filter over the trailing two spatial axes.

    Robust to impulse noise (salt-and-pepper, hot pixels). Larger
    ``window`` blurs sharper features. Nodata (fill / non-finite) pixels
    are replaced by the median of the valid pixels before filtering and
    hold the output fill.

    Args:
        window: Side length of the median window in pixels.

    Examples:
        >>> gz.restore.MedianDenoise(window=3)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a local median, but nodata is first filled with the median of the whole
    # array, so a hole makes every output read the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(self, *, window: int = 3) -> None:
        self.window = window

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(gt, lambda a: median_denoise(a, window=self.window))

MomentMatching

Bases: Operator

Destripe by matching every column's mean and std to a reference.

Convenience operator equivalent to DestripeColumn(method="moment_matching", direction="column", window=...) (same nodata handling): out[:, j] = (z[:, j] − μ_j)·σᵣ_j/σ_j + μᵣ_j (Gadallah et al. 2000).

Parameters:

Name Type Description Default
window int | None

Number of neighbouring columns averaged into the reference moments, or None for a global reference.

21

Examples:

>>> gz.restore.MomentMatching(window=21)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class MomentMatching(Operator):
    """Destripe by matching every column's mean and std to a reference.

    Convenience operator equivalent to
    ``DestripeColumn(method="moment_matching", direction="column", window=...)``
    (same nodata handling): ``out[:, j] = (z[:, j] − μ_j)·σᵣ_j/σ_j + μᵣ_j``
    (Gadallah et al. 2000).

    Args:
        window: Number of neighbouring columns averaged into the
            reference moments, or ``None`` for a global reference.

    Examples:
        >>> gz.restore.MomentMatching(window=21)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each column matched to statistics over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(self, *, window: int | None = 21) -> None:
        self.window = window

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(
            gt,
            lambda a: destripe_column(
                a, method="moment_matching", direction="column", window=self.window
            ),
        )

NLMeans

Bases: Operator

Lightweight non-local-means-style denoiser.

Wraps :func:~geoops.restore._src.array.nl_means. This is a dependency-light approximation of the canonical NL-means; for production use prefer skimage.restoration.denoise_nl_means. Nodata (fill / non-finite) pixels are excluded from the smoothing and hold the output fill.

Parameters:

Name Type Description Default
window int

Nominal patch (comparison-window) side length in pixels.

5
search_radius int

Nominal search-window radius in pixels.

6
h float

Range bandwidth in data units.

0.1

Examples:

>>> gz.restore.NLMeans(window=5, search_radius=6, h=0.1)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class NLMeans(Operator):
    """Lightweight non-local-means-style denoiser.

    Wraps :func:`~geoops.restore._src.array.nl_means`. This is a
    dependency-light approximation of the canonical NL-means; for
    production use prefer ``skimage.restoration.denoise_nl_means``.
    Nodata (fill / non-finite) pixels are excluded from the smoothing
    and hold the output fill.

    Args:
        window: Nominal patch (comparison-window) side length in pixels.
        search_radius: Nominal search-window radius in pixels.
        h: Range bandwidth in data units.

    Examples:
        >>> gz.restore.NLMeans(window=5, search_radius=6, h=0.1)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # patch weights scaled by the scene's noise level
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self, *, window: int = 5, search_radius: int = 6, h: float = 0.1
    ) -> None:
        self.window = window
        self.search_radius = search_radius
        self.h = h

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        return _filter(
            gt,
            lambda a: nl_means(
                a,
                window=self.window,
                search_radius=self.search_radius,
                h=self.h,
            ),
        )

OutlierMask

Bases: Operator

Flag global outliers with a MAD or z-score threshold.

Wraps :func:~geoops.restore._src.array.outlier_mask and returns a boolean carrier (True marks outliers). Outputs the result as bool to keep the mask explicit. Nodata (fill / non-finite) pixels are excluded from the statistics and reported as False.

Parameters:

Name Type Description Default
method Literal['mad', 'zscore']

"mad" (robust, default) or "zscore".

'mad'
k float

Threshold in scaled units.

3.0

Examples:

>>> gz.restore.OutlierMask(method="mad", k=3.0)(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class OutlierMask(Operator):
    """Flag global outliers with a MAD or z-score threshold.

    Wraps :func:`~geoops.restore._src.array.outlier_mask` and returns
    a boolean carrier (``True`` marks outliers). Outputs the result
    as ``bool`` to keep the mask explicit. Nodata (fill / non-finite)
    pixels are excluded from the statistics and reported as ``False``.

    Args:
        method: ``"mad"`` (robust, default) or ``"zscore"``.
        k: Threshold in scaled units.

    Examples:
        >>> gz.restore.OutlierMask(method="mad", k=3.0)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a threshold from robust statistics of every value
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(
        self, *, method: Literal["mad", "zscore"] = "mad", k: float = 3.0
    ) -> None:
        self.method = method
        self.k = k

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        arr, valid = _masked(gt)
        mask = outlier_mask(arr, method=self.method, k=self.k).astype(bool)
        return wrap_filled(gt, mask, fill_value=False, valid=valid)

ReplaceOutliers

Bases: Operator

Replace outliers with median, NaN, or nearest-neighbour interpolation.

Wraps :func:~geoops.restore._src.array.replace_outliers. Nodata (fill / non-finite) pixels are excluded from the outlier statistics and hold the output fill value (they are not filled).

Parameters:

Name Type Description Default
method Literal['mad', 'zscore']

Outlier detector. See :class:OutlierMask.

'mad'
k float

Threshold in scaled units.

3.0
strategy Literal['median', 'nan', 'interp']

"median" (inlier median), "nan" (mark as missing), or "interp" (NaN then nearest-neighbour fill).

'median'

Examples:

>>> gz.restore.ReplaceOutliers(method="mad", k=3.0, strategy="median")(scene)
Source code in packages/geotoolz-ops/src/geoops/restore/_src/operators.py
class ReplaceOutliers(Operator):
    """Replace outliers with median, NaN, or nearest-neighbour interpolation.

    Wraps :func:`~geoops.restore._src.array.replace_outliers`.
    Nodata (fill / non-finite) pixels are excluded from the outlier
    statistics and hold the output fill value (they are not filled).

    Args:
        method: Outlier detector. See :class:`OutlierMask`.
        k: Threshold in scaled units.
        strategy: ``"median"`` (inlier median), ``"nan"`` (mark as missing),
            or ``"interp"`` (NaN then nearest-neighbour fill).

    Examples:
        >>> gz.restore.ReplaceOutliers(method="mad", k=3.0, strategy="median")(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a threshold from robust statistics of every value
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(
        self,
        *,
        method: Literal["mad", "zscore"] = "mad",
        k: float = 3.0,
        strategy: Literal["median", "nan", "interp"] = "median",
    ) -> None:
        self.method = method
        self.k = k
        self.strategy = strategy

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        arr, valid = _masked(gt)
        out = replace_outliers(
            arr, method=self.method, k=self.k, strategy=self.strategy
        )
        return _rewrap(gt, out, valid)

bilateral_denoise(arr, *, sigma_color=0.1, sigma_space=5.0)

Edge-aware denoise using a range-weighted Gaussian approximation.

Computes a spatially smoothed estimate s of shape arr and blends it with the original x using a per-pixel weight :math:w = \exp(-\tfrac{1}{2} ((x - s) / \sigma_c)^2). Where x is far from the local mean (edges, outliers), w is small and the smoothed estimate is suppressed in favour of the original, preserving edges. Where x is close to the local mean (flat regions), w is near 1 and the original passes through — the smoothing is therefore best thought of as an edge-aware attenuator of the Gaussian estimate.

This is a single-pass approximation of a full bilateral filter (no per-pixel neighbourhood weighting). It is fast and dependency- light; for true bilateral filtering use scikit-image.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). NaNs are preserved.

required
sigma_color float

Range bandwidth (data units). Smaller values preserve more edges; larger values smooth more.

0.1
sigma_space float

Spatial bandwidth in pixels.

5.0

Returns:

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

Denoised array with the same shape and NaN positions as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def bilateral_denoise(
    arr: Num[np.ndarray, "*batch h w"],
    *,
    sigma_color: float = 0.1,
    sigma_space: float = 5.0,
) -> Float[np.ndarray, "*batch h w"]:
    r"""Edge-aware denoise using a range-weighted Gaussian approximation.

    Computes a spatially smoothed estimate ``s`` of shape ``arr`` and
    blends it with the original ``x`` using a per-pixel weight
    :math:`w = \exp(-\tfrac{1}{2} ((x - s) / \sigma_c)^2)`. Where
    ``x`` is far from the local mean (edges, outliers), ``w`` is small
    and the *smoothed* estimate is suppressed in favour of the
    original, preserving edges. Where ``x`` is close to the local mean
    (flat regions), ``w`` is near 1 and the original passes through —
    the smoothing is therefore best thought of as an edge-aware
    *attenuator* of the Gaussian estimate.

    This is a single-pass approximation of a full bilateral filter (no
    per-pixel neighbourhood weighting). It is fast and dependency-
    light; for true bilateral filtering use scikit-image.

    Args:
        arr: Array of shape ``(..., H, W)``. NaNs are preserved.
        sigma_color: Range bandwidth (data units). Smaller values
            preserve more edges; larger values smooth more.
        sigma_space: Spatial bandwidth in pixels.

    Returns:
        Denoised array with the same shape and NaN positions as ``arr``.
    """
    values = np.asarray(arr, dtype=float)
    smooth = gaussian_denoise(values, sigma=sigma_space)
    safe_color = max(float(sigma_color), _EPSILON)
    weights = np.exp(-0.5 * ((values - smooth) / safe_color) ** 2)
    return _preserve_nan(values, weights * values + (1.0 - weights) * smooth)

despeckle_frost(arr, *, window=7, damping=2.0)

Apply the Frost (1982) adaptive exponential-kernel speckle filter.

Each output pixel is a normalised weighted mean of its window × window neighbourhood with the exponentially decaying kernel::

m(t) = exp(−K · Cᵥ² · |t|)
x̂    = Σₜ m(t)·z(t) / Σₜ m(t)

where K is damping, |t| is the Euclidean distance (in pixels) from the centre pixel and Cᵥ² = σ_z² / z̄² is the local squared coefficient of variation, computed over the same window. On homogeneous areas Cᵥ² is small, the kernel is wide and the filter approaches the box mean; at edges Cᵥ² is large, the kernel narrows onto the centre pixel and the edge is preserved. Where z̄ = 0 the kernel is the box mean.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). NaNs are preserved and excluded (zero weight) from the neighbourhood sums.

required
window int

Side length of the kernel window. Must be positive.

7
damping float

Damping factor K. Larger values narrow the kernel (keep more edge contrast); 0 is the box mean.

2.0

Returns:

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

Smoothed array with the same shape and NaN positions as arr.

References

Frost, V. S., Stiles, J. A., Shanmugan, K. S., & Holtzman, J. C. (1982). A model for radar images and its application to adaptive digital filtering of multiplicative noise. IEEE TPAMI, 4(2), 157-166.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def despeckle_frost(
    arr: Num[np.ndarray, "*batch h w"], *, window: int = 7, damping: float = 2.0
) -> Float[np.ndarray, "*batch h w"]:
    r"""Apply the Frost (1982) adaptive exponential-kernel speckle filter.

    Each output pixel is a normalised weighted mean of its
    ``window`` × ``window`` neighbourhood with the exponentially
    decaying kernel::

        m(t) = exp(−K · Cᵥ² · |t|)
        x̂    = Σₜ m(t)·z(t) / Σₜ m(t)

    where ``K`` is ``damping``, ``|t|`` is the Euclidean distance (in
    pixels) from the centre pixel and ``Cᵥ² = σ_z² / z̄²`` is the local
    squared coefficient of variation, computed over the same window.
    On homogeneous areas ``Cᵥ²`` is small, the kernel is wide and the
    filter approaches the box mean; at edges ``Cᵥ²`` is large, the
    kernel narrows onto the centre pixel and the edge is preserved.
    Where ``z̄ = 0`` the kernel is the box mean.

    Args:
        arr: Array of shape ``(..., H, W)``. NaNs are preserved and
            excluded (zero weight) from the neighbourhood sums.
        window: Side length of the kernel window. Must be positive.
        damping: Damping factor ``K``. Larger values narrow the kernel
            (keep more edge contrast); ``0`` is the box mean.

    Returns:
        Smoothed array with the same shape and NaN positions as ``arr``.

    References:
        Frost, V. S., Stiles, J. A., Shanmugan, K. S., & Holtzman, J. C.
        (1982). A model for radar images and its application to adaptive
        digital filtering of multiplicative noise. IEEE TPAMI, 4(2),
        157-166.
    """
    values = np.asarray(arr, dtype=float)
    mean, var = _local_moments(values, window)
    cv_sq = np.divide(var, mean * mean, out=np.zeros_like(var), where=mean != 0)
    rate = float(damping) * cv_sq
    valid = np.isfinite(values)
    filled = np.where(valid, values, 0.0)
    half = int(window) // 2
    lo, hi = -half, int(window) - half
    pad = [(0, 0)] * (values.ndim - 2) + [(half, window - 1 - half)] * 2
    padded = np.pad(filled, pad, mode="edge")
    padded_valid = np.pad(valid, pad, mode="edge")
    height, width = values.shape[-2:]
    total = np.zeros_like(filled)
    weight_sum = np.zeros_like(filled)
    for dy in range(lo, hi):
        for dx in range(lo, hi):
            rows = slice(dy + half, dy + half + height)
            cols = slice(dx + half, dx + half + width)
            weight = np.exp(-rate * np.hypot(dy, dx)) * padded_valid[..., rows, cols]
            total += weight * padded[..., rows, cols]
            weight_sum += weight
    out = np.divide(
        total, weight_sum, out=np.full_like(total, np.nan), where=weight_sum > 0
    )
    return _preserve_nan(values, out)

despeckle_lee(arr, *, window=7, cu=0.523)

Apply the Lee (1980) local-statistics speckle filter.

Speckle model: z = x·v with x the unspeckled signal and v unit-mean multiplicative noise of coefficient of variation Cᵤ = σᵥ (cu). With the local mean z̄ and variance σ_z² over a window × window neighbourhood, the model gives (Lee 1980)::

σ_x² = max((σ_z² − Cᵤ²·z̄²) / (1 + Cᵤ²), 0)
k    = σ_x² / (σ_x² + Cᵤ²·z̄²)
x̂    = z̄ + k·(z − z̄)

In terms of the local coefficient of variation Cᵢ = σ_z / z̄ the gain is k = (Cᵢ² − Cᵤ²) / (Cᵢ² + Cᵤ⁴) clipped at 0, so k ∈ [0, 1): on homogeneous speckle (Cᵢ ≤ Cᵤ) k = 0 and the filter returns the local mean; at edges and point targets (Cᵢ ≫ Cᵤ) k → 1 and the pixel passes through. Dropping the O(Cᵤ⁴) term gives the familiar linearised k ≈ 1 − Cᵤ²/Cᵢ².

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). NaNs are preserved and excluded from the window statistics.

required
window int

Side length of the local window. Must be positive.

7
cu float

Noise coefficient of variation Cᵤ. 1/√L for L-look intensity; 0.523 ≈ √(4/π − 1) is the single-look amplitude value (default).

0.523

Returns:

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

Smoothed array with the same shape and NaN positions as arr.

References

Lee, J.-S. (1980). Digital image enhancement and noise filtering by use of local statistics. IEEE TPAMI, 2(2), 165-168.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def despeckle_lee(
    arr: Num[np.ndarray, "*batch h w"], *, window: int = 7, cu: float = 0.523
) -> Float[np.ndarray, "*batch h w"]:
    r"""Apply the Lee (1980) local-statistics speckle filter.

    Speckle model: ``z = x·v`` with ``x`` the unspeckled signal and ``v``
    unit-mean multiplicative noise of coefficient of variation
    ``Cᵤ = σᵥ`` (``cu``). With the local mean ``z̄`` and variance ``σ_z²``
    over a ``window`` × ``window`` neighbourhood, the model gives
    (Lee 1980)::

        σ_x² = max((σ_z² − Cᵤ²·z̄²) / (1 + Cᵤ²), 0)
        k    = σ_x² / (σ_x² + Cᵤ²·z̄²)
        x̂    = z̄ + k·(z − z̄)

    In terms of the local coefficient of variation ``Cᵢ = σ_z / z̄`` the
    gain is ``k = (Cᵢ² − Cᵤ²) / (Cᵢ² + Cᵤ⁴)`` clipped at ``0``, so
    ``k ∈ [0, 1)``: on homogeneous speckle (``Cᵢ ≤ Cᵤ``) ``k = 0`` and
    the filter returns the local mean; at edges and point targets
    (``Cᵢ ≫ Cᵤ``) ``k → 1`` and the pixel passes through. Dropping the
    ``O(Cᵤ⁴)`` term gives the familiar linearised ``k ≈ 1 − Cᵤ²/Cᵢ²``.

    Args:
        arr: Array of shape ``(..., H, W)``. NaNs are preserved and
            excluded from the window statistics.
        window: Side length of the local window. Must be positive.
        cu: Noise coefficient of variation ``Cᵤ``. ``1/√L`` for
            ``L``-look intensity; ``0.523 ≈ √(4/π − 1)`` is the
            single-look *amplitude* value (default).

    Returns:
        Smoothed array with the same shape and NaN positions as ``arr``.

    References:
        Lee, J.-S. (1980). Digital image enhancement and noise filtering
        by use of local statistics. IEEE TPAMI, 2(2), 165-168.
    """
    values = np.asarray(arr, dtype=float)
    mean, var = _local_moments(values, window)
    noise_var = (float(cu) * mean) ** 2
    signal_var = np.maximum((var - noise_var) / (1.0 + float(cu) ** 2), 0.0)
    denom = signal_var + noise_var
    gain = np.divide(signal_var, denom, out=np.zeros_like(signal_var), where=denom > 0)
    return _preserve_nan(values, mean + gain * (values - mean))

despeckle_refined_lee(arr, *, window=7)

Apply a Refined-Lee approximation.

The full Refined-Lee filter chooses one of eight directional sub-windows per pixel before applying the Lee gain. This dependency-light implementation skips the directional selection and just calls :func:despeckle_lee with the default cu. It is kept under a distinct name so pipelines can swap in a true Refined- Lee later without renaming nodes.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). NaNs are preserved.

required
window int

Side length of the local window. Must be positive.

7

Returns:

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

Smoothed array with the same shape and NaN positions as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def despeckle_refined_lee(
    arr: Num[np.ndarray, "*batch h w"], *, window: int = 7
) -> Float[np.ndarray, "*batch h w"]:
    """Apply a Refined-Lee approximation.

    The full Refined-Lee filter chooses one of eight directional
    sub-windows per pixel before applying the Lee gain. This
    dependency-light implementation skips the directional selection and
    just calls :func:`despeckle_lee` with the default ``cu``. It is
    kept under a distinct name so pipelines can swap in a true Refined-
    Lee later without renaming nodes.

    Args:
        arr: Array of shape ``(..., H, W)``. NaNs are preserved.
        window: Side length of the local window. Must be positive.

    Returns:
        Smoothed array with the same shape and NaN positions as ``arr``.
    """
    return despeckle_lee(arr, window=window, cu=0.523)

destripe_column(arr, *, method='mean', direction='column', window=21)

Remove row or column striping by matching per-line statistics.

For direction="column" (default) every column j is summarised over its rows; direction="row" swaps the roles. Leading axes are independent planes.

method="mean" / "median" remove a per-column offset::

out[:, j] = z[:, j] − (s_j − s̄)

where s_j is the column mean (median) and s̄ the mean (median) of all s_j.

method="moment_matching" removes a per-column gain and offset (Gadallah et al. 2000): each column is linearly rescaled so its mean μ_j and standard deviation σ_j match a reference (μᵣ, σᵣ)::

out[:, j] = (z[:, j] − μ_j) · σᵣ_j / σ_j + μᵣ_j

With window=None the reference is global (μᵣ and σᵣ are the averages of μ_j and σ_j over all columns); with an integer window it is the moving average of μ_j / σ_j over the window neighbouring columns, which keeps genuine cross-track trends (e.g. illumination) while removing the detector-to-detector stripes. Within-column detail is untouched apart from the per-column linear map. A column with σ_j = 0 only has its offset matched.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). NaNs are preserved and excluded from the statistics.

required
method Literal['mean', 'median', 'moment_matching']

"mean", "median" or "moment_matching".

'mean'
direction Literal['column', 'row']

Striping direction ("column" for vertical stripes, "row" for horizontal).

'column'
window int | None

Number of neighbouring columns (rows) averaged into the moment-matching reference, or None for a global reference. Only consulted for method="moment_matching".

21

Returns:

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

Destriped array with the same shape and NaN positions as

Float[ndarray, '*batch h w']

arr.

Raises:

Type Description
ValueError

If arr has fewer than two dimensions, method is not one of the documented choices or window is not positive.

References

Gadallah, F. L., Csillag, F., & Smith, E. J. M. (2000). Destriping multisensor imagery with moment matching. International Journal of Remote Sensing, 21(12), 2505-2511.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def destripe_column(
    arr: Num[np.ndarray, "*batch h w"],
    *,
    method: Literal["mean", "median", "moment_matching"] = "mean",
    direction: Literal["column", "row"] = "column",
    window: int | None = 21,
) -> Float[np.ndarray, "*batch h w"]:
    r"""Remove row or column striping by matching per-line statistics.

    For ``direction="column"`` (default) every column ``j`` is summarised over
    its rows; ``direction="row"`` swaps the roles. Leading axes are independent
    planes.

    ``method="mean"`` / ``"median"`` remove a per-column *offset*::

        out[:, j] = z[:, j] − (s_j − s̄)

    where ``s_j`` is the column mean (median) and ``s̄`` the mean (median)
    of all ``s_j``.

    ``method="moment_matching"`` removes a per-column *gain and offset*
    (Gadallah et al. 2000): each column is linearly rescaled so its mean
    ``μ_j`` and standard deviation ``σ_j`` match a reference ``(μᵣ, σᵣ)``::

        out[:, j] = (z[:, j] − μ_j) · σᵣ_j / σ_j + μᵣ_j

    With ``window=None`` the reference is global (``μᵣ`` and ``σᵣ`` are
    the averages of ``μ_j`` and ``σ_j`` over all columns); with an integer
    ``window`` it is the moving average of ``μ_j`` / ``σ_j`` over the
    ``window`` neighbouring columns, which keeps genuine cross-track
    trends (e.g. illumination) while removing the detector-to-detector
    stripes. Within-column detail is untouched apart from the per-column
    linear map. A column with ``σ_j = 0`` only has its offset matched.

    Args:
        arr: Array of shape ``(..., H, W)``. NaNs are preserved and
            excluded from the statistics.
        method: ``"mean"``, ``"median"`` or ``"moment_matching"``.
        direction: Striping direction (``"column"`` for vertical stripes,
            ``"row"`` for horizontal).
        window: Number of neighbouring columns (rows) averaged into the
            moment-matching reference, or ``None`` for a global
            reference. Only consulted for ``method="moment_matching"``.

    Returns:
        Destriped array with the same shape and NaN positions as
        ``arr``.

    Raises:
        ValueError: If ``arr`` has fewer than two dimensions, ``method``
            is not one of the documented choices or ``window`` is not
            positive.

    References:
        Gadallah, F. L., Csillag, F., & Smith, E. J. M. (2000).
        Destriping multisensor imagery with moment matching.
        International Journal of Remote Sensing, 21(12), 2505-2511.
    """
    values = np.asarray(arr, dtype=float)
    if values.ndim < 2:
        raise ValueError("destripe_column expects at least two spatial dimensions")
    if method not in {"mean", "median", "moment_matching"}:
        raise ValueError("method must be 'mean', 'median', or 'moment_matching'")
    spatial_axis = -1 if direction == "column" else -2
    reduce_axis = -2 if direction == "column" else -1
    # All-NaN lines (e.g. a nodata column) have NaN statistics by design;
    # silence numpy's empty-slice warnings for them.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RuntimeWarning)
        if method != "moment_matching":
            reducer = np.nanmedian if method == "median" else np.nanmean
            profile = reducer(values, axis=reduce_axis, keepdims=True)
            target = reducer(profile, axis=spatial_axis, keepdims=True)
            return _preserve_nan(values, values - (profile - target))
        line_mean = np.nanmean(values, axis=reduce_axis, keepdims=True)
        line_std = np.nanstd(values, axis=reduce_axis, keepdims=True)
    if window is None:
        ref_mean = np.nanmean(line_mean, axis=spatial_axis, keepdims=True)
        ref_std = np.nanmean(line_std, axis=spatial_axis, keepdims=True)
    else:
        if window <= 0:
            raise ValueError("window must be positive or None")
        size = [1] * values.ndim
        size[spatial_axis] = int(window)
        ref_mean = _nanmean_filter(line_mean, tuple(size))
        ref_std = _nanmean_filter(line_std, tuple(size))
    gain = np.divide(ref_std, line_std, out=np.ones_like(line_std), where=line_std > 0)
    return _preserve_nan(values, (values - line_mean) * gain + ref_mean)

gap_fill_biharmonic(arr)

Fill NaNs by biharmonic inpainting.

Solves :math:\Delta^2 u = 0 on the missing pixels with the finite pixels as Dirichlet values, through functax.project.fill_gaps (the [interp] extra, same edge-repeat Laplacian as :func:gap_fill_laplacian). Smoother across the mask boundary than the harmonic fill: the gradient is continuous there too.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). Planes are processed independently; an all-NaN plane stays NaN.

required

Returns:

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

Filled array with the same shape as arr; the original

Float[ndarray, '*batch h w']

finite pixels are preserved exactly.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def gap_fill_biharmonic(
    arr: Num[np.ndarray, "*batch h w"],
) -> Float[np.ndarray, "*batch h w"]:
    r"""Fill NaNs by biharmonic inpainting.

    Solves :math:`\Delta^2 u = 0` on the missing pixels with the finite
    pixels as Dirichlet values, through ``functax.project.fill_gaps``
    (the ``[interp]`` extra, same edge-repeat Laplacian as
    :func:`gap_fill_laplacian`). Smoother across the mask boundary than the
    harmonic fill: the gradient is continuous there too.

    Args:
        arr: Array of shape ``(..., H, W)``. Planes are processed
            independently; an all-NaN plane stays NaN.

    Returns:
        Filled array with the same shape as ``arr``; the original
        finite pixels are preserved exactly.
    """
    return _fill_gaps(arr, "biharmonic", "gap_fill_biharmonic")

gap_fill_idw(arr, *, power=2.0, radius=5)

Fill NaNs with inverse-distance weighted finite neighbours.

For each NaN pixel p, takes all finite neighbours within radius pixels (Euclidean) and replaces it with :math:\hat{p} = \sum_i w_i x_i / \sum_i w_i where :math:w_i = 1 / \max(d_i, \epsilon)^{\text{power}}. NaNs whose neighbourhood is empty are left as NaN.

The weights come from one functax.interp.InverseDistance plan per 2-D plane (the [interp] extra), from the finite pixels to the gaps, with k the number of pixels within radius so the neighbourhood is the whole disc.

Powers >= 64 numerically converge to nearest-neighbour weights, so the function short-circuits to :func:gap_fill_nearest in that case.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). Planes are processed independently.

required
power float

IDW exponent. 2.0 is the standard choice; larger values bias toward nearer neighbours.

2.0
radius int

Maximum search radius in pixels.

5

Returns:

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

Filled array with the same shape as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def gap_fill_idw(
    arr: Num[np.ndarray, "*batch h w"], *, power: float = 2.0, radius: int = 5
) -> Float[np.ndarray, "*batch h w"]:
    r"""Fill NaNs with inverse-distance weighted finite neighbours.

    For each NaN pixel ``p``, takes all finite neighbours within
    ``radius`` pixels (Euclidean) and replaces it with
    :math:`\hat{p} = \sum_i w_i x_i / \sum_i w_i` where
    :math:`w_i = 1 / \max(d_i, \epsilon)^{\text{power}}`. NaNs whose
    neighbourhood is empty are left as NaN.

    The weights come from one ``functax.interp.InverseDistance`` plan per
    2-D plane (the ``[interp]`` extra), from the finite pixels to the gaps,
    with ``k`` the number of pixels within ``radius`` so the neighbourhood is
    the whole disc.

    Powers ``>= 64`` numerically converge to nearest-neighbour weights,
    so the function short-circuits to :func:`gap_fill_nearest` in that case.

    Args:
        arr: Array of shape ``(..., H, W)``. Planes are processed
            independently.
        power: IDW exponent. ``2.0`` is the standard choice; larger
            values bias toward nearer neighbours.
        radius: Maximum search radius in pixels.

    Returns:
        Filled array with the same shape as ``arr``.
    """
    if power >= _IDW_POWER_THRESHOLD:
        return gap_fill_nearest(arr, max_distance=radius)
    values = np.asarray(arr, dtype=float)
    return _fill_from_valid(
        values,
        k=_lattice_neighbours(radius),
        power=power,
        radius=_inclusive(radius),
        feature="gap_fill_idw",
    )

gap_fill_laplacian(arr, *, iterations=None)

Fill NaNs by solving a discrete Laplace equation.

Solves :math:\Delta u = 0 on the missing pixels with the finite pixels as Dirichlet values, through functax.project.fill_gaps (the [interp] extra): the five-point Laplacian with edge-repeat boundaries (the ghost pixel past the raster edge is the edge pixel), solved by conjugate gradients to √ε. This is the limit the Jacobi sweeps of earlier releases converged to.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). Planes are processed independently; an all-NaN plane stays NaN.

required
iterations int | None

Deprecated and ignored (the solve is exact); passing it warns.

None

Returns:

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

Filled array with the same shape as arr; the original

Float[ndarray, '*batch h w']

finite pixels are preserved exactly.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def gap_fill_laplacian(
    arr: Num[np.ndarray, "*batch h w"], *, iterations: int | None = None
) -> Float[np.ndarray, "*batch h w"]:
    r"""Fill NaNs by solving a discrete Laplace equation.

    Solves :math:`\Delta u = 0` on the missing pixels with the finite
    pixels as Dirichlet values, through ``functax.project.fill_gaps``
    (the ``[interp]`` extra): the five-point Laplacian with edge-repeat
    boundaries (the ghost pixel past the raster edge is the edge pixel), solved
    by conjugate gradients to √ε. This is the limit the Jacobi sweeps of
    earlier releases converged to.

    Args:
        arr: Array of shape ``(..., H, W)``. Planes are processed
            independently; an all-NaN plane stays NaN.
        iterations: Deprecated and ignored (the solve is exact); passing it
            warns.

    Returns:
        Filled array with the same shape as ``arr``; the original
        finite pixels are preserved exactly.
    """
    _warn_iterations(iterations, "gap_fill_laplacian")
    return _fill_gaps(arr, "laplace", "gap_fill_laplacian")

gap_fill_nearest(arr, *, max_distance=None)

Fill NaNs from the nearest finite neighbour.

Reads each gap from its nearest finite pixel through a one-neighbour functax.interp.InverseDistance plan per 2-D plane (the [interp] extra). Where several finite pixels are equally near, the plan's k-d tree picks one of them. Pixels whose nearest finite neighbour is farther than max_distance (when given) are left as NaN.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W). Planes are processed independently.

required
max_distance int | None

Optional maximum Euclidean fill radius in pixels. None (default) fills every NaN that has at least one finite neighbour anywhere in the plane.

None

Returns:

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

Filled array with the same shape as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def gap_fill_nearest(
    arr: Num[np.ndarray, "*batch h w"], *, max_distance: int | None = None
) -> Float[np.ndarray, "*batch h w"]:
    """Fill NaNs from the nearest finite neighbour.

    Reads each gap from its nearest finite pixel through a one-neighbour
    ``functax.interp.InverseDistance`` plan per 2-D plane (the ``[interp]``
    extra). Where several finite pixels are equally near, the plan's k-d
    tree picks one of them. Pixels whose nearest finite neighbour is
    farther than ``max_distance`` (when given) are left as NaN.

    Args:
        arr: Array of shape ``(..., H, W)``. Planes are processed
            independently.
        max_distance: Optional maximum Euclidean fill radius in pixels.
            ``None`` (default) fills every NaN that has at least one
            finite neighbour anywhere in the plane.

    Returns:
        Filled array with the same shape as ``arr``.
    """
    values = np.asarray(arr, dtype=float)
    radius = None if max_distance is None else _inclusive(max_distance)
    return _fill_from_valid(
        values, k=1, power=1.0, radius=radius, feature="gap_fill_nearest"
    )

gaussian_denoise(arr, *, sigma=1.0)

Gaussian smooth over the trailing two (spatial) axes.

NaN-aware: missing pixels are excluded from both numerator and weight (Nadaraya-Watson style normalisation), then re-stamped onto the output. Non-spatial axes (e.g. bands) are filtered independently with sigma=0.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W).

required
sigma float

Gaussian standard deviation in pixels. 0 is a no-op.

1.0

Returns:

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

Smoothed array with the same shape and NaN positions as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def gaussian_denoise(
    arr: Num[np.ndarray, "*batch h w"], *, sigma: float = 1.0
) -> Float[np.ndarray, "*batch h w"]:
    """Gaussian smooth over the trailing two (spatial) axes.

    NaN-aware: missing pixels are excluded from both numerator and
    weight (Nadaraya-Watson style normalisation), then re-stamped onto
    the output. Non-spatial axes (e.g. bands) are filtered
    independently with ``sigma=0``.

    Args:
        arr: Array of shape ``(..., H, W)``.
        sigma: Gaussian standard deviation in pixels. ``0`` is a no-op.

    Returns:
        Smoothed array with the same shape and NaN positions as ``arr``.
    """
    values = np.asarray(arr, dtype=float)
    sigma_tuple = (0.0,) * max(values.ndim - 2, 0) + (float(sigma), float(sigma))
    valid = np.isfinite(values)
    filled = np.where(valid, values, 0.0)
    weights = ndimage.gaussian_filter(valid.astype(float), sigma_tuple, mode="nearest")
    smooth = ndimage.gaussian_filter(filled, sigma_tuple, mode="nearest")
    out = np.divide(
        smooth, weights, out=np.full_like(smooth, np.nan), where=weights > 0
    )
    return _preserve_nan(values, out)

median_denoise(arr, *, window=3)

Median smooth over the trailing two (spatial) axes.

NaNs are temporarily replaced with the global nanmedian so SciPy's median filter is well-defined, then re-stamped on the output. Edge pixels use mode="nearest" (the edge pixel is repeated outwards, not reflected).

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W).

required
window int

Side length of the median window. Must be positive.

3

Returns:

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

Smoothed array with the same shape and NaN positions as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def median_denoise(
    arr: Num[np.ndarray, "*batch h w"], *, window: int = 3
) -> Float[np.ndarray, "*batch h w"]:
    """Median smooth over the trailing two (spatial) axes.

    NaNs are temporarily replaced with the global ``nanmedian`` so
    SciPy's median filter is well-defined, then re-stamped on the
    output. Edge pixels use ``mode="nearest"`` (the edge pixel is
    repeated outwards, not reflected).

    Args:
        arr: Array of shape ``(..., H, W)``.
        window: Side length of the median window. Must be positive.

    Returns:
        Smoothed array with the same shape and NaN positions as ``arr``.
    """
    values = np.asarray(arr, dtype=float)
    filled = np.where(np.isfinite(values), values, np.nanmedian(values))
    out = ndimage.median_filter(
        filled, size=_spatial_size(values, window), mode="nearest"
    )
    return _preserve_nan(values, out)

nl_means(arr, *, window=5, search_radius=6, h=0.1)

Lightweight non-local-means-style denoiser.

True non-local-means averages each pixel with similarly-patterned patches elsewhere in the image, which is expensive and adds scikit-image as a dependency. This implementation is a dependency-light approximation: it computes a wide Gaussian smoothing estimate whose effective radius is set by (search_radius + window) / 6, then blends it with the original using the same range-weighted scheme as :func:bilateral_denoise with bandwidth h.

Use this only when scikit-image is unavailable; for production NL-means, prefer skimage.restoration.denoise_nl_means.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Array of shape (..., H, W).

required
window int

Nominal patch side length (pixels).

5
search_radius int

Nominal search-window radius (pixels).

6
h float

Range bandwidth (data units).

0.1

Returns:

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

Denoised array with the same shape and NaN positions as arr.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def nl_means(
    arr: Num[np.ndarray, "*batch h w"],
    *,
    window: int = 5,
    search_radius: int = 6,
    h: float = 0.1,
) -> Float[np.ndarray, "*batch h w"]:
    """Lightweight non-local-means-style denoiser.

    True non-local-means averages each pixel with similarly-patterned
    patches elsewhere in the image, which is expensive and adds
    scikit-image as a dependency. This implementation is a
    *dependency-light approximation*: it computes a wide Gaussian
    smoothing estimate whose effective radius is set by
    ``(search_radius + window) / 6``, then blends it with the
    original using the same range-weighted scheme as
    :func:`bilateral_denoise` with bandwidth ``h``.

    Use this only when scikit-image is unavailable; for production
    NL-means, prefer ``skimage.restoration.denoise_nl_means``.

    Args:
        arr: Array of shape ``(..., H, W)``.
        window: Nominal patch side length (pixels).
        search_radius: Nominal search-window radius (pixels).
        h: Range bandwidth (data units).

    Returns:
        Denoised array with the same shape and NaN positions as ``arr``.
    """
    sigma = max((float(search_radius) + float(window)) / 6.0, 0.1)
    smooth = gaussian_denoise(arr, sigma=sigma)
    values = np.asarray(arr, dtype=float)
    weights = np.exp(-0.5 * ((values - smooth) / max(float(h), _EPSILON)) ** 2)
    return _preserve_nan(values, weights * values + (1.0 - weights) * smooth)

outlier_mask(arr, *, method='mad', k=3.0)

Flag robust global outliers.

method="mad" (default) uses the median + median-absolute- deviation; "zscore" uses the mean + standard deviation. The MAD is scaled by 1 / Phi^{-1}(0.75) so it estimates the same scale as the standard deviation under a Gaussian model. Returns a boolean array where True marks outliers.

When the estimated scale is zero (constant data) the mask flags any pixel that differs from the centre, which is consistent with "anything that breaks the constant pattern is an outlier". When the scale is non-finite (all-NaN input) returns an all-False mask.

Parameters:

Name Type Description Default
arr Num[ndarray, '*dims']

Input array of any shape. Statistics are global (whole array), not windowed.

required
method Literal['mad', 'zscore']

"mad" (robust, default) or "zscore".

'mad'
k float

Threshold in scaled units (approximately standard deviations).

3.0

Returns:

Type Description
Bool[ndarray, '*dims']

Boolean array of the same shape; True marks outliers.

Raises:

Type Description
ValueError

If method is not "mad" or "zscore".

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def outlier_mask(
    arr: Num[np.ndarray, "*dims"],
    *,
    method: Literal["mad", "zscore"] = "mad",
    k: float = 3.0,
) -> Bool[np.ndarray, "*dims"]:
    r"""Flag robust global outliers.

    ``method="mad"`` (default) uses the median + median-absolute-
    deviation; ``"zscore"`` uses the mean + standard deviation. The MAD
    is scaled by 1 / Phi^{-1}(0.75) so it estimates the same scale as
    the standard deviation under a Gaussian model. Returns a boolean
    array where ``True`` marks outliers.

    When the estimated scale is zero (constant data) the mask flags any
    pixel that differs from the centre, which is consistent with
    "anything that breaks the constant pattern is an outlier". When the
    scale is non-finite (all-NaN input) returns an all-False mask.

    Args:
        arr: Input array of any shape. Statistics are global (whole
            array), not windowed.
        method: ``"mad"`` (robust, default) or ``"zscore"``.
        k: Threshold in scaled units (approximately standard
            deviations).

    Returns:
        Boolean array of the same shape; ``True`` marks outliers.

    Raises:
        ValueError: If ``method`` is not ``"mad"`` or ``"zscore"``.
    """
    values = np.asarray(arr, dtype=float)
    if method == "mad":
        center = np.nanmedian(values)
        # _MAD_TO_STD_SCALE converts MAD to a std estimate; it is the
        # consistency constant 1 / inverse_standard_normal_cdf(0.75).
        scale = _MAD_TO_STD_SCALE * np.nanmedian(np.abs(values - center))
    elif method == "zscore":
        center = np.nanmean(values)
        scale = np.nanstd(values)
    else:
        raise ValueError("method must be 'mad' or 'zscore'")
    if scale == 0:
        return np.isfinite(values) & (values != center)
    if not np.isfinite(scale):
        return np.zeros(values.shape, dtype=bool)
    return np.abs(values - center) > k * scale

pca_denoise(arr, *, n_components, axis=-3)

Reconstruct an array from its top PCA components along axis.

Convenience composition of :func:fit_pca and :func:inverse_pca. Keeping fewer components than bands suppresses band-uncorrelated noise while preserving the dominant spectral structure.

Parameters:

Name Type Description Default
arr Num[ndarray, '*dims']

Array with a band axis at position axis; typically (bands, H, W). The components are fitted on the pixels that are finite in every band; NaN positions are re-stamped as NaN on the output.

required
n_components int

Number of principal components to keep. Must be between 1 and the number of bands.

required
axis int

Position of the band axis. Defaults to -3.

-3

Returns:

Type Description
Float[ndarray, '*dims']

Reconstructed array with the same shape and NaN positions as

Float[ndarray, '*dims']

arr.

Raises:

Type Description
ValueError

If n_components is out of range, any band is entirely NaN or no pixel is finite in every band.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def pca_denoise(
    arr: Num[np.ndarray, "*dims"], *, n_components: int, axis: int = -3
) -> Float[np.ndarray, "*dims"]:
    """Reconstruct an array from its top PCA components along ``axis``.

    Convenience composition of :func:`fit_pca` and :func:`inverse_pca`.
    Keeping fewer components than bands suppresses band-uncorrelated
    noise while preserving the dominant spectral structure.

    Args:
        arr: Array with a band axis at position ``axis``; typically
            ``(bands, H, W)``. The components are fitted on the pixels
            that are finite in every band; NaN positions are re-stamped
            as NaN on the output.
        n_components: Number of principal components to keep. Must be
            between 1 and the number of bands.
        axis: Position of the band axis. Defaults to ``-3``.

    Returns:
        Reconstructed array with the same shape and NaN positions as
        ``arr``.

    Raises:
        ValueError: If ``n_components`` is out of range, any band is
            entirely NaN or no pixel is finite in every band.
    """
    model = fit_pca(arr, n_components=n_components, axis=axis)
    return inverse_pca(model["scores"], model)

replace_outliers(arr, *, method='mad', k=3.0, strategy='median')

Replace detected outliers with a scalar or nearest-neighbour fill.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch h w']

Input array.

required
method Literal['mad', 'zscore']

Outlier-detection strategy. See :func:outlier_mask.

'mad'
k float

Outlier threshold in scaled units.

3.0
strategy Literal['median', 'nan', 'interp']

"median" replaces outliers with the median of the inliers; "nan" sets them to NaN; "interp" fills them by nearest-neighbour interpolation over the spatial axes via :func:gap_fill_nearest.

'median'

Returns:

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

Array of the same shape as arr with outliers replaced.

Raises:

Type Description
ValueError

If method or strategy is not one of the documented choices.

Source code in packages/geotoolz-ops/src/geoops/restore/_src/array.py
def replace_outliers(
    arr: Num[np.ndarray, "*batch h w"],
    *,
    method: Literal["mad", "zscore"] = "mad",
    k: float = 3.0,
    strategy: Literal["median", "nan", "interp"] = "median",
) -> Float[np.ndarray, "*batch h w"]:
    """Replace detected outliers with a scalar or nearest-neighbour fill.

    Args:
        arr: Input array.
        method: Outlier-detection strategy. See :func:`outlier_mask`.
        k: Outlier threshold in scaled units.
        strategy: ``"median"`` replaces outliers with the median of the
            inliers; ``"nan"`` sets them to NaN; ``"interp"`` fills
            them by nearest-neighbour interpolation over the spatial
            axes via :func:`gap_fill_nearest`.

    Returns:
        Array of the same shape as ``arr`` with outliers replaced.

    Raises:
        ValueError: If ``method`` or ``strategy`` is not one of the
            documented choices.
    """
    values = np.asarray(arr, dtype=float)
    mask = outlier_mask(values, method=method, k=k)
    if strategy == "median":
        return np.where(mask, np.nanmedian(values[~mask]), values)
    if strategy == "nan":
        return np.where(mask, np.nan, values)
    if strategy == "interp":
        return gap_fill_nearest(np.where(mask, np.nan, values))
    raise ValueError("strategy must be 'median', 'nan', or 'interp'")