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.

Concepts

Every step in a geotoolz pipeline is an Operator, and every pipeline is an operator built from smaller ones. This page explains that model and the rules every operator keeps. The how-tos put it to work: define an operator and branching pipelines.

The Operator

An Operator is a callable with a keyword-only constructor and an _apply method. The base class comes from pipekit, which knows nothing about rasters; geotoolz operators narrow it to GeoArray and ndarray.

The base class gives youWhat it does
__call__On a value, runs _apply now. On an Input or Node, records a graph node instead.
a | bBuilds a Sequential.
get_config()JSON of the constructor arguments, derived from __init__. Drives __repr__, op.state and YAML round-trips.
Operator.from_state(op.state)Rebuilds an equal operator from that JSON.

Two class flags change how an operator composes:

Writing your own, with the full set of rules and a contract test, is Define an operator.

Sequential and Graph

A Sequential chain and a Graph with a cloud-mask branch, with the output shape and dtype of every step

Both are operators, so a Graph can sit inside a Sequential and the other way round. The landing-page quickstart builds the pipeline in the picture.

Execution is eager: calling an operator on a value runs it. The only deferred step is graph recording, and the finished Graph runs eagerly too. For chunked, lazy arrays, put a dask.array inside the carrier.

Choose a composition shape

You want…UseDecided
a single chain of stepsSequential or a | bwhen you write it
named intermediates, branches, fan-in, several outputsGraphwhen you write it
one input, many named outputsFanoutwhen you write it
a two-way fork on the whole carrierBranch(predicate, if_true, if_false)at run time
N-way dispatch keyed off an attribute (sensor, level)Switch(key, cases, default)at run time
a side effect that keeps the carrier flowingSinkat run time

Branch and Switch look at the whole carrier, not at pixels. For per-pixel choices use a mask and ApplyMask. Worked examples of each shape are in Branching pipelines.

Observers and building blocks

Observers return their input unchanged, so they drop into any chain.

OperatorWhat it does
Tap(fn)Calls fn(x) and passes x on.
Snapshot()A controller: snap.at("key") is a step that stores x in snap.captures["key"].
ShapeTrace()Prints shape and dtype at each step; mode="diff_only" skips repeats.
Identity()A no-op, for any slot that needs an operator.
Const(value)Returns value whatever the input.
Lambda(fn)Wraps a plain function as an operator.
import numpy as np

import geoops as gz

rng: np.random.Generator = np.random.default_rng(0)
dn: np.ndarray = rng.integers(200, 4000, size=(4, 32, 32), dtype=np.uint16)  # (4, 32, 32) uint16

shapes: list[tuple[int, ...]] = []
snap: gz.Snapshot = gz.Snapshot()
pipeline: gz.Sequential = (
    gz.DNToReflectance(scale=1e-4)                     # (4, 32, 32) uint16 → (4, 32, 32) float64
    | gz.Tap(lambda x: shapes.append(x.shape))
    | snap.at("reflectance")
    | gz.NDVI(red=2, nir=3)                            # (4, 32, 32) float64 → (32, 32) float64
)
ndvi: np.ndarray = pipeline(dn)                        # (4, 32, 32) uint16 → (32, 32) float64
reflectance: np.ndarray = snap.captures["reflectance"]  # (4, 32, 32) float64
assert shapes == [(4, 32, 32)]

The plain array in gives a plain array out. pipekit also ships Profile, Histogram, Cache, Retry, Try and the Assert* checks; see the pipekit docs.

Multi-input operators

An operator that combines several carriers takes every carrier as a positional _apply argument. Constructor arguments hold only configuration, which is what lets a Graph wire carriers in.

KindCallIn a Graph
Two carriersIMEEstimate(wind_speed=3.5)(kg_m2, plume_mask)IMEEstimate(wind_speed=3.5)(Input("enh"), Input("mask"))
Optional second carrierSBMP()(scene, reference_scene) or SBMP()(scene)SBMP()(Input("scene"), Input("ref"))
N-ary reducerCombineMasks()(m1, m2) or CombineMasks()([m1, m2])CombineMasks()(Input("a"), Input("b"))

Georeferencing checks

Every family uses the helpers in geoops.carrier, so the errors read the same everywhere.

