You turn a Sentinel-2 search into an NDVI map of Lake Tahoe in about thirty lines. This notebook owns step 1 of a three-part story, find, and runs the other two steps briefly. The patcher notebook goes deeper on cut, the operators notebook on compute.
| Setting | Value |
|---|---|
| AOI | Lake Tahoe, lon/lat (-120.25, 38.85, -119.85, 39.30) |
| Season | 2024-06-01 to 2024-09-30 |
| Archive | Sentinel-2 L2A on the Microsoft Planetary Computer |
| Bands | red B04 and near-infrared B08 |
What you’ll learn:
Turn a STAC search into a queryable catalog with
gc.sources.from_stac_search.Filter it by space, time and cloud cover with
queryandwhere.Pick the clearest date that covers the whole AOI.
Stage the files and build a patcher field with
gc.patch.field_for.Tile, compute NDVI and stitch with
geoops.patch_ops.
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-cloud @ {repo}/geotoolz-cloud",
f"geotoolz-patcher @ {repo}/geotoolz-patcher",
f"geotoolz @ {repo}/geotoolz",
f"geotoolz-catalog[stac,patch,cloud] @ {repo}/geotoolz-catalog",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import datetime as dt
import tempfile
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import planetary_computer
import pystac_client
import shapely
import geocatalog as gc
import geoops as gz
import geopatcher as gp
from geoarray import GeoArray
from geoops.patch_ops import ApplyToChips, GridSampler, MergePatchesimport 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,pystac_client,geocatalog,geopatcher,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
pystac_client: 0.9.0
geocatalog : 0.5.0
geopatcher : 0.10.0
geotoolz : 0.10.0
Compiler : GCC 13.3.0
OS : Linux
Release : 6.18.44-fc-v114
Machine : x86_64
Processor : x86_64
CPU cores : 4
Architecture: 64bit
1. Discover — a STAC search becomes a catalog¶
gc.sources.from_stac_search runs the search and returns one catalog row per (item, asset). asset_key="*" keeps every asset, so later steps can pick bands. extra_properties copies eo:cloud_cover into a column you can filter on.
BBOX: tuple[float, float, float, float] = (-120.25, 38.85, -119.85, 39.30) # lon/lat
SEASON: str = "2024-06-01/2024-09-30"
client: pystac_client.Client = pystac_client.Client.open(
"https://planetarycomputer.microsoft.com/api/stac/v1",
modifier=planetary_computer.sign_inplace, # signed hrefs, so rasterio can read them
)
catalog: gc.GeoCatalog = gc.sources.from_stac_search(
client,
collections=["sentinel-2-l2a"],
bounds=BBOX,
datetime=SEASON,
asset_key="*",
extra_properties=("eo:cloud_cover",),
)
print(f"{len(catalog)} (item, asset) rows")
print(f"temporal extent: {catalog.temporal_extent}")
catalog.gdf[["asset_key", "stac_item_id", "crs", "eo:cloud_cover"]].head()2181 (item, asset) rows
temporal extent: [2024-06-02 18:49:21.024000, 2024-09-30 18:52:11.024000]
2. Filter — space, time, cloud cover and bands¶
A GeoSlice is the request every catalog answers: bounds, time interval, resolution and CRS. query filters by space and time; where filters on any other column with a pandas query string. See Catalog concepts for the GeoSlice contract.
aoi: gc.GeoSlice = gc.GeoSlice(
bounds=BBOX,
interval=pd.Interval(
pd.Timestamp("2024-06-01"), pd.Timestamp("2024-09-30"), closed="both"
),
resolution=(3e-4, 3e-4), # ≈ 30 m, a 3× decimation of the native 10 m grid
crs="EPSG:4326",
)
hits: gc.GeoCatalog = catalog.query(aoi).where(
"`eo:cloud_cover` < 20 and asset_key in ['B04', 'B08']"
)
print(f"{len(hits)} rows: red + NIR, under 20 % cloud")162 rows: red + NIR, under 20 % cloud
3. Choose — the clearest date that covers the whole AOI¶
Lake Tahoe sits where UTM zones 10 and 11 meet, so each date brings two or more tiles. The lowest-cloud tile is not enough: some tiles are mostly no-data, and a 0 % cloud cover over no pixels is useless.
Each footprint traces a tile’s valid data. Group the rows by date, keep the dates whose footprints cover the AOI, and take the clearest.
aoi_box: shapely.Polygon = shapely.box(*BBOX)
table: pd.DataFrame = hits.gdf.assign(date=hits.gdf.index.left.date)
lowest: pd.Series = table.sort_values("eo:cloud_cover").iloc[0]
share: float = lowest.geometry.intersection(aoi_box).area / aoi_box.area
print(f"lowest-cloud tile {lowest['stac_item_id']} covers {share:.1%} of the AOI")
per_day: pd.DataFrame = table.groupby("date").agg(
cloud_cover=("eo:cloud_cover", "max"),
coverage=(
"geometry",
lambda g: shapely.union_all(g.values).intersection(aoi_box).area / aoi_box.area,
),
tiles=("stac_item_id", "nunique"),
)
full: pd.DataFrame = per_day[per_day["coverage"] > 0.999]
best_day: dt.date = full["cloud_cover"].idxmin()
print(f"{len(full)} of {len(per_day)} dates cover the AOI; clearest: {best_day}")
full.sort_values("cloud_cover").head()lowest-cloud tile S2B_MSIL2A_20240806T184919_R113_T11SKD_20240806T235408 covers 0.0% of the AOI
40 of 40 dates cover the AOI; clearest: 2024-09-22
fig, ax = plt.subplots(figsize=(12, 5))
ax.scatter(full.index, full["cloud_cover"], c="C0", label="date covering the AOI")
ax.axvline(best_day, color="k", linestyle="--", label=f"chosen: {best_day}")
ax.set_ylabel("max eo:cloud_cover (%)")
ax.set_title("Sentinel-2 L2A over Lake Tahoe, summer 2024")
ax.legend()
plt.show()
4. Stage and load — local files, then a patcher field¶
gc.staging.stage downloads each row’s file once into a local cache and returns a catalog that points at the copies. gc.patch.field_for mosaics them onto the slice grid as one geoarray.GeoArray and wraps it as a gp.RasterField. Both tiles are reprojected onto the slice’s lon/lat grid on the way in.
start: pd.Timestamp = pd.Timestamp(best_day)
end: pd.Timestamp = start + pd.Timedelta(hours=23, minutes=59)
day: gc.GeoSlice = gc.GeoSlice(
bounds=BBOX,
interval=pd.Interval(start, end, closed="both"),
resolution=aoi.resolution,
crs=aoi.crs,
)
cache: Path = Path(tempfile.gettempdir()) / "geotoolz-tahoe" # reused across runs
rows: gc.GeoCatalog = hits.query(day)
red_rows: gc.GeoCatalog = gc.staging.stage(rows.where("asset_key == 'B04'"), dest=cache)
nir_rows: gc.GeoCatalog = gc.staging.stage(rows.where("asset_key == 'B08'"), dest=cache)
red: gp.RasterField = gc.patch.field_for(red_rows, day) # (1, 1500, 1333) uint16
nir: gp.RasterField = gc.patch.field_for(nir_rows, day) # (1, 1500, 1333) uint16
scene: GeoArray = gz.StackBands()([red.reader, nir.reader]) # (2, 1500, 1333) uint16
print(f"scene: {scene.shape} {scene.dtype}, crs={scene.crs}, fill={scene.fill_value}")scene: (2, 1500, 1333) uint16, crs=EPSG:4326, fill=0.0
5. Cut and compute — NDVI tile by tile¶
Three patch_ops operators put the patcher inside a Sequential: split the field, run an operator on every chip, stitch the chips back. The chip operator is gz.DNToReflectance (Sentinel-2 L2A stores reflectance × 10 000) followed by gz.NDVI. The cut and compute notebooks explain each half.
patcher: gp.SpatialPatcher = gp.SpatialPatcher(
geometry=gp.spatial.geometry.Rectangular(size=(256, 256), boundary="pad"),
sampler=gp.spatial.sampler.RegularStride(step=(192, 192)), # 64 px overlap
window=gp.spatial.window.Hann(),
aggregation=gp.spatial.aggregation.OverlapAdd(),
)
ndvi_op: gz.Sequential = gz.DNToReflectance(scale=1e-4) | gz.NDVI(red=0, nir=1)
field: gp.RasterField = gp.RasterField(scene)
tiled: gz.Sequential = gz.Sequential(
[
GridSampler(patcher=patcher), # field → list[Patch]
ApplyToChips(operator=ndvi_op), # (2, 256, 256) uint16 → (256, 256) float64
MergePatches(aggregation=patcher.aggregation, domain=field.domain),
]
)
ndvi: GeoArray = tiled(field) # (2, 1500, 1333) uint16 → (1500, 1333) float64
print(f"{patcher.n_anchors(field)} chips → ndvi {ndvi.shape} {ndvi.dtype}")
print(f"NDVI range: [{np.nanmin(ndvi):.2f}, {np.nanmax(ndvi):.2f}]")56 chips → ndvi (1500, 1333) float64
NDVI range: [-0.23, 0.71]
NDVI is a per-pixel index, so the tiled result matches NDVI of the whole scene, edges included: the Hann window never reaches zero, so every pixel a chip covers keeps its value (see Window convention).
whole: GeoArray = ndvi_op(scene) # (2, 1500, 1333) uint16 → (1500, 1333) float64
tiled_px: np.ndarray = np.asarray(ndvi) # (1500, 1333) float64
whole_px: np.ndarray = np.asarray(whole) # (1500, 1333) float64
print(f"max |tiled − whole|: {np.nanmax(np.abs(tiled_px - whole_px)):.1e}")max |tiled − whole|: 2.2e-16
extent: tuple[float, float, float, float] = (BBOX[0], BBOX[2], BBOX[1], BBOX[3])
fig, (ax_red, ax_ndvi) = plt.subplots(1, 2, figsize=(12, 5))
ax_red.imshow(np.asarray(scene)[0], cmap="Greys_r", vmin=0, vmax=3000, extent=extent)
ax_red.set_title(f"Red (B04) DN, {best_day}")
im = ax_ndvi.imshow(np.asarray(ndvi), cmap="RdYlGn", vmin=-0.2, vmax=0.8, extent=extent)
ax_ndvi.set_title("NDVI, tiled and stitched")
fig.colorbar(im, ax=ax_ndvi, label="NDVI")
for ax in (ax_red, ax_ndvi):
ax.set_xlabel("lon")
ax.set_ylabel("lat")
plt.show()
Forest around the lake reads green, the lake and bare granite read red. Fallen Leaf Lake is the small water body south-west of the lake.
Summary¶
from_stac_searchturned a STAC search into a catalog you canqueryand filter withwhere.Footprints and cloud cover picked one clear date that covers the whole AOI.
stageandfield_forturned that date’s rows into aRasterFieldon your grid.GridSampler → ApplyToChips → MergePatchescomputed NDVI tile by tile.
Next: cut the same scene into patches and see why the window matters, or compute a cloud-masked NDVI with a Graph. To keep the catalog between sessions, write it with gc.storage.to_geoparquet; see From STAC.