You compose library operators into a cloud-masked NDVI pipeline, then add one operator of your own. This is step 3 of the Lake Tahoe story. The find notebook chose the scene, 2024-09-22; the cut notebook chose the 10 km South Shore box used here.
How Sequential and Graph work is explained once in Operator concepts. Here you use them on real pixels.
What you’ll learn:
Chain library operators with
|into aSequential.Mask cloud and shadow with
gz.S2SCLandgz.ApplyMask.Wire a two-branch pipeline as a
Graph.Compute several indices from one input with
gz.Fanout.Write your own operator and check it with
geoops.testing.check_operator.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo: str = "git+https://github.com/jejjohnson/geotoolz@main#subdirectory=packages"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
"pipekit-ops @ git+https://github.com/jejjohnson/pipekit#subdirectory=packages/pipekit-ops",
f"geotoolz @ {repo}/geotoolz",
f"geotoolz-catalog[stac] @ {repo}/geotoolz-catalog",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import planetary_computer
import pystac_client
from rasterio.enums import Resampling
import geocatalog as gc
import geoops as gz
from geoarray import GeoArray
from geoops.carrier import wrap_like
from geoops.testing import check_operatorimport importlib.util
try:
from IPython import get_ipython
ipython = get_ipython()
except ImportError:
ipython = None
if ipython is not None and importlib.util.find_spec("watermark") is not None:
ipython.run_line_magic("load_ext", "watermark")
ipython.run_line_magic(
"watermark",
"-v -m -p numpy,matplotlib,pipekit,geocatalog,geotoolz",
)
else:
print("watermark extension not installed; skipping reproducibility readout.")Python implementation: CPython
Python version : 3.13.16
IPython version : 9.13.0
numpy : 2.4.5
matplotlib: 3.10.9
pipekit : 0.0.2
geocatalog: 0.4.0
geotoolz : 0.9.0
Compiler : GCC 13.3.0
OS : Linux
Release : 6.18.44-fc-v80
Machine : x86_64
Processor : x86_64
CPU cores : 4
Architecture: 64bit
1. Load the South Shore box through the catalog¶
The scene comes from the same catalog search as the other two notebooks. Load green, red and NIR at their native 10 m, plus the 20 m scene classification layer (SCL). SCL holds class labels, so it is upsampled with nearest-neighbour resampling.
client: pystac_client.Client = pystac_client.Client.open(
"https://planetarycomputer.microsoft.com/api/stac/v1",
modifier=planetary_computer.sign_inplace,
)
catalog: gc.GeoCatalog = gc.sources.from_stac_search(
client,
collections=["sentinel-2-l2a"],
bounds=(-120.25, 38.85, -119.85, 39.30), # Lake Tahoe, lon/lat
datetime="2024-09-22",
asset_key="*",
).where("crs == 'EPSG:32610'") # the UTM zone 10 tile covers the box
day: pd.Timestamp = pd.Timestamp("2024-09-22")
south_shore: gc.GeoSlice = gc.GeoSlice(
bounds=(755e3, 4308e3, 765e3, 4318e3), # UTM 10N, m
interval=pd.Interval(day, day + pd.Timedelta(hours=23, minutes=59), closed="both"),
resolution=(10.0, 10.0),
crs="EPSG:32610",
)
def load(asset: str, resampling: Resampling = Resampling.bilinear) -> GeoArray:
"""Read one asset of the scene on the South Shore grid."""
rows: gc.GeoCatalog = catalog.where(f"asset_key == '{asset}'")
return gc.load.load_raster(rows, south_shore, resampling=resampling)
GREEN, RED, NIR, QA = 0, 1, 2, 3 # band positions in the stack below
green: GeoArray = load("B03") # (1, 1000, 1000) uint16
red: GeoArray = load("B04") # (1, 1000, 1000) uint16
nir: GeoArray = load("B08") # (1, 1000, 1000) uint16
scl: GeoArray = load("SCL", Resampling.nearest) # (1, 1000, 1000) uint8, 20 m → 10 m
scene: GeoArray = gz.StackBands()([green, red, nir, scl]) # (4, 1000, 1000) uint16
print(f"scene: {scene.shape} {scene.dtype}, crs={scene.crs}")scene: (4, 1000, 1000) uint16, crs=EPSG:32610
2. Chain operators with Sequential¶
a | b builds a Sequential that runs a, then b. Keep the three reflectance bands, decode the stored values (reflectance × 10 000) with gz.DNToReflectance, then compute gz.NDVI.
keep: gz.SelectBands = gz.SelectBands(bands=[GREEN, RED, NIR])
reflectance: gz.Sequential = keep | gz.DNToReflectance(scale=1e-4)
ndvi_pipe: gz.Sequential = reflectance | gz.NDVI(red=RED, nir=NIR)
ndvi: GeoArray = ndvi_pipe(scene) # (4, 1000, 1000) uint16 → (1000, 1000) float64
print(ndvi_pipe)
print(
f"ndvi: {ndvi.shape} {ndvi.dtype}, range [{np.nanmin(ndvi):.2f}, {np.nanmax(ndvi):.2f}]"
)Sequential([SelectBands(bands=[0, 1, 2], axis=-3), DNToReflectance(scale=0.0001, offset=0.0, axis=-3), NDVI(red=1, nir=2, axis=-3, eps=1e-10)])
ndvi: (1000, 1000) float64, range [-0.27, 0.72]
3. Build a cloud mask from SCL¶
gz.S2SCL returns a boolean mask where True means drop the pixel, the polarity every geotoolz mask uses (see Mask polarity). By default it drops every class except vegetation, bare soil and water.
scl_mask: gz.S2SCL = gz.S2SCL(qa_band=QA)
drop: GeoArray = scl_mask(scene) # (4, 1000, 1000) uint16 → (1000, 1000) bool
classes, counts = np.unique(np.asarray(scene)[QA], return_counts=True)
for value, count in zip(classes, counts, strict=True):
print(f"{gz.SCL(int(value)).name:<15} {count / counts.sum():6.1%}")
print(f"dropped: {np.asarray(drop).mean():.1%} of pixels")DARK_AREA_PIXELS 0.9%
VEGETATION 48.0%
NOT_VEGETATED 16.2%
WATER 33.2%
UNCLASSIFIED 1.7%
dropped: 2.6% of pixels
This late-September scene is nearly cloud-free, so the mask mostly drops dark (shaded) and unclassified pixels. No NO_DATA class appears, so the tile covers the whole box.
4. Wire both branches as a Graph¶
NDVI and the mask both start from the same scene and meet in gz.ApplyMask. A linear Sequential cannot express that, so call the operators on a symbolic gz.Input and wrap the result in a gz.Graph.
scene_in: gz.Input = gz.Input("scene")
ndvi_node: gz.Node = ndvi_pipe(scene_in)
drop_node: gz.Node = scl_mask(scene_in)
clean_node: gz.Node = gz.ApplyMask()(ndvi_node, drop_node) # dropped pixels become NaN
graph: gz.Graph = gz.Graph(
inputs={"scene": scene_in},
outputs={"ndvi": ndvi_node, "drop": drop_node, "clean": clean_node},
)
out: dict[str, GeoArray] = graph(scene=scene)
print({name: (value.shape, str(value.dtype)) for name, value in out.items()}){'ndvi': ((1000, 1000), 'float64'), 'drop': ((1000, 1000), 'bool'), 'clean': ((1000, 1000), 'float64')}
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
axes[0].imshow(np.asarray(out["ndvi"]), cmap="RdYlGn", vmin=-0.2, vmax=0.8)
axes[0].set_title("NDVI")
axes[1].imshow(np.asarray(out["drop"]), cmap="Greys")
axes[1].set_title("SCL mask (black = drop)")
im = axes[2].imshow(np.asarray(out["clean"]), cmap="RdYlGn", vmin=-0.2, vmax=0.8)
axes[2].set_title("Masked NDVI")
fig.colorbar(im, ax=axes[2], label="NDVI")
for ax in axes:
ax.set_xticks([])
ax.set_yticks([])
plt.show()
5. Several indices from one input with Fanout¶
gz.Fanout runs each named operator on the same input and returns a dict. Here it adds the McFeeters water index, gz.NDWI, which uses the green band. Water has NDWI above 0, so NDWI > 0 should agree with SCL’s own WATER class.
ndvi_op: gz.NDVI = gz.NDVI(red=RED, nir=NIR)
ndwi_op: gz.NDWI = gz.NDWI(green=GREEN, nir=NIR)
indices: gz.Fanout = gz.Fanout({"ndvi": ndvi_op, "ndwi": ndwi_op})
fan: gz.Sequential = reflectance | indices
products: dict[str, GeoArray] = fan(scene) # {name: (1000, 1000) float64}
ndwi_water: np.ndarray = np.asarray(products["ndwi"]) > 0 # (1000, 1000) bool
scl_water: np.ndarray = np.asarray(scene)[QA] == gz.SCL.WATER # (1000, 1000) bool
agree: float = (ndwi_water == scl_water).mean()
print(
f"water: NDWI {ndwi_water.mean():.1%}, SCL {scl_water.mean():.1%}; agree {agree:.1%}"
)
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, title, img in zip(
axes, ("NDWI > 0", "SCL class WATER"), (ndwi_water, scl_water), strict=True
):
ax.imshow(img, cmap="Blues", interpolation="nearest")
ax.set_title(title)
ax.set_xticks([])
ax.set_yticks([])
plt.show()water: NDWI 33.1%, SCL 33.2%; agree 98.9%

