Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Define an operator

Write your own step and it composes with every built-in: in a Sequential, in a Graph, and in get_config(). This page is the one walkthrough; the model behind it is in Concepts.

Write the operator

Subclass geoops.Operator (pipekit’s), store each keyword-only argument under its own name, and do the work in _apply. Rewrap the result with geoops.carrier.wrap_like, or wrap_filled when nodata pixels need the output’s fill, then run geoops.testing.check_operator.

import numpy as np
from geoarray import GeoArray
from rasterio.transform import from_origin

import geoops as gz
from geoops.carrier import carried_fill, wrap_filled
from geoops.testing import check_operator


class Scale(gz.Operator):
    """Multiply digital numbers by a scale factor."""

    backends = ("numpy",)                                           # it computes with NumPy

    def __init__(self, *, scale: float = 1e-4) -> None:
        self.scale = scale                                          # same name as the argument

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out: np.ndarray = np.asarray(gt, dtype=np.float32) * self.scale  # (C, H, W) any → (C, H, W) float32
        # Rewrap like the input and write the output's fill into its nodata pixels.
        return wrap_filled(gt, out, fill_value=carried_fill(gt, out.dtype))


rng: np.random.Generator = np.random.default_rng(0)
dn: np.ndarray = rng.integers(1, 4000, size=(4, 32, 32), dtype=np.uint16)  # (4, 32, 32) uint16
dn[:, :2, :2] = 0                                                         # a few nodata pixels
scene: GeoArray = GeoArray(
    dn, transform=from_origin(750_000, 4_350_000, 10, 10), crs="EPSG:32610",
    fill_value=0, attrs={"band_names": ["B2", "B3", "B4", "B8"]},
)

op: Scale = Scale(scale=1e-4)
reflectance: GeoArray = check_operator(op, scene)                        # (4, 32, 32) uint16 → (4, 32, 32) float32
assert op.get_config() == {"scale": 1e-4}
assert gz.Operator.from_state(op.state).get_config() == op.get_config()

check_operator fails naming the first broken rule. It checks:

Follow the rules

RuleWhy
Keyword-only __init__(self, *, ...), each argument stored under its own nameget_config() is derived from it; configs map to arguments by name.
Hold configuration only, never a carrierA second raster is a positional _apply argument, so a Graph can wire it in.
Implement _apply, never __call____call__ switches between eager runs and graph recording.
Read with np.asarray(gt), rewrap with wrap_likePlain arrays and GeoArrays both work; CRS, transform and attrs carry over.
Declare backends("numpy",) for an _apply that reads with np.asarray; ("numpy", "jax") only when it computes with the carrier’s namespace and runs under jax.jit. pipekit moves the carrier to a backend you list and the result back to JAX, and refuses a trace or a dask carrier you do not list.
Never mutate the inputThe same scene may feed other branches.
Declare the output fillFalse for masks, 0 for labels and counts, NaN for new float quantities, carried_fill(gt, dtype) for carried values.
Use the shared parameter namesred / nir / qa_band for one band, bands, fill_value, window, seed, eps.

The full parameter vocabulary is in packages/geotoolz-ops/AGENTS.md.

Collapse bands and judge nodata

An index reads two bands and returns one value per pixel. Resolve band references by name or position, leave invalid pixels as NaN, and decorate _apply with over_frames so a (T, C, H, W) stack runs frame by frame.

import numpy as np
from geoarray import GeoArray
from rasterio.transform import from_origin

import geoops as gz
from geoops.carrier import mask_invalid_to_nan, over_frames, resolve_band, wrap_like
from geoops.testing import check_operator


class RedEdgeChlorophyll(gz.Operator):
    """CIre = NIR / red edge - 1 (Gitelson 2003); NaN where either band is nodata."""

    backends = ("numpy",)

    def __init__(self, *, nir: int | str = 3, red_edge: int | str = 2, eps: float = 1e-10) -> None:
        self.nir, self.red_edge, self.eps = nir, red_edge, eps

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        x: np.ndarray = mask_invalid_to_nan(gt)                       # (C, H, W) any → (C, H, W) float · NaN = nodata
        nir: np.ndarray = x[resolve_band(gt, self.nir)]               # (H, W) float
        red_edge: np.ndarray = x[resolve_band(gt, self.red_edge)]     # (H, W) float
        return wrap_like(gt, nir / (red_edge + self.eps) - 1, fill_value=np.nan)


rng: np.random.Generator = np.random.default_rng(0)
dn: np.ndarray = rng.integers(1, 4000, size=(4, 32, 32), dtype=np.uint16)  # (4, 32, 32) uint16
dn[:, :2, :2] = 0                                                         # a few nodata pixels
scene: GeoArray = GeoArray(
    dn, transform=from_origin(750_000, 4_350_000, 10, 10), crs="EPSG:32610",
    fill_value=0, attrs={"band_names": ["B2", "B4", "B5", "B8"]},
)

cire: GeoArray = check_operator(RedEdgeChlorophyll(nir="B8", red_edge="B5"), scene)  # (4, 32, 32) uint16 → (32, 32) float · NaN = nodata
assert np.isnan(np.asarray(cire)[:2, :2]).all()

Built-in indices such as gz.NDVI have the same shape. Before writing a step, search the capability index: it may already exist.

Hold a live object

An operator that holds a callable, model or open handle cannot rebuild from JSON. Set forbid_in_yaml = True: its config becomes a debug repr, and from_state refuses to rebuild it.

from collections.abc import Callable

import numpy as np

import geoops as gz
from geoops.carrier import wrap_like


class ApplyFunction(gz.Operator):
    """Apply an elementwise function to every pixel."""

    forbid_in_yaml = True
    backends = ("numpy",)

    def __init__(self, *, fn: Callable[[np.ndarray], np.ndarray]) -> None:
        self.fn = fn

    def _apply(self, gt: np.ndarray) -> np.ndarray:
        return wrap_like(gt, self.fn(np.asarray(gt)))


x: np.ndarray = np.random.default_rng(0).random((3, 8, 8))  # (3, 8, 8) float64
y: np.ndarray = ApplyFunction(fn=np.sqrt)(x)                  # (3, 8, 8) float64 → (3, 8, 8) float64

For a one-off function, pipekit’s gz.Lambda(fn) does the same without a class.

Write a terminal operator

An operator that returns something other than a carrier, such as None after a write, sets _terminal = True. Sequential then accepts it only as the last step.

import tempfile
from pathlib import Path

import numpy as np

import geoops as gz


class SaveNpy(gz.Operator):
    """Write the array to a .npy file; returns None."""

    _terminal = True
    backends = ("numpy",)

    def __init__(self, *, path: str) -> None:
        self.path = path

    def _apply(self, gt: np.ndarray) -> None:
        np.save(self.path, np.asarray(gt))


path: str = str(Path(tempfile.mkdtemp()) / "ndvi.npy")
x: np.ndarray = np.random.default_rng(0).random((4, 8, 8))                  # (4, 8, 8) float64
pipeline: gz.Sequential = gz.NDVI(red=2, nir=3) | SaveNpy(path=path)        # (4, 8, 8) float64 → None
pipeline(x)
saved: np.ndarray = np.load(path)                                          # (8, 8) float64

The built-in writers (gz.WriteGeoTIFF, gz.WriteCOG, gz.WriteZarr) are terminal the same way. To write mid-chain and keep the carrier flowing, use gz.Sink(write_fn), which returns its input.

Learn state with fit and transform

An operator that learns from data never overwrites its constructor attributes in _apply. It follows the fitted-operator contract:

Fitted attributes are not constructor arguments, so they stay out of get_config() with no extra code.

Further reading