"""Satellite flood mapping for the Valencia DANA floods of 29 October 2024 with Sentinel-1 and Sentinel-2. Part 2 of "GIS for disaster emergency response". Maps the flood in L'Horta Sud from the earliest post-event Sentinel-1 RTC pass (change detection against a pre-event pass on the same orbit), cross-checks it with a post-event Sentinel-2 L2A scene (MNDWI water and a fresh-sediment index), and scores both against the Copernicus EMS Rapid Mapping delineation EMSR773 with an agreement matrix. Run with: python satellite_flood_mapping.py """ import json import platform import zipfile from datetime import datetime, timezone from importlib.metadata import version from pathlib import Path import geopandas as gpd import matplotlib matplotlib.use("Agg") import matplotlib.patheffects as pe import matplotlib.pyplot as plt import numpy as np import pandas as pd import planetary_computer import pystac_client import rasterio import rasterio.features import requests from matplotlib.colors import ListedColormap from matplotlib.patches import Patch from PIL import Image from pyproj import Transformer from rasterio.enums import Resampling from rasterio.transform import from_origin from rasterio.vrt import WarpedVRT from scipy import ndimage from skimage.filters import threshold_otsu HERE = Path(__file__).parent OUT = HERE / "output" DATA = HERE / "data" OUT.mkdir(exist_ok=True) DATA.mkdir(exist_ok=True) plt.rcParams.update({"figure.dpi": 150, "savefig.bbox": "tight", "font.size": 9}) pd.set_option("display.width", 140) np.seterr(all="ignore") print("=== versions ===") print(f"python {platform.python_version()} | pystac-client {pystac_client.__version__} | " f"rasterio {rasterio.__version__} | geopandas {gpd.__version__} | numpy {np.__version__} | " f"scikit-image {version('scikit-image')}") STAC_URL = "https://planetarycomputer.microsoft.com/api/stac/v1" EMS_API = "https://rapidmapping.emergency.copernicus.eu/backend/dashboard-api/public-activations/?code=EMSR773" BBOX = (-0.55, 39.33, -0.30, 39.50) # lon/lat: L'Horta Sud, from Torrent and Aldaia to the Albufera EVENT = datetime(2024, 10, 29, 14, 30, tzinfo=timezone.utc) # EMS event time CRS = "EPSG:25830" # ETRS89 / UTM zone 30N RES = 10 # metres: native resolution of both sensors' main bands S1_ORBIT = 110 # descending pass over Valencia at 06:02 UTC S1_CONTROL, S1_PRE, S1_POST = "2024-10-08", "2024-10-20", "2024-11-01" S2_TILE, S2_PRE, S2_POST = "30SYJ", "2024-10-26", "2024-10-31" S2_CLOUD = [0, 1, 3, 8, 9, 11] # SCL: no data, saturated, cloud shadow, cloud medium/high, snow to_utm = Transformer.from_crs("EPSG:4326", CRS, always_xy=True) xs, ys = to_utm.transform([BBOX[0], BBOX[2], BBOX[0], BBOX[2]], [BBOX[1], BBOX[1], BBOX[3], BBOX[3]]) x0, x1 = np.floor(min(xs) / RES) * RES, np.ceil(max(xs) / RES) * RES y0, y1 = np.floor(min(ys) / RES) * RES, np.ceil(max(ys) / RES) * RES WIDTH, HEIGHT = int((x1 - x0) / RES), int((y1 - y0) / RES) TRANSFORM = from_origin(x0, y1, RES, RES) PX_KM2 = RES * RES / 1e6 def section(title: str) -> None: print(f"\n=== {title} ===") def km2(mask: np.ndarray) -> float: return float(mask.sum() * PX_KM2) def warp(href: str, resampling=Resampling.average, dtype="float32") -> np.ndarray: """Stream a remote COG onto the analysis grid; NaN (or 0 for integers) where there is no data.""" nodata = np.nan if dtype == "float32" else 0 with rasterio.open(href) as src, WarpedVRT(src, crs=CRS, transform=TRANSFORM, width=WIDTH, height=HEIGHT, resampling=resampling, src_nodata=src.nodata, nodata=nodata, dtype=dtype) as vrt: return vrt.read(1) def rasterize(geoms) -> np.ndarray: return rasterio.features.rasterize(geoms, out_shape=(HEIGHT, WIDTH), transform=TRANSFORM).astype(bool) def clean(mask: np.ndarray, min_px: int = 20) -> np.ndarray: """Morphological opening, then drop patches smaller than min_px pixels (20 px = 0.2 ha).""" m = ndimage.binary_opening(mask, iterations=1) lab, n = ndimage.label(m) sizes = ndimage.sum(m, lab, index=np.arange(1, n + 1)) return np.isin(lab, 1 + np.flatnonzero(sizes >= min_px)) # --- Step 1: the Copernicus EMS reference -------------------------------------------- section("Copernicus EMS activation EMSR773") act = requests.get(EMS_API, timeout=60).json()["results"][0] print(f"{act['code']}: {act['name']} | event {act['eventTime']} UTC | activated {act['activationTime']} UTC") aoi1 = next(a for a in act["aois"] if a["number"] == 1) first = next(p for p in aoi1["products"] if p["type"] == "DEL" and p["monitoringNumber"] == 0) print(f"AOI {aoi1['number']:02d} {aoi1['name']}: first delineation, delivered {first['version']['deliveryTime'][:16]}") for img in first["images"]: print(f" {img['sensorName']:<12} {img['acquisitionTime']} ({img['resolutionClass']})") zip_path = DATA / Path(first["downloadPath"]).name if not zip_path.exists(): zip_path.write_bytes(requests.get(first["downloadPath"], timeout=300).content) stem = zip_path.stem.replace("_v1", "") def ems_layer(name: str) -> gpd.GeoDataFrame: return gpd.read_file(f"zip://{zip_path.resolve()}!{stem}_{name}_v1.shp").to_crs(CRS) ems = ems_layer("observedEventA") ems_aoi = ems_layer("areaOfInterestA") with zipfile.ZipFile(zip_path) as z, z.open(f"{stem}_source_v1.dbf") as f: (DATA / "source.dbf").write_bytes(f.read()) sources = gpd.read_file(DATA / "source.dbf").set_index("src_id") ems["source"] = ems.dmg_src_id.map(lambda i: f"{sources.source_nam[i]} {sources.src_date[i]}") grid_box = gpd.GeoSeries.from_xy([x0, x1], [y0, y1], crs=CRS).total_bounds ems_box = ems.clip(grid_box) ems_box["km2"] = ems_box.area / 1e6 print(f"study area {WIDTH * RES / 1000:.1f} x {HEIGHT * RES / 1000:.1f} km; EMS observed flood inside it:") print(ems_box.groupby(["notation", "source"]).km2.sum().round(1).to_string()) ems_area = rasterize(ems.geometry[ems.notation == "Flooded area"]) ems_trace = rasterize(ems.geometry[ems.notation == "Flood trace"]) & ~ems_area ems_any = ems_area | ems_trace in_aoi = rasterize(ems_aoi.geometry) # --- Step 2: find the Sentinel-1 passes ---------------------------------------------- catalog = pystac_client.Client.open(STAC_URL, modifier=planetary_computer.sign_inplace) s1_items = list(catalog.search(collections=["sentinel-1-rtc"], bbox=BBOX, datetime="2024-10-01/2024-11-10").items()) section("Sentinel-1 RTC passes over the study area") passes = pd.DataFrame([{"date": i.datetime.strftime("%Y-%m-%d"), "time_utc": i.datetime.strftime("%H:%M"), "orbit": i.properties["sat:relative_orbit"], "direction": i.properties["sat:orbit_state"]} for i in s1_items]).drop_duplicates().sort_values(["date", "time_utc"]) print(passes.to_string(index=False)) post_item = next(i for i in s1_items if i.datetime.strftime("%Y-%m-%d") == S1_POST) print(f"first pass after the event: {S1_POST} {post_item.datetime:%H:%M} UTC, " f"{(post_item.datetime - EVENT).total_seconds() / 3600:.0f} hours after the rain began") ENL = post_item.properties["sar:looks_equivalent_number"] def lee_filter(img: np.ndarray, size: int = 7, enl: float = ENL) -> np.ndarray: """Lee (1980) speckle filter on linear power.""" nan = np.isnan(img) img = np.where(nan, np.nanmedian(img), img) mean = ndimage.uniform_filter(img, size) var = np.maximum(ndimage.uniform_filter(img * img, size) - mean * mean, 0) ci2 = var / np.maximum(mean * mean, 1e-12) w = np.clip(1 - (1 / enl) / np.maximum(ci2, 1e-12), 0, 1) out = mean + w * (img - mean) out[nan] = np.nan return out def read_s1_db(date: str, pol: str = "vv") -> np.ndarray: """Mosaic every frame of one orbit on one date, Lee-filter in linear power, return dB.""" frames = [i for i in s1_items if i.datetime.strftime("%Y-%m-%d") == date and i.properties["sat:relative_orbit"] == S1_ORBIT] power = np.full((HEIGHT, WIDTH), np.nan, "float32") for it in frames: arr = warp(it.assets[pol].href) power = np.where(np.isfinite(power), power, arr) return 10 * np.log10(lee_filter(power)) section("reading Sentinel-1 VV (orbit 110, descending, 10 m)") vv = {d: read_s1_db(d) for d in (S1_CONTROL, S1_PRE, S1_POST)} for d, a in vv.items(): print(f"{d}: {np.isfinite(a).mean():.1%} valid, median {np.nanmedian(a):.1f} dB") # --- Step 3: Sentinel-1 change detection ------------------------------------------------ pre, post = vv[S1_PRE], vv[S1_POST] s1_valid = np.isfinite(pre) & np.isfinite(post) thr = threshold_otsu(post[s1_valid]) DROP = -3.0 # dB: the pixel must also have darkened by 3 dB or more def s1_flood(before: np.ndarray, after: np.ndarray) -> np.ndarray: return clean((after < thr) & (before >= thr) & (after - before < DROP)) s1_water_pre = clean(pre < thr) s1 = s1_flood(pre, post) & s1_valid control = s1_flood(vv[S1_CONTROL], pre) & s1_valid section("Sentinel-1 change detection") print(f"Otsu threshold on {S1_POST}: {thr:.1f} dB; change rule: below it, above it before, and {DROP:.0f} dB darker") print(f"water on {S1_PRE}: {km2(s1_water_pre):.1f} km²") print(f"new water on {S1_POST}: {km2(s1):.1f} km²") print(f"same rule on two dry dates ({S1_CONTROL} -> {S1_PRE}): {km2(control):.2f} km² flagged") # --- Step 4: Sentinel-2 water and fresh sediment --------------------------------------------- s2_items = {} for d in (S2_PRE, S2_POST): s2_items[d] = next(i for i in catalog.search(collections=["sentinel-2-l2a"], bbox=BBOX, datetime=d).items() if i.properties["s2:mgrs_tile"] == S2_TILE) def read_s2(item) -> dict: """Surface reflectance (0-1) at 10 m. Baseline 04.00+ scenes carry a +1000 offset.""" offset = 1000 if float(item.properties["s2:processing_baseline"]) >= 4 else 0 bands = {b: (warp(item.assets[b].href, Resampling.bilinear) - offset) / 10000 for b in ("B02", "B03", "B04", "B08", "B11")} bands["SCL"] = warp(item.assets["SCL"].href, Resampling.nearest, "uint8") return bands s2 = {d: read_s2(it) for d, it in s2_items.items()} def mndwi(b: dict) -> np.ndarray: return (b["B03"] - b["B11"]) / (b["B03"] + b["B11"]) def sediment(b: dict) -> np.ndarray: """Normalised difference of red and SWIR1: wet, fresh mud is bright in red and dark in SWIR1.""" return (b["B04"] - b["B11"]) / (b["B04"] + b["B11"]) s2_clear = ~np.isin(s2[S2_POST]["SCL"], S2_CLOUD) & ~np.isin(s2[S2_PRE]["SCL"], S2_CLOUD) permanent = (mndwi(s2[S2_PRE]) > 0) | (s2[S2_PRE]["SCL"] == 6) | s1_water_pre s2_water = clean((mndwi(s2[S2_POST]) > 0) & ~permanent) & s2_clear d_sed = sediment(s2[S2_POST]) - sediment(s2[S2_PRE]) s2_sed = clean((d_sed > 0.2) & ~s2_water & ~permanent) & s2_clear section("Sentinel-2 L2A") for d, it in s2_items.items(): p = it.properties print(f"{d} {p['s2:mgrs_tile']} {it.datetime:%H:%M} UTC | tile cloud {p['eo:cloud_cover']:.0f}% | baseline {p['s2:processing_baseline']}") print(f"post-event scene: {(s2_items[S2_POST].datetime - EVENT).total_seconds() / 3600:.0f} hours after the rain began") print(f"clear on both dates (SCL): {s2_clear[in_aoi].mean():.1%} of the study area") print(f"permanent water (sea, port, Albufera, river): {km2(permanent):.1f} km²") print(f"new water, MNDWI > 0: {km2(s2_water):.1f} km²") print(f"fresh sediment, red/SWIR1 index up by > 0.2: {km2(s2_sed):.1f} km²") # --- Step 5: agreement with the Copernicus EMS delineation ------------------------------------- domain = in_aoi & s1_valid & ~permanent combined = s1 | s2_water | s2_sed def agreement(pred: np.ndarray, ref: np.ndarray, where: np.ndarray) -> dict: tp = km2(pred & ref & where) fp = km2(pred & ~ref & where) fn = km2(~pred & ref & where) tn = km2(~pred & ~ref & where) return {"domain_km2": tp + fp + fn + tn, "ours_km2": tp + fp, "ems_km2": tp + fn, "TP": tp, "FP": fp, "FN": fn, "TN": tn, "precision": tp / (tp + fp), "recall": tp / (tp + fn), "F1": 2 * tp / (2 * tp + fp + fn), "IoU": tp / (tp + fp + fn), "overall": (tp + tn) / (tp + fp + fn + tn)} methods = { "S1 change, all pixels": (s1, domain), "S1 change, S2-clear pixels": (s1, domain & s2_clear), "S2 water (MNDWI)": (s2_water, domain & s2_clear), "S2 water + sediment": (s2_water | s2_sed, domain & s2_clear), "S1 + S2 combined": (combined, domain & s2_clear), } metrics = pd.DataFrame({k: agreement(p, ems_any, w) for k, (p, w) in methods.items()}).T section("agreement with EMSR773 (flooded area + flood trace), km² and scores") print(metrics[["domain_km2", "ours_km2", "ems_km2", "TP", "FP", "FN"]].round(1).to_string()) print(metrics[["precision", "recall", "F1", "IoU", "overall"]].round(3).to_string()) section("confusion matrix, S1 + S2 combined (km², S2-clear pixels)") m = metrics.loc["S1 + S2 combined"] print(pd.DataFrame([[m.TP, m.FN], [m.FP, m.TN]], index=["EMS flooded", "EMS not flooded"], columns=["ours flooded", "ours not flooded"]).round(1).to_string()) section("recall by EMS class (share of EMS pixels we also mapped)") rec = [] for name, (pred, where) in methods.items(): rec.append({"method": name, "flooded area": (pred & ems_area & where).sum() / (ems_area & where).sum(), "flood trace": (pred & ems_trace & where).sum() / (ems_trace & where).sum()}) rec = pd.DataFrame(rec).set_index("method") print(rec.round(3).to_string()) # A second, independent reference: the very-high-resolution delineation of AOI03 Horta Sud (31 October). aoi3 = next(a for a in act["aois"] if a["number"] == 3) p3 = next(p for p in aoi3["products"] if p["type"] == "DEL") zip3 = DATA / Path(p3["downloadPath"]).name if not zip3.exists(): zip3.write_bytes(requests.get(p3["downloadPath"], timeout=300).content) vhr = gpd.read_file(f"zip://{zip3.resolve()}!{zip3.stem.replace('_v1', '')}_observedEventA_v1.shp").to_crs(CRS) vhr_mask = rasterize(vhr.geometry) & domain section("check against the AOI03 Horta Sud delineation (WorldView-2/GeoEye-1, 31 Oct)") print(f"VHR-mapped flood inside the study area: {km2(vhr_mask):.1f} km² " f"({km2(vhr_mask & s2_clear):.1f} km² on S2-clear pixels)") print(f"share caught: S1 {(s1 & vhr_mask).sum() / vhr_mask.sum():.1%}, " f"S1 + S2 combined {(combined & vhr_mask & s2_clear).sum() / (vhr_mask & s2_clear).sum():.1%} (S2-clear pixels)") # --- Step 6: save the results --------------------------------------------------------------- classes = np.zeros((HEIGHT, WIDTH), "uint8") classes[s2_sed] = 3 classes[s2_water] = 2 classes[s1] = 1 classes[~domain] = 255 with rasterio.open(OUT / "flood_valencia_2024.tif", "w", driver="GTiff", height=HEIGHT, width=WIDTH, count=1, dtype="uint8", crs=CRS, transform=TRANSFORM, nodata=255, compress="deflate") as dst: dst.write(classes, 1) dst.update_tags(1, classes="0 not flooded, 1 Sentinel-1 new water, 2 Sentinel-2 new water, 3 Sentinel-2 fresh sediment") labels = {1: "S1 water 2024-11-01", 2: "S2 water 2024-10-31", 3: "S2 sediment 2024-10-31"} shapes = rasterio.features.shapes(classes, mask=(classes > 0) & (classes < 255), transform=TRANSFORM) polys = gpd.GeoDataFrame.from_features( [{"geometry": g, "properties": {"class": labels[int(v)]}} for g, v in shapes], crs=CRS) polys["area_ha"] = (polys.area / 1e4).round(2) polys.to_file(OUT / "flood_valencia_2024.gpkg", driver="GPKG") (OUT / "metrics.json").write_text(json.dumps({"agreement": metrics.round(4).to_dict(orient="index"), "recall_by_class": rec.round(4).to_dict(orient="index"), "s1_threshold_db": round(float(thr), 2)}, indent=2)) section("saved") print(f"{len(polys):,} polygons: " + ", ".join(f"{k} {v:.1f} km²" for k, v in (polys.groupby('class').area_ha.sum() / 100).items())) # --- Step 7: figures ------------------------------------------------------------------------------- extent = [x0 / 1000, x1 / 1000, y0 / 1000, y1 / 1000] CREDIT = ("Contains modified Copernicus Sentinel data 2024 (Planetary Computer). " "Reference: © European Union, Copernicus EMS Rapid Mapping EMSR773.") TOWNS = {"València": (-0.376, 39.470), "Paiporta": (-0.418, 39.428), "Picanya": (-0.435, 39.436), "Torrent": (-0.465, 39.437), "Aldaia": (-0.463, 39.465), "Catarroja": (-0.404, 39.403), "Massanassa": (-0.398, 39.411), "Sedaví": (-0.384, 39.427), "Alfafar": (-0.385, 39.420), "L'Albufera": (-0.345, 39.345)} def frame(ax, title: str, towns: bool = True, credit: bool = True) -> None: ax.set_title(title) ax.set_xlabel("Easting (km, EPSG:25830)") ax.set_ylabel("Northing (km)") ax.set_xlim(extent[:2]) ax.set_ylim(extent[2:]) if towns: for name, (lon, lat) in TOWNS.items(): ex, ey = to_utm.transform(lon, lat) ax.plot(ex / 1000, ey / 1000, "o", ms=2.5, color="black", mec="white", mew=0.6) ax.annotate(name, (ex / 1000, ey / 1000), xytext=(4, 3), textcoords="offset points", fontsize=7, color="black", path_effects=[pe.withStroke(linewidth=2, foreground="white")]) if credit: ax.text(0.01, 0.01, CREDIT, transform=ax.transAxes, fontsize=5.5, color="#333", bbox={"facecolor": "white", "alpha": 0.7, "pad": 1.5, "lw": 0}) def true_colour(b: dict, gain: float = 3.2) -> np.ndarray: rgb = np.dstack([b["B04"], b["B03"], b["B02"]]) * gain return np.clip(rgb ** (1 / 1.2), 0, 1) # 01: the EMS reference over the pre-event image fig, ax = plt.subplots(figsize=(9, 8.2), constrained_layout=True) ax.imshow(true_colour(s2[S2_PRE]), extent=extent) ems_km = ems_box.set_geometry(ems_box.geometry.scale(1e-3, 1e-3, origin=(0, 0))) # axes are in km for notation, colour in (("Flood trace", "#e8590c"), ("Flooded area", "#1c7ed6")): ems_km[ems_km.notation == notation].plot(ax=ax, color=colour, alpha=0.55, lw=0) ax.legend(handles=[Patch(color="#1c7ed6", alpha=0.7, label=f"Flooded area ({ems_box[ems_box.notation == 'Flooded area'].km2.sum():.0f} km²)"), Patch(color="#e8590c", alpha=0.7, label=f"Flood trace ({ems_box[ems_box.notation == 'Flood trace'].km2.sum():.0f} km²)")], loc="upper left", fontsize=8, title="EMSR773 first delineation", title_fontsize=8) frame(ax, f"Copernicus EMS observed flood over Sentinel-2, {pd.Timestamp(S2_PRE):%d %b %Y} (before)") fig.savefig(OUT / "01-ems-reference.png", dpi=190) plt.close(fig) # 02: Sentinel-1 before, after and change d_vv = post - pre fig, axes = plt.subplots(1, 3, figsize=(15, 5.2), constrained_layout=True) for ax, arr, title in ((axes[0], pre, f"VV before, {pd.Timestamp(S1_PRE):%d %b}"), (axes[1], post, f"VV after, {pd.Timestamp(S1_POST):%d %b} 06:02 UTC")): im = ax.imshow(arr, cmap="gray", vmin=-25, vmax=0, extent=extent) frame(ax, title, towns=False, credit=False) fig.colorbar(im, ax=axes[:2], shrink=0.7, label="VV backscatter (dB)", location="bottom", aspect=40) im2 = axes[2].imshow(d_vv, cmap="RdBu", vmin=-8, vmax=8, extent=extent) frame(axes[2], "Change (after − before)", towns=True, credit=False) fig.colorbar(im2, ax=axes[2], shrink=0.7, label="dB (red = darker after)", location="bottom", aspect=20) fig.savefig(OUT / "02-sentinel-1-change.png") plt.close(fig) # 03: histogram and the dry-date control fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), constrained_layout=True) bins = np.linspace(-30, 5, 141) axes[0].hist(pre[s1_valid], bins=bins, color="#adb5bd", alpha=0.85, label=f"before ({S1_PRE})") axes[0].hist(post[s1_valid], bins=bins, color="#1d6fa3", alpha=0.55, label=f"after ({S1_POST})") axes[0].axvline(thr, color="#e8590c", lw=2, label=f"Otsu threshold {thr:.1f} dB") axes[0].set(xlabel="VV backscatter (dB), Lee-filtered", ylabel="pixels", title="Water threshold") axes[0].legend(fontsize=7) bins = np.linspace(-12, 12, 121) axes[1].hist((pre - vv[S1_CONTROL])[s1_valid], bins=bins, color="#adb5bd", alpha=0.85, label="two dry dates (8 → 20 Oct)") axes[1].hist(d_vv[s1_valid], bins=bins, color="#1d6fa3", alpha=0.55, label="across the flood (20 Oct → 1 Nov)") axes[1].axvline(DROP, color="#e8590c", lw=2, label=f"{DROP:.0f} dB change rule") axes[1].set_yscale("log") axes[1].set(xlabel="change in VV (dB)", ylabel="pixels (log scale)", title="Change between passes") axes[1].legend(fontsize=7) for ax in axes: ax.grid(alpha=0.3) fig.savefig(OUT / "03-sentinel-1-threshold.png") plt.close(fig) # 04: Sentinel-2 after, with the water and sediment masks fig, axes = plt.subplots(1, 2, figsize=(15, 6.6), constrained_layout=True) axes[0].imshow(true_colour(s2[S2_POST]), extent=extent) frame(axes[0], f"Sentinel-2 true colour, {pd.Timestamp(S2_POST):%d %b %Y} 10:51 UTC", credit=False) base = np.dstack([np.clip(true_colour(s2[S2_POST]).mean(axis=2) * 0.9 + 0.1, 0, 1)] * 3) overlay = np.zeros((HEIGHT, WIDTH, 4)) overlay[~s2_clear] = (1, 1, 1, 0.75) overlay[s2_sed] = (0.74, 0.47, 0.18, 1) overlay[s2_water] = (0.11, 0.49, 0.84, 1) overlay[permanent & s2_clear] = (0.55, 0.65, 0.75, 0.5) axes[1].imshow(base, extent=extent) axes[1].imshow(overlay, extent=extent, interpolation="nearest") axes[1].legend(handles=[Patch(color=(0.11, 0.49, 0.84), label=f"New water, MNDWI > 0 ({km2(s2_water):.1f} km²)"), Patch(color=(0.74, 0.47, 0.18), label=f"Fresh sediment ({km2(s2_sed):.1f} km²)"), Patch(color=(0.55, 0.65, 0.75), label="Permanent water"), Patch(facecolor="white", edgecolor="#999", label="Cloud or shadow (masked)")], loc="upper left", fontsize=7) frame(axes[1], "Water and sediment from Sentinel-2") fig.savefig(OUT / "04-sentinel-2-water-sediment.png") plt.close(fig) # 05: agreement map agree = np.zeros((HEIGHT, WIDTH), "uint8") where = domain & s2_clear agree[combined & ems_any & where] = 1 agree[combined & ~ems_any & where] = 2 agree[~combined & ems_any & where] = 3 agree[domain & ~s2_clear & s1 & ems_any] = 1 agree[domain & ~s2_clear & s1 & ~ems_any] = 2 agree[domain & ~s2_clear & ~s1 & ems_any] = 4 fig, ax = plt.subplots(figsize=(9, 8.2), constrained_layout=True) ax.imshow(np.where(np.isfinite(pre), np.clip((pre + 25) / 25, 0, 1), 1), cmap="gray", vmin=-0.6, vmax=1.4, extent=extent) cols = ["#2b8a3e", "#e8590c", "#7048e8", "#c5b3f6"] ax.imshow(np.ma.masked_equal(agree, 0), cmap=ListedColormap(cols), vmin=1, vmax=4, extent=extent, interpolation="nearest") mc = metrics.loc["S1 + S2 combined"] ax.legend(handles=[Patch(color=cols[0], label="Both: satellite map and EMS"), Patch(color=cols[1], label="Satellite map only (commission)"), Patch(color=cols[2], label="EMS only (omission)"), Patch(color=cols[3], label="EMS only, under cloud on 31 Oct")], loc="upper left", fontsize=8, title=f"F1 {mc.F1:.2f} | IoU {mc.IoU:.2f} (S2-clear pixels)", title_fontsize=8) frame(ax, "Satellite flood map (S1 + S2) against the Copernicus EMS delineation") fig.savefig(OUT / "05-agreement-map.png", dpi=190) plt.close(fig) # 06: agreement matrices and recall by class show = ["S1 change, S2-clear pixels", "S2 water + sediment", "S1 + S2 combined"] fig, axes = plt.subplots(1, 4, figsize=(16, 3.9), constrained_layout=True, gridspec_kw={"width_ratios": [1, 1, 1, 1.35]}) for ax, name in zip(axes, show): r = metrics.loc[name] mat = np.array([[r.TP, r.FN], [r.FP, r.TN]]) ax.imshow(mat / mat.sum(), cmap="Blues", vmin=0, vmax=0.5) for (i, j), v in np.ndenumerate(mat): ax.text(j, i, f"{v:.1f} km²", ha="center", va="center", fontsize=9, color="white" if v / mat.sum() > 0.3 else "black") ax.set_xticks([0, 1], ["mapped", "not mapped"]) ax.set_yticks([0, 1], ["EMS flooded", "EMS dry"]) ax.set_title(f"{name}\nF1 {r.F1:.2f} | IoU {r.IoU:.2f}", fontsize=8.5) rec_show = rec.loc[show] yy = np.arange(len(show)) axes[3].barh(yy + 0.2, rec_show["flooded area"] * 100, 0.38, color="#1c7ed6", label="EMS flooded area") axes[3].barh(yy - 0.2, rec_show["flood trace"] * 100, 0.38, color="#e8590c", label="EMS flood trace") axes[3].set_yticks(yy, [s.replace(", S2-clear pixels", "") for s in show], fontsize=8) axes[3].invert_yaxis() axes[3].set_xlim(0, 100) axes[3].set_xlabel("share of EMS pixels also mapped (%)") axes[3].set_title("Recall by EMS class", fontsize=8.5) axes[3].legend(fontsize=7, loc="lower right") axes[3].grid(axis="x", alpha=0.3) fig.savefig(OUT / "06-agreement-matrix.png") plt.close(fig) # Imagery-heavy figures: a 256-colour palette keeps them web-sized with no visible change for name in ("01-ems-reference.png", "02-sentinel-1-change.png", "04-sentinel-2-water-sediment.png"): with Image.open(OUT / name) as im: small = im.convert("RGB").quantize(256, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) small.save(OUT / name, optimize=True) print("figures: " + ", ".join(sorted(p.name for p in OUT.glob("*.png"))))