6. Write your own operator¶
The library has no NDVI land-cover classifier, so write one. Subclass gz.Operator, take keyword-only configuration, and put the work in _apply; never override __call__. Rewrap the result with geoops.carrier.wrap_like, which keeps the georeferencing and sets the new fill.
The full walkthrough is Define an operator.
class NDVIClasses(gz.Operator):
"""Label NDVI as water (1), sparse cover (2) or vegetation (3); 0 = no data.
Args:
water_below: NDVI under this value is water.
vegetation_above: NDVI at or above this value is vegetation.
"""
backends = ("numpy",) # it computes with NumPy
def __init__(self, *, water_below: float = 0.02, vegetation_above: float = 0.25):
self.water_below = water_below
self.vegetation_above = vegetation_above
def _apply(self, ndvi: GeoArray) -> GeoArray:
values: np.ndarray = np.asarray(ndvi) # (..., H, W) float
edges: list[float] = [self.water_below, self.vegetation_above]
labels: np.ndarray = np.digitize(values, edges) + 1 # (..., H, W) int64
labels[~np.isfinite(values)] = 0 # nodata stays nodata
return wrap_like(ndvi, labels.astype(np.uint8), fill_value=0)Clear lake water sits near NDVI 0 in this scene, so water_below=0.02 separates it from bare granite.
check_operator runs the library’s own contract checks on your operator. They cover config round-trip, graph mode, fresh attrs, dtype-matched fills and (T, C, H, W) stacks. It raises on the first failure.
classify: NDVIClasses = NDVIClasses(water_below=0.02, vegetation_above=0.25)
_ = check_operator(classify, out["clean"])
print(f"contract OK; config = {classify.get_config()}")
clean: GeoArray = out["clean"] # (1000, 1000) float64 · NaN = dropped
labels: GeoArray = classify(clean) # (1000, 1000) float64 → (1000, 1000) uint8
names: dict[int, str] = {0: "no data", 1: "water", 2: "sparse", 3: "vegetation"}
values, counts = np.unique(np.asarray(labels), return_counts=True)
print(
{
names[int(v)]: f"{c / counts.sum():.1%}"
for v, c in zip(values, counts, strict=True)
}
)
fig, ax = plt.subplots(figsize=(12, 5))
im = ax.imshow(
np.asarray(labels), cmap="viridis", vmin=0, vmax=3, interpolation="nearest"
)
cbar = fig.colorbar(im, ax=ax, ticks=list(names))
cbar.ax.set_yticklabels(list(names.values()))
ax.set_title("NDVIClasses on the masked NDVI")
ax.set_xticks([])
ax.set_yticks([])
plt.show()contract OK; config = {'water_below': 0.02, 'vegetation_above': 0.25}
{'no data': '2.7%', 'water': '33.5%', 'sparse': '15.3%', 'vegetation': '48.5%'}

Summary¶
|chainedSelectBands,DNToReflectanceandNDVIinto oneSequential.S2SCLbuilt a drop mask (True= drop) andApplyMaskwrote NaN into it.A
Graphjoined the NDVI and mask branches;Fanoutadded NDWI from the same input.NDVIClasseskept the operator contract, andcheck_operatorproved it.
Next: run this pipeline tile by tile over the whole lake with the patcher, as in the cut notebook. For runtime branching, see Branching pipelines.