Earth Observation Data and Tools for Climate Resilience and Risk Monitoring¶
with medium-resolution EO examples for Africa and Asia¶
This notebook is focused on:
- medium-resolution Earth Observation (EO) datasets such as Sentinel-3, MODIS, and a few complementary products;
- practical access patterns using STAC API, Microsoft Planetary Computer (MPC), Google Earth Engine (GEE), Xee, and cubo;
- simple climate resilience and risk-monitoring examples for Africa and Asia.
This notebook is built as a practice notebook. Some cells may require authentication or internet access and are meant for live demonstration only.
Learning objectives¶
By the end of the session, participants should be able to:
- explain why medium-resolution EO is useful for continental and regional monitoring;
- discover datasets with a STAC API;
- read EO data from Microsoft Planetary Computer;
- access Earth Engine collections in Python with GEE and Xee;
- use cubo as a higher-level data-cube interface for both STAC and GEE;
- build basic resilience indicators such as:
- NDVI time series,
- simple anomalies,
- rainfall + vegetation context,
- coastal water/land color quicklooks.
Why medium-resolution EO?¶
Medium-resolution EO is often a strong fit for climate resilience because it balances:
- spatial detail sufficient for regional landscapes, coastlines, croplands, and large water bodies;
- temporal frequency suitable for anomaly detection and seasonal monitoring;
- manageable data volume for teaching and prototyping.
Typical use cases¶
- drought and vegetation stress,
- flood extent context,
- water quality and coastal monitoring,
- land surface conditions,
- seasonal food-security and livelihood monitoring.
Datasets used in this tutorial¶
Core datasets¶
- MODIS MOD13Q1 / MYD13Q1: 16-day vegetation indices at 250 m
- Sentinel-3 OLCI: ocean and land color radiances at 300 m
- optional complementary context:
- CHIRPS rainfall,
- MODIS LST,
- Sentinel-3 SLSTR where relevant
Study areas¶
- Africa: Somali Region of Ethiopia / East Africa vegetation monitoring Event Reference
- Asia: Ganges-Brahmaputra delta coastal-water example
You can replace these AOIs with your own polygons later.
#!python -m pip install -q cubo xarray dask[complete] pystac-client planetary-computer xee earthengine-api geemap matplotlib pandas numpy shapely geopandas contextily
#!python -m pip install -q odc-stac stackstac rioxarray
# !python -m pip freeze > requirements.txt
Create a venv and install the dependencies¶
# !python -m venv .venv
# !source .venv/bin/activate
# !pip install -r requirements.txt
# !python -m pip install -r requirements.txt ## incase you have problems with the above command, try this one instead. It will install the packages in the requirements.txt file into your current Python environment.
Imports¶
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import geopandas as gpd
import contextily as cx
from shapely.geometry import box, mapping
# STAC / MPC
from pystac_client import Client
import planetary_computer as pc
# GEE / Xee
import ee
import xee
# Cubo
import cubo
Authentication notes¶
Earth Engine¶
For local Jupyter:
ee.Authenticate()
ee.Initialize(project="YOUR_GEE_PROJECT")
For high-volume endpoint when appropriate:
ee.Initialize(project="YOUR_GEE_PROJECT",
opt_url="https://earthengine-highvolume.googleapis.com")
Microsoft Planetary Computer¶
The STAC API is public for metadata search. Asset access often requires signing with planetary_computer.sign_inplace(...) or a modifier function in pystac-client.
# Uncomment when running locally for the first time:
ee.Authenticate()
# Example initialization:
ee.Initialize(project="ee-kizarzakir")
# ee.Initialize(project="YOUR_GEE_PROJECT")
# Or high-volume endpoint:
# ee.Initialize(
# project="YOUR_GEE_PROJECT",
# opt_url="https://earthengine-highvolume.googleapis.com"
# )
Helper variables: Africa and Asia AOIs¶
# Africa example:
africa_bbox = [43.503799,5.721212,43.839569,5.952095] # minx, miny, maxx, maxy
# Asia example: Ganges-Brahmaputra delta / coastal Bangladesh (broad bbox)
asia_bbox = [88.231201,21.399377,89.288635,22.629223]
africa_geom = mapping(box(*africa_bbox))
asia_geom = mapping(box(*asia_bbox))
print("Africa bbox:", africa_bbox)
print("Asia bbox:", asia_bbox)
# Visualize Asia bbox using GeoPandas + simple basemap
bbox_gdf = gpd.GeoDataFrame(
{"name": ["Asia AOI"]},
geometry=[box(*asia_bbox)],
crs="EPSG:4326",
)
bbox_3857 = bbox_gdf.to_crs(epsg=3857)
ax = bbox_3857.boundary.plot(figsize=(8, 8), color="red", linewidth=2)
cx.add_basemap(ax, source=cx.providers.CartoDB.Positron)
ax.set_title("Asia AOI Bounding Box")
ax.set_axis_off()
plt.show()
bbox_gdf = gpd.GeoDataFrame(
{"name": ["Africa AOI"]},
geometry=[box(*africa_bbox)],
crs="EPSG:4326",
)
bbox_3857 = bbox_gdf.to_crs(epsg=3857)
ax = bbox_3857.boundary.plot(figsize=(8, 8), color="red", linewidth=2)
cx.add_basemap(ax, source=cx.providers.CartoDB.Positron)
ax.set_title("Africa AOI Bounding Box")
ax.set_axis_off()
plt.show()
Part 1 — Discover data with STAC API and MPC¶
This section shows the lowest-friction pattern:
- open a STAC API,
- search a collection by space and time,
- inspect returned items,
- optionally pass those results into higher-level tooling later.
# Microsoft Planetary Computer STAC
stac_url = "https://planetarycomputer.microsoft.com/api/stac/v1"
catalog = Client.open(
stac_url,
modifier=pc.sign_inplace, # automatically sign returned items/assets
)
# why modifier=pc.sign_inplace?
# Because many of the items/assets in the Planetary Computer catalog require authentication to access, and this modifier will automatically sign the returned items/assets with the necessary credentials for access.
print(catalog)
# STAC hierarchy: Catalog -> Collection -> Item -> Asset
print("STAC concepts:")
print("1) Catalog : the top-level entry point (API root) that lists datasets.")
print("2) Collection: a dataset/group with shared metadata (e.g., MODIS NDVI).")
print("3) Item : one spatiotemporal record in a collection (scene/time granule).")
print("4) Asset : actual files/links inside an item (bands, metadata, thumbnails, etc.).")
print("\nCurrent catalog:")
print(f"- id: {catalog.id}")
print(f"- title: {getattr(catalog, 'title', None)}")
# Use a known collection from this notebook
collection_id = "modis-13Q1-061"
col = catalog.get_collection(collection_id)
print("\nExample collection:")
print(f"- id: {col.id}")
print(f"- title: {col.title}")
print(f"- description (first 160 chars): {str(col.description)[:160]}...")
# Fetch one example item
search = catalog.search(
collections=[collection_id],
bbox=africa_bbox,
datetime="2021-01-01/2021-12-31",
limit=1,
)
items = list(search.items())
if items:
item = items[0]
print("\nExample item:")
print(f"- id: {item.id}")
print(f"- datetime: {item.datetime}")
print(f"- collection: {item.collection_id}")
print(f"- bbox: {item.bbox}")
asset_keys = list(item.assets.keys())
print(f"\nItem has {len(asset_keys)} assets. First 8 keys: {asset_keys[:8]}")
# Show one asset in detail
k = asset_keys[0]
a = item.assets[k]
print("\nExample asset:")
print(f"- key: {k}")
print(f"- href: {a.href}")
print(f"- media_type: {a.media_type}")
print(f"- roles: {a.roles}")
else:
print("\nNo items found for the example query.")
# list of collections available in the catalog
print ("Collections available in the catalog:")
for collection in catalog.get_collections():
print("-", collection.id)
# collection tree
modis_collection = catalog.get_collection("modis-13Q1-061") # from the list of collections in the catalog - we are taking the MODIS NDVI collection as an example
modis_collection
Example 1A: Search MODIS NDVI for Africa¶
search_modis_africa = catalog.search(
collections=["modis-13Q1-061"],
bbox=africa_bbox,
datetime="2021-03-01/2022-05-31",
limit=5,
)
items_modis_africa = list(search_modis_africa.items())
print(f"Returned {len(items_modis_africa)} items")
print("Top 3 items:")
for item in items_modis_africa[:3]:
print(item.id, item.datetime)
Important Note¶
- STAC separates collection metadata from items/assets.
- A STAC search is often the most transferable pattern across cloud EO catalogs.
- MPC is a good demonstration platform because it exposes many datasets through a standard STAC API.
Example 1B: Search Sentinel-3 for Asia¶
#Sentinel-3 OLCI
search_s3_asia = catalog.search(
collections=["sentinel-3-olci-lfr-l2-netcdf"],
bbox=asia_bbox,
datetime="2023-01-01/2023-03-31",
limit=5,
)
items_s3_asia = list(search_s3_asia.items())
print(f"Returned {len(items_s3_asia)} items")
print("Top 3 items:")
for item in items_s3_asia[:3]:
print(item.id, item.datetime)
# check the assets of the first item
if items_s3_asia:
item = items_s3_asia[0]
print(f"\nAssets for item {item.id}:")
for key, asset in item.assets.items():
print(f"- {key}: {asset.href} (media_type: {asset.media_type})")
else:
print("\nNo items found for Sentinel-3 OLCI search.")
Optional: Inspect asset names from a returned STAC item¶
if items_modis_africa:
first_item = items_modis_africa[0]
print("Item ID:", first_item.id)
print("Assets:")
for k in first_item.assets:
print(" -", k)
Part 2 — Use cubo as a simpler data-cube interface¶
cubo is handy because it gives a compact, xarray-friendly entry point and supports STAC and GEE workflows.
Example 2A: cubo with STAC-like workflow (Africa)¶
This is a compact pattern for building an on-demand EO mini-cube around a point.
- the cube small,
- the time range short,
- the number of bands minimal.
# A point near Somali Region of Ethiopia
lat_africa = 5.947659
lon_africa = 43.559889
start_date = "2021-05-01"
end_date = "2022-05-31"
# a simple cube demonstration
da_africa_cubo = cubo.create(
lat=lat_africa,
lon=lon_africa,
collection="modis-13Q1-061",
bands=["250m_16_days_NDVI"],
start_date=start_date,
end_date=end_date,
edge_size=64,
resolution=250,
)
da_africa_cubo
time_index = 2
# Select band and apply scaling only when needed
if "band" in da_africa_cubo.dims:
ndvi = da_africa_cubo.sel(band="250m_16_days_NDVI")
else:
ndvi = da_africa_cubo
scale_factor = 10000.0 if float(ndvi.max().values) > 1.5 else 1.0
ndvi_2d = ndvi.isel(time=time_index).squeeze() / scale_factor
time_labels = pd.date_range(start=start_date, end=end_date, periods=ndvi.sizes["time"])
snapshot_label = time_labels[time_index].strftime("%Y-%m-%d")
plt.figure(figsize=(6, 5))
ndvi_2d.plot(cmap="YlGn")
plt.title(f"MODIS NDVI snapshot ({snapshot_label})")
plt.axis("off")
plt.show()
Example 2B: cubo with Google Earth Engine (Asia, Sentinel-3 or MODIS)¶
When gee=True, cubo can pull data cubes from Earth Engine collections.
# Initialize Earth Engine first if needed:
# ee.Initialize(project="YOUR_GEE_PROJECT",
# opt_url="https://earthengine-highvolume.googleapis.com")
lat_africa = 5.947659
lon_africa = 43.559889
# Example: MODIS NDVI via GEE-backed cubo
da_africa_gee_cubo = cubo.create(
lat=lat_africa,
lon=lon_africa,
collection="MODIS/061/MOD13Q1",
bands=["NDVI", "EVI"],
start_date=start_date,
end_date=end_date,
edge_size=64,
resolution=250,
gee=True,
)
da_africa_gee_cubo
lat_asia = 22.5
lon_asia = 90.0
da_asia_cubo = cubo.create(
lat=lat_asia,
lon=lon_asia,
collection="MODIS/061/MOD13Q1",
bands=["NDVI", "EVI"],
start_date=start_date,
end_date=end_date,
edge_size=64,
resolution=250,
gee=True,
)
da_asia_cubo
# visualize one time step
time_index = 2
# Select band and plot
if "band" in da_asia_cubo.dims:
ndvi = da_asia_cubo.sel(band="NDVI")
else:
ndvi = da_asia_cubo
ndvi_2d = ndvi.isel(time=time_index).squeeze() / 10000.0
plt.figure(figsize=(6, 5))
ndvi_2d.plot(cmap="YlGn")
plt.title(f"MODIS NDVI snapshot ({ndvi.time.values[time_index]})")
plt.axis("off")
plt.show()
Optional Sentinel-3 variant in GEE-backed cubo¶
# Sentinel-3 OLCI in GEE
da_s3_cubo = cubo.create(
lat=lat_asia,
lon=lon_asia,
collection="COPERNICUS/S3/OLCI",
bands=["Oa08_radiance", "Oa06_radiance", "Oa04_radiance"],
start_date=start_date,
end_date=end_date,
edge_size=64,
resolution=300,
gee=True,
)
da_s3_cubo
Part 3 — Earth Engine + Xee for xarray-native analysis¶
xee is excellent when you want Earth Engine collections to feel more like xarray datasets.
This is a strong teaching path for people already comfortable with Python arrays.
Example 3A: Africa MODIS NDVI time series with Xee¶
# Earth Engine geometry
africa_roi = ee.Geometry.Rectangle(africa_bbox)
# plot the geometry on a map using geemap
import geemap
Map = geemap.Map(center=[(africa_bbox[1] + africa_bbox[3]) / 2, (africa_bbox[0] + africa_bbox[2]) / 2], zoom=6)
Map.addLayer(africa_roi, {}, "Africa ROI")
Map.addLayerControl()
Map
# MODIS NDVI collection
modis_ic = (
ee.ImageCollection("MODIS/061/MOD13Q1")
.filterBounds(africa_roi)
.filterDate(start_date, end_date)
.select(["NDVI", "EVI"])
)
# xee scale is in CRS units; in EPSG:4326 use ~250 m in degrees
scale_deg_250m = 250 / 111320
# Open with xee
ds_modis_xee = xr.open_dataset(
modis_ic,
engine="ee",
geometry=africa_bbox,
crs="EPSG:4326",
scale=scale_deg_250m,
)
print(ds_modis_xee.sizes)
ds_modis_xee
Example 3B: Reduce to a simple regional mean time series¶
# Previous (STAC cubo) approach kept for reference:
# if "band" in da_africa_cubo.dims:
# ndvi = da_africa_cubo.sel(band="250m_16_days_NDVI")
# else:
# ndvi = da_africa_cubo
# scale_factor = 10000.0 if float(ndvi.max().values) > 1.5 else 1.0
# ndvi = ndvi / scale_factor
# ndvi_mean_da = ndvi.mean(dim=("x", "y"))
# n_time = ndvi_mean_da.sizes["time"]
# time_axis = pd.date_range(start=start_date, end=end_date, periods=n_time)
# ndvi_mean_series = pd.Series(np.asarray(ndvi_mean_da.values).reshape(-1), index=time_axis, name="NDVI")
# Use GEE cubo directly (native time, no NaT fix needed)
if "band" in da_africa_gee_cubo.dims:
band_names = [str(b) for b in da_africa_gee_cubo.band.values]
target_band = "NDVI" if "NDVI" in band_names else band_names[0]
ndvi = da_africa_gee_cubo.sel(band=target_band)
else:
ndvi = da_africa_gee_cubo
scale_factor = 10000.0 if float(ndvi.max().values) > 1.5 else 1.0
ndvi = ndvi / scale_factor
ndvi_mean_series = ndvi.mean(dim=("x", "y")).to_series()
fig, ax = plt.subplots(figsize=(10, 4))
ndvi_mean_series.plot(ax=ax, marker="o")
ax.set_title(f"Africa GEE cubo NDVI mean ({start_date} to {end_date})")
ax.set_ylabel("NDVI")
ax.set_xlabel("time")
plt.show()
# Interactive comparison
import ipywidgets as widgets
from IPython.display import display
# Select NDVI band from GEE cubo
if "band" in da_africa_gee_cubo.dims:
band_names = [str(b) for b in da_africa_gee_cubo.band.values]
target_band = "NDVI" if "NDVI" in band_names else band_names[0]
ndvi_cube = da_africa_gee_cubo.sel(band=target_band).transpose("time", "y", "x")
else:
ndvi_cube = da_africa_gee_cubo.transpose("time", "y", "x")
scale_factor = 10000.0 if float(ndvi_cube.max().values) > 1.5 else 1.0
ndvi_cube = ndvi_cube / scale_factor
time_labels = pd.to_datetime(ndvi_cube.time.values).strftime("%Y-%m-%d").tolist()
max_index = ndvi_cube.sizes["time"] - 1
vmin = float(np.nanpercentile(ndvi_cube.values, 5))
vmax = float(np.nanpercentile(ndvi_cube.values, 95))
left_slider = widgets.IntSlider(
value=0, min=0, max=max_index, step=1, description="Left:", continuous_update=False
)
right_slider = widgets.IntSlider(
value=max_index, min=0, max=max_index, step=1, description="Right:", continuous_update=False
)
output = widgets.Output()
def draw_comparison(_=None):
left_index = left_slider.value
right_index = right_slider.value
with output:
output.clear_output(wait=True)
fig, axes = plt.subplots(1, 2, figsize=(12, 4), sharex=True, sharey=True)
left_plot = ndvi_cube.isel(time=left_index).plot(
ax=axes[0], cmap="YlGn", vmin=vmin, vmax=vmax, add_colorbar=False
)
ndvi_cube.isel(time=right_index).plot(
ax=axes[1], cmap="YlGn", vmin=vmin, vmax=vmax, add_colorbar=False
)
axes[0].set_title(f"NDVI {time_labels[left_index]}")
axes[1].set_title(f"NDVI {time_labels[right_index]}")
axes[0].set_xlabel("X")
axes[1].set_xlabel("X")
axes[0].set_ylabel("Y")
axes[1].set_ylabel("Y")
cax = axes[1].inset_axes([1.05, 0.08, 0.03, 1]) # for reference to move the colorbar: left, bottom, width, height
cb = fig.colorbar(left_plot, cax=cax, orientation="vertical")
cb.set_label("NDVI")
plt.tight_layout()
plt.show()
left_slider.observe(draw_comparison, names="value")
right_slider.observe(draw_comparison, names="value")
display(widgets.HBox([left_slider, right_slider]), output)
draw_comparison()
Example 3C: Simple anomaly against a baseline¶
# Illustrative anomaly workflow
modis_baseline_ic = (
ee.ImageCollection("MODIS/061/MOD13Q1")
.filterBounds(africa_roi)
.filterDate("2010-01-01", "2023-12-31")
.select("NDVI")
)
# Keep CRS/scale consistent with the main xee load above
scale_deg_250m = 250 / 111320
ds_baseline = xr.open_dataset(
modis_baseline_ic,
engine="ee",
geometry=africa_bbox,
crs="EPSG:4326",
scale=scale_deg_250m,
)
baseline_ndvi = ds_baseline["NDVI"] / 10000.0
current_ndvi = ds_modis_xee["NDVI"] / 10000.0
baseline_mean = baseline_ndvi.mean(dim="time")
current_mean = current_ndvi.mean(dim="time")
anomaly = current_mean - baseline_mean
plt.figure(figsize=(6, 5))
anomaly.plot(cmap="RdYlGn")
plt.title("NDVI anomaly map: 2023 vs 2015-2022 baseline")
plt.show()
# bbbox average anomaly time series
baseline_regional_mean = baseline_ndvi.mean(dim=("time", "lon", "lat"))
current_regional_series = current_ndvi.mean(dim=("lon", "lat"))
anomaly_series = (current_regional_series - baseline_regional_mean).to_series()
ax = anomaly_series.plot(figsize=(10, 4), marker="o", color="purple")
ax.axhline(0, color="black", linestyle="--", linewidth=1)
ax.set_title("Regional average NDVI anomaly time series (2023 vs 2015-2022)")
ax.set_ylabel("NDVI anomaly")
plt.show()
Part 4 — Asia example: Sentinel-3 OLCI with MPC + cubo (no GEE required)¶
Sentinel-3 OLCI is useful for:
- coastal water color context,
- sediment/turbidity proxies,
- large estuaries and deltas,
- broad land-water transitions.
For participants without GEE access, use cubo directly with MPC/STAC-backed collections.
# MPC + cubo Sentinel-3 example (Asia AOI)
# Use valid asset names from sentinel-3-olci-lfr-l2-netcdf
da_s3_mpc = cubo.create(
lat=lat_asia,
lon=lon_asia,
collection="sentinel-3-olci-lfr-l2-netcdf",
bands=["otci", "gifapar", "rc-gifapar"],
start_date=start_date,
end_date=end_date,
edge_size=96,
resolution=300,
)
da_s3_mpc
Quicklook visualization idea¶
# Quicklook once da_s3_mpc is loaded
try:
rgb = xr.concat(
[
da_s3_mpc.sel(band="otci").isel(time=0),
da_s3_mpc.sel(band="gifapar").isel(time=0),
da_s3_mpc.sel(band="rc-gifapar").isel(time=0),
],
dim="band",
)
rgb = rgb / rgb.quantile(0.98)
rgb = rgb.clip(0, 1)
plt.figure(figsize=(6, 6))
plt.imshow(np.transpose(rgb.values, (1, 2, 0)))
plt.title("Sentinel-3 MPC quicklook (otci / gifapar / rc-gifapar)")
plt.axis("off")
plt.show()
except Exception:
print("MPC Sentinel-3 NetCDF RGB stacking is not supported in this environment.")
print("Using GEE Sentinel-3 quicklook fallback (da_s3_cubo).")
rgb = xr.concat(
[
da_s3_cubo.sel(band="Oa08_radiance").isel(time=0),
da_s3_cubo.sel(band="Oa06_radiance").isel(time=0),
da_s3_cubo.sel(band="Oa04_radiance").isel(time=0),
],
dim="band",
)
rgb = rgb / rgb.quantile(0.98)
rgb = rgb.clip(0, 1)
plt.figure(figsize=(6, 6))
plt.imshow(np.transpose(rgb.values, (1, 2, 0)))
plt.title("Sentinel-3 GEE quicklook fallback")
plt.axis("off")
plt.show()
Interpreting Sentinel-3 quicklooks for deltas¶
- These RGB-style composites are context images (qualitative), not directly a calibrated index map.
- Bright/dark and color differences show relative reflectance contrasts within the scene after stretch.
- For quantitative analysis, combine with quality masks and science variables (e.g., OLCI products or derived indices).
Common Sentinel-3 OLCI band combinations used in delta/coastal literature¶
- Natural-color style:
Oa08 / Oa06 / Oa04- Useful for broad land-water context and plume visualization.
- Water-contrast style:
Oa11 / Oa08 / Oa04- Highlights suspended sediments/turbid features versus clearer water.
- NIR-emphasis style:
Oa17 / Oa08 / Oa06- Can help separate vegetation-rich land/wetland from open water.
Always validate interpretation with in-situ data, QA flags, and time-series behavior.
# Optional: literature-style Sentinel-3 OLCI combinations for delta studies (GEE-backed cubo)
s3_combo_bands = ["Oa04_radiance", "Oa06_radiance", "Oa08_radiance", "Oa11_radiance", "Oa17_radiance"]
da_s3_cubo_lit = cubo.create(
lat=lat_asia,
lon=lon_asia,
collection="COPERNICUS/S3/OLCI",
bands=s3_combo_bands,
start_date=start_date,
end_date=end_date,
edge_size=64,
resolution=300,
gee=True,
)
def _quick_rgb(da, r, g, b, t=0):
rgb = xr.concat(
[
da.sel(band=r).isel(time=t),
da.sel(band=g).isel(time=t),
da.sel(band=b).isel(time=t),
],
dim="band",
)
rgb = rgb / rgb.quantile(0.98)
return rgb.clip(0, 1)
combo_specs = [
("Natural-color style", ("Oa08_radiance", "Oa06_radiance", "Oa04_radiance")),
("Water-contrast style", ("Oa11_radiance", "Oa08_radiance", "Oa04_radiance")),
("NIR-emphasis style", ("Oa17_radiance", "Oa08_radiance", "Oa06_radiance")),
]
fig, axes = plt.subplots(1, len(combo_specs), figsize=(15, 5))
for ax, (title, (r, g, b)) in zip(axes, combo_specs):
rgb = _quick_rgb(da_s3_cubo_lit, r, g, b, t=0)
ax.imshow(np.transpose(rgb.values, (1, 2, 0)))
ax.set_title(f"{title}\n({r} / {g} / {b})")
ax.axis("off")
plt.suptitle("Sentinel-3 OLCI delta-focused band combinations (quicklook)")
plt.tight_layout()
plt.show()
Part 5 — Integrated approach with MPC + cubo (no GEE required)¶
A resilience workflow is usually stronger when satellite observations are interpreted together with:
- rainfall,
- temperature,
- hydrology,
- exposure and vulnerability layers.
Below is an MPC + cubo pattern for rainfall and vegetation context.
Example 5A: CHIRPS rainfall + MODIS NDVI in Africa¶
# MODIS NDVI cube via GEE-backed cubo
da_modis_mpc = cubo.create(
lat=lat_africa,
lon=lon_africa,
collection="MODIS/061/MOD13Q1",
bands=["NDVI"],
start_date=start_date,
end_date=end_date,
edge_size=96,
resolution=250,
gee=True,
)
# CHIRPS rainfall cube via GEE-backed cubo
da_chirps_mpc = cubo.create(
lat=lat_africa,
lon=lon_africa,
collection="UCSB-CHG/CHIRPS/DAILY",
bands=["precipitation"],
start_date=start_date,
end_date=end_date,
edge_size=96,
resolution=5566,
gee=True,
)
print(da_modis_mpc)
print(da_chirps_mpc)
# MODIS NDVI (scale to [-1, 1]-like range when needed)
ndvi = da_modis_mpc.sel(band="NDVI")
ndvi_scale = 10000.0 if float(ndvi.max().values) > 1.5 else 1.0
ndvi_series = (ndvi / ndvi_scale).mean(dim=("y", "x")).to_series().sort_index()
# CHIRPS rainfall
rain = da_chirps_mpc.sel(band="precipitation")
rain_series = rain.mean(dim=("y", "x")).to_series().sort_index()
# Align dates shared by both series
common_index = ndvi_series.index.intersection(rain_series.index)
ndvi_series = ndvi_series.loc[common_index]
rain_series = rain_series.loc[common_index]
fig, ax1 = plt.subplots(figsize=(12, 4))
ax2 = ax1.twinx()
# Rainfall plot
rain_line, = ax1.plot(
rain_series.index, rain_series.values,
color="tab:blue", linewidth=1.8, label="Rainfall (CHIRPS)"
)
ax1.fill_between(
rain_series.index, rain_series.values, 0,
color="tab:blue", alpha=0.20
)
# NDVI plot
ndvi_line, = ax2.plot(
ndvi_series.index, ndvi_series.values,
color="darkgreen", linewidth=1.8, label="NDVI (MODIS)"
)
ax2.fill_between(
ndvi_series.index, ndvi_series.values, 0,
color="darkgreen", alpha=0.20
)
ax1.set_title("Africa Example — GEE + cubo rainfall and Vegetation")
ax1.set_xlabel("Time")
ax1.set_ylabel("Rainfall (mm/day)", color="tab:blue")
ax2.set_ylabel("NDVI", color="darkgreen")
ax1.tick_params(axis="y", colors="tab:blue")
ax2.tick_params(axis="y", colors="darkgreen")
ax1.grid(alpha=0.25)
lines = [rain_line, ndvi_line]
labels = [line.get_label() for line in lines]
ax1.legend(lines, labels, loc="upper left")
plt.tight_layout()
plt.show()
Comparison of the four main access patterns¶
| Option | Best use | Strength | Watch out for |
|---|---|---|---|
| STAC API | discovery and interoperable search | standards-based, portable | actual asset handling may still require extra code |
| MPC | cloud-hosted STAC datasets | easy search and many public datasets | collection naming and asset structure vary |
| GEE | large-scale catalog + processing | huge catalog, server-side filtering | authentication and API concepts |
| Xee | Earth Engine to xarray | analysis-friendly for Python users | some workflows still need EE thinking |
| cubo | compact data-cube creation | simple mental model across STAC/GEE | backend support varies by collection |
Key message¶
Climate resilience monitoring is rarely about one sensor or one platform. The most practical skill is learning to move between:
- discovery,
- access,
- cube creation,
- aggregation,
- interpretation.
Interpretation examples¶
- Lower NDVI together with rainfall deficits can indicate drought stress.
- Sentinel-3 coastal color patterns can help identify sediment plumes and broad coastal change context.
- Medium-resolution products are excellent for regional monitoring, but not for parcel-scale decisions.
Exercises for participants¶
- Replace the Africa bounding box AOI of your choice.
- Replace the Asia AOI with the Mekong Delta.
- Add a 2019–2024 annual NDVI summary.
- Compute a monthly climatology.
- Add MODIS LST or CHIRPS rainfall and compare seasonal patterns.
- Try the same workflow through:
- raw STAC search or other STAC via Cubo
Closing remarks¶
This notebook intentionally mixes several access patterns because that reflects real EO practice:
- no single interface solves every workflow,
- standards like STAC improve portability,
- Earth Engine accelerates computation,
- xarray-based tools make Python analysis cleaner,
cubocan reduce boilerplate for prototyping.
# import nbformat
# from nbconvert import HTMLExporter
# import os
# def ipynb_to_html(ipynb_path, html_path):
# """
# Convert a Jupyter Notebook (.ipynb) to an HTML file with outputs preserved.
# Args:
# ipynb_path (str): Path to the .ipynb file.
# html_path (str): Path to save the generated HTML file.
# """
# try:
# # Validate file existence
# if not os.path.isfile(ipynb_path):
# raise FileNotFoundError(f"Notebook file not found: {ipynb_path}")
# # Read the notebook
# with open(ipynb_path, 'r', encoding='utf-8') as f:
# notebook_node = nbformat.read(f, as_version=4)
# # Create HTML exporter
# html_exporter = HTMLExporter()
# html_exporter.exclude_input = False # Keep code cells
# html_exporter.exclude_output = False # Keep outputs
# # Convert notebook to HTML
# body, _ = html_exporter.from_notebook_node(notebook_node)
# # Save HTML file
# with open(html_path, 'w', encoding='utf-8') as f:
# f.write(body)
# print(f"✅ HTML file created: {html_path}")
# except Exception as e:
# print(f"❌ Error: {e}")
# # Example usage
# ipynb_to_html("cubo_xarray_dask_tutorial.ipynb", "docs\\assets\\cubo_xarray_dask_tutorial.html")