Band names

Every operator that takes a band reference resolves it with geoops.carrier.resolve_band, so "B4" means the same band in every family.

Mask polarity

Every masking mask uses one polarity: True = drop the pixel. Producers (qa, mask, restore.OutlierMask) and consumers (ApplyMask, CombineMasks) agree on it (decision record #154).

Fitted operators

Some operators learn state from data: the normalize scalers, matched_filter.MatchedFilter, restore.MNF and learn.SklearnOp. They share one contract (decision record #143) and satisfy pipekit_ops.protocols.FittableTransformer.

MethodDoes
fit(x) -> selfLearns state into trailing-underscore attributes (mean_, std_, cov_op_).
transform(x)Applies the state. Never fits or mutates; raises ValueError when unfitted.
inverse(x)Undoes transform where that makes sense (the scalers, MNF).
op(x)Calls transform, fitting first when configured to learn on call.
import numpy as np

import geoops as gz

rng: np.random.Generator = np.random.default_rng(0)
train: np.ndarray = rng.normal(0.2, 0.05, size=(4, 32, 32))  # (4, 32, 32) float64
scene: np.ndarray = rng.normal(0.2, 0.05, size=(4, 32, 32))  # (4, 32, 32) float64

scaler: gz.StandardScaler = gz.normalize.StandardScaler().fit(train)
normed: np.ndarray = scaler(scene)                            # (4, 32, 32) float64 → (4, 32, 32) float64
restored: np.ndarray = scaler.inverse(normed)                 # (4, 32, 32) float64 → (4, 32, 32) float64

mnf: gz.MNF = gz.restore.MNF(n_components=2).fit(scene)
denoised: np.ndarray = mnf.inverse(mnf(scene))                # (4, 32, 32) → (2, 32, 32) → (4, 32, 32) float64

Coupling: which dims an operator mixes

An operator couples a dim when some output depends on two or more input values that differ along it: a filter mixes neighbouring pixels, a band ratio mixes bands, a composite mixes dates. Re-indexing alone (selecting or reordering bands, cropping) moves values without mixing them, so it is an effect on the dim, not a coupling. The set of coupled dims is the operator’s coupling class:

Coupled dimsClassExamples
nonepointwiseDNToReflectance, ApplyMask
bandspectralNDVI, BandMath, ApplySRF
space (y and x)spatialGaussianDenoise, Reproject, PercentileClip
timetemporalMedianComposite
level, spacevolumetricGradient3D
band, spacespatio-spectralSLIC
The nine coupling classes as a lattice over band, space and time, with the number of geoops operators in each, examples with their reach, and what each class means when a scene is tiled or split in time

An operator class declares it as coupling, a geoops.carrier.Coupling, beside backends. With the coupled dims come what the operator does to each one (select, reduce, regrid, …), the spatial reach in pixels (None for an operator that reads the whole scene) and the dims a fit reads beyond them.

from geoops.carrier import Coupling

# NDVI = (ρ_NIR − ρ_red) / (ρ_NIR + ρ_red): two bands at one pixel → one band
ndvi: Coupling = Coupling(couples={"band"}, effects={"band": "reduce"})
# per-band percentiles over the whole scene, then a pointwise stretch
clip: Coupling = Coupling(couples={"space"}, reach=None)
# x′ = (x − μ_c) / σ_c, with μ_c and σ_c fitted over every pixel
scaler: Coupling = Coupling(fit={"space"})

The reach is what tiling needs: a tile reproduces the whole-scene result in its interior only when it overlaps its neighbours by at least the reach. An operator with reach=None gives a different answer per tile, whatever the overlap.

geoops.testing.measure_coupling(build, scene) measures the coupling by perturbing one pixel, a far block and one frame of a stack, and geoops.testing.assert_coupling(op, measured) checks that the declaration contains what was measured. The measurement is a lower bound: a topology statistic such as a connected-components label can ignore one changed pixel.

Where geotoolz fits

The geostack: geocatalog finds, geoproducts reads, geopatcher cuts, geoops computes, geopatcher stitches

geotoolz is the compute stage. It sees only GeoArrays, so it does not care which catalog or reader produced them. The seams are on How the packages interlock; the patcher bridge is Tile → operate → stitch.

Further reading