Source code: Flood damage, exposure and population affected in Python: the Valencia floods of October 2024
Runnable Python scripts, requirements and console output for the tutorial “Flood damage, exposure and population affected in Python: the Valencia floods…
Last updated
These are the exact scripts used to produce every figure and number in Flood damage, exposure and population affected in Python: the Valencia floods of October 2024. Download them, install the requirements into a fresh virtual environment and run them from this folder.
- flood_exposure.py
- requirements.txt
- console.txt: the console output recorded when we ran it
python -m venv .venv.venv\Scripts\activate # macOS/Linux: source .venv/bin/activatepip install -r requirements.txtpython flood_exposure.pyflood_exposure.py
"""Flood damage, exposure and population affected in Python: the Valencia DANA floods of 29 October 2024.
Part 3 of "GIS for disaster emergency response". The script downloads the Copernicus EMS Rapid Mappingproducts for activation EMSR773 (AOI03, Horta Sud: the flood delineation and the damage grading),Overture Maps buildings with DuckDB, GISCO municipal boundaries, INE municipal population (Padron,1 January 2024) and two 100 m population grids (JRC GHSL GHS-POP and WorldPop). It then counts thebuildings and people in the flood, checks the extent against the EMS damage grading, and summariseseverything per municipality in a table and a choropleth that responders can use.Run with: python flood_exposure.py"""import ioimport jsonimport platformimport sysimport zipfilefrom importlib.metadata import versionfrom pathlib import Path
import duckdbimport geopandas as gpdimport matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pyogrioimport rasterioimport rasterio.featuresimport requestsimport shapelyfrom matplotlib.colors import BoundaryNorm, ListedColormapfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patchfrom rasterio.merge import mergefrom rasterio.transform import Affinefrom rasterio.windows import from_bounds
HERE = Path(__file__).parentDATA, OUT = HERE / "data", HERE / "output"DATA.mkdir(exist_ok=True)OUT.mkdir(exist_ok=True)plt.rcParams.update({"figure.dpi": 150, "savefig.bbox": "tight", "font.size": 9})pd.set_option("display.width", 160)pd.set_option("display.max_columns", 20)
CRS = "EPSG:25830" # ETRS89 / UTM zone 30N: metres for areas and lengthsEMS_API = "https://rapidmapping.emergency.copernicus.eu/backend/dashboard-api/public-activations/?code=EMSR773"LAU_URL = "https://gisco-services.ec.europa.eu/distribution/v2/lau/shp/LAU_RG_01M_2024_4326.shp.zip"INE_URL = "https://servicios.ine.es/wstempus/js/ES/DATOS_TABLA/2903?nult=2&tip=AM" # Padron, Valencia provinceGHSL_URL = ("https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/GHSL/GHS_POP_GLOBE_R2023A/" "GHS_POP_E2025_GLOBE_R2023A_54009_100/V1-0/tiles/GHS_POP_E2025_GLOBE_R2023A_54009_100_V1_0_{tile}.zip")GHSL_TILES = ["R5_C18", "R5_C19"] # the Mollweide tile edge at x = -41 km runs through Horta SudWORLDPOP_URL = ("https://data.worldpop.org/GIS/Population/Global_2015_2030/R2025A/2024/ESP/v1/100m/" "constrained/esp_pop_2024_CN_100m_R2025A_v1.tif")GRADE_ORDER = ["Possibly damaged", "Damaged", "Destroyed"]NOT_HOMES = {"industrial", "commercial", "agricultural", "outbuilding", "civic", "education", "religious", "service", "transportation", "medical", "military", "entertainment"}CREDIT = ("Flood extent and damage grading: © European Union, Copernicus Emergency Management Service, EMSR773. " "Buildings: Overture Maps Foundation (OpenStreetMap, IGN). Boundaries: © EuroGeographics.")
def section(title: str) -> None: print(f"\n=== {title} ===")
def download(url: str, path: Path) -> Path: if not path.exists(): with requests.get(url, stream=True, timeout=300) as r: r.raise_for_status() with open(path, "wb") as f: for chunk in r.iter_content(1 << 20): f.write(chunk) return path
def read_ems(zip_path: Path, layer: str) -> gpd.GeoDataFrame: """Read one shapefile layer (e.g. 'observedEventA') from an EMS product zip, in metres.""" name = next(n for n in zipfile.ZipFile(zip_path).namelist() if f"_{layer}_" in n and n.endswith(".shp")) return gpd.read_file(f"zip://{zip_path.as_posix()}!{name}").to_crs(CRS)
def touches(geoms: gpd.GeoSeries, area) -> np.ndarray: """True where a geometry intersects `area`, via a spatial index on the area's parts (fast for many features).""" parts = gpd.GeoDataFrame(geometry=gpd.GeoSeries([area], crs=CRS).explode(index_parts=False).values, crs=CRS) hit = gpd.sjoin(gpd.GeoDataFrame(geometry=geoms.values, crs=CRS), parts, predicate="intersects").index.unique() return np.isin(np.arange(len(geoms)), hit)
section("versions")print(f"python {platform.python_version()} | geopandas {gpd.__version__} | duckdb {duckdb.__version__} | " f"rasterio {rasterio.__version__} | shapely {shapely.__version__} | pyogrio {pyogrio.__version__} | " f"numpy {np.__version__} | pandas {pd.__version__} | matplotlib {matplotlib.__version__}")
# ---------------------------------------------------------------------------- 1. Copernicus EMS productssection("Step 1: Copernicus EMS products for EMSR773, AOI03 Horta Sud")act_file = DATA / "emsr773.json"if not act_file.exists(): act_file.write_text(requests.get(EMS_API, timeout=60).text, encoding="utf-8")act = json.loads(act_file.read_text(encoding="utf-8"))["results"][0]print(f"{act['code']}: {act['name']} | event {act['eventTime']} UTC | activated {act['activationTime']} UTC")aoi03 = next(a for a in act["aois"] if a["number"] == 3)products = {}for p in aoi03["products"]: kind = {"DEL": "delineation", "GRA": "grading"}[p["type"]] images = ", ".join(sorted({f"{i['sensorName']} {i['acquisitionTime'][:16].replace('T', ' ')}" for i in p["images"]})) zpath = download(p["downloadPath"], DATA / Path(p["downloadPath"]).name) products[kind] = zpath print(f"{p['type']} {kind:<11} {zpath.name} ({zpath.stat().st_size / 1e6:.0f} MB) | imagery: {images}")
aoi = pd.concat([read_ems(products[k], "areaOfInterestA") for k in products]).union_all()flood_del = read_ems(products["delineation"], "observedEventA")flood_gra = read_ems(products["grading"], "observedEventA")grading = read_ems(products["grading"], "builtUpP")roads = read_ems(products["grading"], "transportationL")extents = {"delineation": flood_del.union_all(), "grading": flood_gra.union_all()}extents["union"] = shapely.union(extents["delineation"], extents["grading"])FLOOD = extents["union"]print(f"AOI03 (delineation + grading AOIs): {aoi.area / 1e6:.1f} km2")for name, g in [("delineation", flood_del), ("grading", flood_gra)]: by = g.dissolve("notation").area / 1e6 print(f"flood polygons in the {name} product: {len(g):,} | {extents[name].area / 1e6:.1f} km2 " f"({', '.join(f'{k.lower()} {v:.1f}' for k, v in by.items())})")print(f"overlap {shapely.intersection(extents['delineation'], extents['grading']).area / 1e6:.1f} km2 | " f"union {FLOOD.area / 1e6:.1f} km2")print(f"graded building points: {len(grading):,} | {grading.damage_gra.value_counts().reindex(GRADE_ORDER).to_dict()}")print("graded points inside each flood extent: " + " | ".join( f"{k} {touches(grading.geometry, v).mean():.0%}" for k, v in extents.items()))
# ---------------------------------------------------------------------------- 2. municipalities and populationsection("Step 2: municipalities (GISCO LAU 2024) and INE population (1 January 2024)")lau = gpd.read_file(f"zip://{download(LAU_URL, DATA / Path(LAU_URL).name).as_posix()}", bbox=(-0.75, 39.30, -0.30, 39.56))lau = lau[lau.CNTR_CODE == "ES"].to_crs(CRS)munis = lau[lau.intersects(aoi)].copy()munis["ine_code"] = munis.GISCO_ID.str[3:]munis["area_km2"] = munis.area / 1e6munis["share_in_aoi"] = munis.intersection(aoi).area / munis.area
ine_file = DATA / "ine_padron_valencia.json"if not ine_file.exists(): ine_file.write_text(requests.get(INE_URL, timeout=120).text, encoding="utf-8")rows = []for s in json.loads(ine_file.read_text(encoding="utf-8")): meta = {m["T3_Variable"]: m for m in s["MetaData"]} if "Municipios" in meta and meta["Sexo"]["Nombre"] == "Total": val = {d["Anyo"]: d["Valor"] for d in s["Data"]} rows.append((meta["Municipios"]["Codigo"], meta["Municipios"]["Nombre"], val.get(2024)))ine = pd.DataFrame(rows, columns=["ine_code", "ine_name", "pop_ine_2024"])munis = munis.merge(ine, on="ine_code", how="left").sort_values("share_in_aoi", ascending=False)munis["name"] = (munis.LAU_NAME.str.replace(r"^(.+), (l'|el|la)$", r"\2 \1", regex=True) .str.replace("l' ", "l'").str.split(" / ").str[0])print(f"{len(ine)} municipalities in Valencia province in the INE table; {len(munis)} touch AOI03; " f"INE population missing for {munis.pop_ine_2024.isna().sum()}")full = munis.share_in_aoi >= 0.9print(f"wholly or mostly (>= 90%) inside AOI03: {full.sum()} municipalities, {munis.pop_ine_2024[full].sum():,.0f} residents")print(f"partly inside: {', '.join(f'{n} {s:.0%}' for n, s in zip(munis["name"][~full], munis.share_in_aoi[~full]))}")
# ---------------------------------------------------------------------------- 3. Overture buildingssection("Step 3: Overture Maps buildings with DuckDB")bld_file = DATA / "overture_buildings.parquet"if not bld_file.exists(): release = requests.get("https://stac.overturemaps.org/catalog.json", timeout=60).json()["latest"] x0, y0, x1, y1 = gpd.GeoSeries([aoi.buffer(500)], crs=CRS).to_crs(4326).total_bounds con = duckdb.connect() con.sql("INSTALL spatial; LOAD spatial; INSTALL httpfs; LOAD httpfs; SET s3_region = 'us-west-2';") bbox_sql = f"bbox.xmin <= {x1} AND bbox.xmax >= {x0} AND bbox.ymin <= {y1} AND bbox.ymax >= {y0}" files = [r[0] for r in con.sql(f""" SELECT assets.aws.alternate.s3.href FROM read_parquet('https://stac.overturemaps.org/{release}/collections.parquet') WHERE collection = 'building' AND {bbox_sql}""").fetchall()] con.sql(f""" COPY (SELECT id, subtype, class, height, num_floors, list_filter(sources, lambda s: s.property = '')[1].dataset AS source, '{release}' AS release, geometry FROM read_parquet({files}) WHERE {bbox_sql}) TO '{bld_file.as_posix()}' (FORMAT parquet)""")bld = gpd.read_parquet(bld_file).to_crs(CRS)bld = bld[bld.geometry.is_valid & bld.geometry.geom_type.isin(["Polygon", "MultiPolygon"])].reset_index(drop=True)bld["footprint_m2"] = bld.areabld["floors"] = bld.num_floors.fillna(1).clip(1, 30)bld["home"] = ~bld.subtype.isin(NOT_HOMES) & (bld.footprint_m2 >= 30) # could hold residentsin_aoi = bld.representative_point().within(aoi)print(f"Overture release {bld.release.iloc[0]}: {len(bld):,} buildings in AOI03 + 500 m, {in_aoi.sum():,} inside AOI03")print("source of the footprint:", bld[in_aoi].source.value_counts().to_dict())print(f"with num_floors: {bld[in_aoi].num_floors.notna().mean():.0%} | with a subtype: " f"{bld[in_aoi].subtype.notna().mean():.0%} | could hold residents: {bld[in_aoi].home.mean():.0%}")
# ---------------------------------------------------------------------------- 4. buildings in the floodsection("Step 4: buildings in the flood extent")pts = bld.representative_point()bld["muni"] = gpd.sjoin(gpd.GeoDataFrame(geometry=pts, crs=CRS), munis[["name", "geometry"]], how="left", predicate="within")["name"].groupby(level=0).first()bld["in_aoi"] = in_aoifor name, ext in extents.items(): bld[f"in_{name}"] = touches(bld.geometry, ext)bld["flooded"] = bld.in_unioncentroid_in = touches(pts, FLOOD)print(f"footprint touches the flood: {bld.flooded.sum():,} buildings " f"({bld.footprint_m2[bld.flooded].sum() / 1e6:.2f} km2 of roof, " f"{(bld.footprint_m2 * bld.floors)[bld.flooded].sum() / 1e6:.2f} km2 of floor space)")print(f"centroid inside the flood instead: {centroid_in.sum():,} buildings")print(f"by flood extent: delineation only {bld.in_delineation.sum():,} | grading product {bld.in_grading.sum():,} | " f"union {bld.in_union.sum():,}")print("flooded buildings by Overture subtype:", bld[bld.flooded].subtype.fillna("(none)").value_counts().head(6).to_dict())
# match each EMS grading point to the Overture building it sits on (or the nearest one within 10 m)gp = gpd.sjoin(grading[["damage_gra", "obj_type", "geometry"]], bld[["geometry"]], how="left", predicate="within")gp = gp[~gp.index.duplicated()]miss = gp.index_right.isna()near = gpd.sjoin_nearest(grading[miss][["geometry"]], bld[["geometry"]], how="left", max_distance=10)gp.loc[miss, "index_right"] = near[~near.index.duplicated()].index_rightprint(f"EMS grading points on an Overture footprint: {(~miss).sum():,} of {len(gp):,}; " f"within 10 m: {gp.index_right.notna().sum() - (~miss).sum():,}; unmatched: {gp.index_right.isna().sum():,}")gp["rank"] = gp.damage_gra.map({g: i for i, g in enumerate(GRADE_ORDER)})worst = gp.dropna(subset=["index_right"]).groupby("index_right")["rank"].max()bld["ems_grade"] = pd.Series(np.array(GRADE_ORDER)[worst.to_numpy()], index=worst.index.astype(int))print("graded buildings:", bld.ems_grade.value_counts().reindex(GRADE_ORDER).to_dict())# the EMS interpreters also classed each graded building's use: drop the non-residential ones from the homesnon_res = gp[gp.obj_type.str.startswith("12-")].index_right.dropna().astype(int).unique()print(f"Overture 'homes' the EMS grading classes as non-residential: {bld.home.iloc[non_res].sum():,} (now excluded)")bld.loc[non_res, "home"] = False
print("\nshare of EMS-graded buildings inside each flood extent (a check on the extent):")graded = bld[bld.ems_grade.notna()]for name in extents: by_grade = graded.groupby("ems_grade")[f"in_{name}"].mean().reindex(GRADE_ORDER) print(f" {name:<12} all {graded[f'in_{name}'].mean():6.1%} | " + " | ".join(f"{g.lower()} {v:.1%}" for g, v in by_grade.items()))
roads["km"] = roads.length / 1000roads["muni"] = gpd.sjoin(gpd.GeoDataFrame(geometry=roads.representative_point(), crs=CRS), munis[["name", "geometry"]], how="left", predicate="within")["name"].groupby(level=0).first()km = roads.pivot_table(index="simplified", columns="damage_gra", values="km", aggfunc="sum", fill_value=0)print("\ngraded transport lines (km):")print(km.reindex(columns=GRADE_ORDER).round(1).sort_values("Damaged", ascending=False).to_string())
# ---------------------------------------------------------------------------- 5. population gridssection("Step 5: population in the flood (GHSL 100 m and WorldPop 3 arcsec)")
def read_grid(name: str, bounds_crs: str): """Population array, transform and CRS for the municipalities' extent (all of each municipality).""" b = munis.to_crs(bounds_crs).total_bounds if bounds_crs == "EPSG:4326": b = (b[0] - 0.01, b[1] - 0.01, b[2] + 0.01, b[3] + 0.01) else: # snap to the 100 m GHSL grid so merge() copies cells without resampling b = tuple(np.r_[np.floor(b[:2] / 100) * 100 - 200, np.ceil(b[2:] / 100) * 100 + 200]) if name == "GHSL": srcs = [rasterio.open(f"zip://{download(GHSL_URL.format(tile=t), DATA / Path(GHSL_URL.format(tile=t)).name).as_posix()}" f"!GHS_POP_E2025_GLOBE_R2023A_54009_100_V1_0_{t}.tif") for t in GHSL_TILES] arr, tr = merge(srcs, bounds=b, res=100, nodata=0) crs = srcs[0].crs for s in srcs: s.close() arr = arr[0] else: with rasterio.open(download(WORLDPOP_URL, DATA / Path(WORLDPOP_URL).name)) as s: w = from_bounds(*b, s.transform).round_offsets().round_lengths() arr, tr, crs = s.read(1, window=w), s.window_transform(w), s.crs arr = np.where(arr > 0, arr, 0).astype("float64") return arr, tr, crs
def fraction(geom, shape, transform, crs, k=10): """Share of each grid cell covered by geom, from a k x k supersampled rasterisation.""" g = gpd.GeoSeries([geom], crs=CRS).to_crs(crs).iloc[0] fine = rasterio.features.rasterize([(g, 1)], out_shape=(shape[0] * k, shape[1] * k), transform=transform * Affine.scale(1 / k), dtype="uint8") return fine.reshape(shape[0], k, shape[1], k).mean(axis=(1, 3))
grids, cells = {}, {}for name, crs in [("GHSL", "ESRI:54009"), ("WorldPop", "EPSG:4326")]: pop, tr, gcrs = read_grid(name, crs) m = munis.reset_index(drop=True).to_crs(gcrs) muni_id = rasterio.features.rasterize(((g, i + 1) for i, g in enumerate(m.geometry)), out_shape=pop.shape, transform=tr, dtype="int16") # cell centre decides the municipality f_flood = fraction(FLOOD, pop.shape, tr, gcrs) grids[name] = dict(pop=pop, transform=tr, crs=gcrs, flood=f_flood, muni=muni_id) # building-weighted (dasymetric) share: spread each cell's people over the floor space of its homes; # where a cell has buildings but no homes, over all its buildings; where it has none, over its area xy = bld.representative_point().to_crs(gcrs) rr, cc = (np.asarray(v) for v in rasterio.transform.rowcol(tr, xy.x.values, xy.y.values)) inside = (rr >= 0) & (rr < pop.shape[0]) & (cc >= 0) & (cc < pop.shape[1]) c = bld[inside].assign(cell=rr[inside] * pop.shape[1] + cc[inside], w=lambda d: d.footprint_m2 * d.floors) bw = f_flood.ravel().copy() for sel in [c, c[c.home]]: # homes overwrite all buildings tot = sel.groupby("cell").w.sum() share = (sel[sel.flooded].groupby("cell").w.sum() / tot).reindex(tot.index).fillna(0) bw[share.index.to_numpy()] = share.to_numpy() bw = bw.reshape(pop.shape) grids[name]["bw"] = bw # residents allocated to each home, for the building table c = c[c.home] c["residents"] = c.w / c.cell.map(tot) * pop.ravel()[c.cell.to_numpy()] bld.loc[c.index, f"res_{name}"] = c.residents cells[name] = pd.DataFrame({"muni": muni_id.ravel(), "pop": pop.ravel(), "area_w": (pop * f_flood).ravel(), "bldg_w": (pop * bw).ravel()}) res = abs(tr.a) * 111_320 * np.cos(np.radians(39.4)) if name == "WorldPop" else abs(tr.a) print(f"{name}: {pop.shape[1]} x {pop.shape[0]} cells (~{res:.0f} m) | total {pop.sum():,.0f} people | " f"in the flood: area-weighted {cells[name].area_w.sum():,.0f}, building-weighted {cells[name].bldg_w.sum():,.0f}") in_homes = bld.loc[bld.flooded & bld.home, f"res_{name}"].sum() print(f" of which in flooded homes {in_homes:,.0f}; in cells where Overture has no home {cells[name].bldg_w.sum() - in_homes:,.0f}")
# cross-check the grids against the INE register for whole municipalitiesm = munis.reset_index(drop=True)for name in grids: m[f"grid_{name}"] = cells[name].groupby("muni")["pop"].sum().reindex(range(1, len(m) + 1)).to_numpy() m[f"aff_{name}"] = cells[name].groupby("muni")["bldg_w"].sum().reindex(range(1, len(m) + 1)).fillna(0).to_numpy() m[f"aff_area_{name}"] = cells[name].groupby("muni")["area_w"].sum().reindex(range(1, len(m) + 1)).fillna(0).to_numpy()print("\ngrid totals against the INE Padron (1 January 2024), all", len(m), "municipalities:")for name in grids: d = m[f"grid_{name}"] / m.pop_ine_2024 - 1 print(f" {name:<8} sum {m[f'grid_{name}'].sum():,.0f} vs INE {m.pop_ine_2024.sum():,.0f} ({m[f'grid_{name}'].sum() / m.pop_ine_2024.sum() - 1:+.1%}) | " f"per municipality median {d.median():+.1%}, middle half {d.quantile(0.25):+.1%} to {d.quantile(0.75):+.1%} | " f"within 10%: {(d.abs() <= 0.1).sum()} of {len(d)}")
# ---------------------------------------------------------------------------- 6. municipality summarysection("Step 6: summary per municipality")flood_by_muni = gpd.overlay(munis[["name", "geometry"]], gpd.GeoDataFrame(geometry=[FLOOD], crs=CRS), how="intersection")m["flood_km2"] = m["name"].map(flood_by_muni.dissolve("name").area / 1e6).fillna(0)fb = bld[bld.flooded]m["bldg_flooded"] = m["name"].map(fb.groupby("muni").size()).fillna(0).astype(int)m["homes_flooded"] = m["name"].map(fb[fb.home].groupby("muni").size()).fillna(0).astype(int)dmg = bld[bld.ems_grade.isin(["Damaged", "Destroyed"])]m["ems_damaged_destroyed"] = m["name"].map(dmg.groupby("muni").size()).fillna(0).astype(int)m["ems_possibly"] = m["name"].map(bld[bld.ems_grade == "Possibly damaged"].groupby("muni").size()).fillna(0).astype(int)rd = roads[roads.damage_gra.isin(["Damaged", "Destroyed"]) & ~roads.simplified.isin(["Tracks"])]m["roads_damaged_km"] = m["name"].map(rd.groupby("muni").km.sum()).fillna(0)m["affected_low"] = m[["aff_GHSL", "aff_WorldPop"]].min(axis=1)m["affected_high"] = m[["aff_GHSL", "aff_WorldPop"]].max(axis=1)m["affected_mid"] = m[["aff_GHSL", "aff_WorldPop"]].mean(axis=1)m["affected_pct"] = 100 * m.affected_mid / m.pop_ine_2024in_homes = fb[fb.home].groupby("muni")[["res_GHSL", "res_WorldPop"]].sum()m["in_homes_mid"] = m["name"].map(in_homes.mean(axis=1)).fillna(0) # residents placed in identifiable flooded homes
table = m[m.flood_km2 > 0.01].sort_values("affected_mid", ascending=False)show = pd.DataFrame({ "municipality": table["name"], "INE pop": table.pop_ine_2024.map("{:,.0f}".format), "mapped": (100 * table.share_in_aoi).map("{:.0f}%".format), "flood km2": table.flood_km2.map("{:.2f}".format), "bldgs flooded": table.bldg_flooded.map("{:,}".format), "EMS dmg+destr": table.ems_damaged_destroyed.map("{:,}".format), "roads dmg km": table.roads_damaged_km.map("{:.1f}".format), "people (GHSL-WorldPop)": [f"{lo:,.0f}-{hi:,.0f}" for lo, hi in zip(table.affected_low, table.affected_high)], "% of pop": table.affected_pct.map("{:.0f}%".format), "in homes": (100 * table.in_homes_mid / table.affected_mid).map("{:.0f}%".format),})print(show.to_string(index=False))tot = m[["flood_km2", "bldg_flooded", "homes_flooded", "ems_damaged_destroyed", "roads_damaged_km", "aff_GHSL", "aff_WorldPop", "aff_area_GHSL", "aff_area_WorldPop"]].sum()print(f"\nAOI03 total: {tot.flood_km2:.1f} km2 flooded | {tot.bldg_flooded:,.0f} buildings ({tot.homes_flooded:,.0f} could hold residents) | " f"{tot.ems_damaged_destroyed:,.0f} graded damaged or destroyed | {tot.roads_damaged_km:.0f} km of roads and railways (not tracks) graded damaged or destroyed")print(f"people in flooded buildings: GHSL {tot.aff_GHSL:,.0f} | WorldPop {tot.aff_WorldPop:,.0f} " f"(area-weighted: GHSL {tot.aff_area_GHSL:,.0f} | WorldPop {tot.aff_area_WorldPop:,.0f})")
out = table[["ine_code", "name", "pop_ine_2024", "share_in_aoi", "flood_km2", "bldg_flooded", "homes_flooded", "ems_damaged_destroyed", "ems_possibly", "roads_damaged_km", "aff_GHSL", "aff_WorldPop", "affected_low", "affected_high", "affected_pct", "in_homes_mid"]].round(3)out.to_csv(OUT / "municipality_summary.csv", index=False, encoding="utf-8")out.to_excel(OUT / "municipality_summary.xlsx", index=False, sheet_name="EMSR773 AOI03")gpkg = OUT / "flood_exposure.gpkg"gpkg.unlink(missing_ok=True)gpd.GeoDataFrame(out.merge(m[["ine_code", "geometry"]], on="ine_code"), crs=CRS).to_file(gpkg, layer="municipalities")keep = ["id", "muni", "subtype", "num_floors", "footprint_m2", "home", "ems_grade", "res_GHSL", "res_WorldPop", "geometry"]fb_out = bld[bld.flooded][keep].round({"footprint_m2": 1, "res_GHSL": 2, "res_WorldPop": 2})fb_out.to_file(gpkg, layer="buildings_flooded")gpd.GeoDataFrame(geometry=[FLOOD], crs=CRS).to_file(gpkg, layer="flood_extent")print(f"\nwrote municipality_summary.csv/.xlsx and flood_exposure.gpkg " f"(layers: municipalities, buildings_flooded {len(fb_out):,}, flood_extent)")
# ---------------------------------------------------------------------------- figuressection("figures")ctx = munis.clip(aoi.buffer(1500).envelope)xmin, ymin, xmax, ymax = shapely.bounds(aoi.buffer(300))GRADE_COL = {"Possibly damaged": "#fdae61", "Damaged": "#d7301f", "Destroyed": "#67000d"}
def save(fig, name): for a in fig.axes: # geopandas labels map axes with the CRS axis names; the maps have no ticks if not a.get_xticks().size and not a.get_yticks().size: a.set_xlabel("") a.set_ylabel("") fig.savefig(OUT / name) plt.close(fig)
def base(ax, title): ctx.boundary.plot(ax=ax, color="#9a9a9a", lw=0.5, zorder=1) gpd.GeoSeries([aoi], crs=CRS).boundary.plot(ax=ax, color="black", lw=0.8, ls="--", zorder=5) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_title(title, fontsize=10) ax.set_xticks([]) ax.set_yticks([]) ax.plot([xmax - 5800, xmax - 800], [ymin + 900, ymin + 900], color="black", lw=2) ax.text(xmax - 3300, ymin + 1250, "5 km", ha="center", fontsize=8)
# 1: the two EMS extents and the graded buildingsfig, axes = plt.subplots(1, 2, figsize=(13, 5.3))fig.subplots_adjust(left=0.005, right=0.995, top=0.9, bottom=0.13, wspace=0.02)for ax, name, ttl in [(axes[0], "delineation", "Delineation product (DEL, v1)"), (axes[1], "grading", "Grading product (GRA, v2): observed flood")]: base(ax, ttl) bld[bld.in_aoi].plot(ax=ax, color="#d9d9d9", lw=0, zorder=2) gpd.GeoSeries([extents[name]], crs=CRS).plot(ax=ax, color="#2b8cbe", alpha=0.75, lw=0, zorder=3) for g, col in GRADE_COL.items(): grading[grading.damage_gra == g].plot(ax=ax, color=col, markersize=2.5, zorder=4) inside = touches(grading.geometry, extents[name]).mean() ax.text(0.01, 0.01, f"{extents[name].area / 1e6:.1f} km2 flooded\n{inside:.0%} of EMS graded points inside", transform=ax.transAxes, fontsize=8.5, va="bottom", bbox=dict(fc="white", ec="none", alpha=0.85))for n in ["Paiporta", "Torrent", "Catarroja", "Aldaia", "Quart de Poblet", "Riba-roja de Túria"]: p = munis[munis["name"] == n].representative_point().iloc[0] for ax in axes: ax.annotate(n, (p.x, p.y), fontsize=7.5, ha="center", color="#222222", zorder=6, bbox=dict(fc="white", ec="none", alpha=0.6, pad=0.5))handles = [Patch(color="#2b8cbe", alpha=0.75, label="EMS flood extent (flooded area and flood trace)"), Patch(color="#d9d9d9", label="Building (Overture Maps)")] + \ [Line2D([], [], marker="o", ls="", color=c, markersize=4, label=f"EMS grading: {g.lower()}") for g, c in GRADE_COL.items()] + \ [Line2D([], [], color="black", ls="--", lw=0.8, label="AOI03 Horta Sud")]fig.legend(handles=handles, loc="lower center", ncol=4, fontsize=8, frameon=False, bbox_to_anchor=(0.5, 0.02))fig.suptitle("Copernicus EMS EMSR773, Horta Sud: two flood extents from imagery of 31 October 2024", fontsize=11)fig.text(0.5, 0.0, CREDIT, ha="center", fontsize=6.5, color="#555555")save(fig, "01-ems-flood-extents.png")
# 2: building-level zoom on Paiporta, Benetusser and Massanassafig, ax = plt.subplots(figsize=(11, 9))cx, cy = munis[munis["name"] == "Paiporta"].representative_point().iloc[0].coords[0]zx0, zx1, zy0, zy1 = cx - 1300, cx + 2700, cy - 1900, cy + 1300z = bld.cx[zx0:zx1, zy0:zy1]gpd.GeoSeries([FLOOD], crs=CRS).clip((zx0, zy0, zx1, zy1)).plot(ax=ax, color="#9ecae1", lw=0, zorder=1)z[~z.flooded].plot(ax=ax, color="#d9d9d9", lw=0, zorder=2)z[z.flooded & z.ems_grade.isna()].plot(ax=ax, color="#3f6f9f", lw=0, zorder=3)for g, col in GRADE_COL.items(): sel = z[z.ems_grade == g] if len(sel): sel.plot(ax=ax, color=col, lw=0, zorder=4)rz = roads.cx[zx0:zx1, zy0:zy1]for g, lw in [("Possibly damaged", 0.6), ("Damaged", 1.3), ("Destroyed", 2.0)]: rz[rz.damage_gra == g].plot(ax=ax, color="black", lw=lw, zorder=5)munis.boundary.plot(ax=ax, color="#555555", lw=1, ls=":", zorder=6)for n in ["Paiporta", "Benetússer", "Massanassa", "Sedaví", "Picanya", "Alfafar"]: p = munis[munis["name"] == n].geometry.iloc[0].intersection(shapely.box(zx0, zy0, zx1, zy1)) if not p.is_empty: q = p.representative_point() ax.annotate(n, (q.x, q.y), fontsize=10, weight="bold", ha="center", color="#222222", zorder=7, bbox=dict(fc="white", ec="none", alpha=0.7, pad=1))ax.set_xlim(zx0, zx1)ax.set_ylim(zy0, zy1)ax.set_xticks([])ax.set_yticks([])ax.plot([zx1 - 700, zx1 - 200], [zy0 + 150, zy0 + 150], color="black", lw=2)ax.text(zx1 - 450, zy0 + 200, "500 m", ha="center", fontsize=8, bbox=dict(fc="white", ec="none", alpha=0.8, pad=1))handles = [Patch(color="#9ecae1", label="EMS flood extent"), Patch(color="#d9d9d9", label="Building, not in flood"), Patch(color="#3f6f9f", label="Building in flood, not graded")] + \ [Patch(color=c, label=f"EMS grading: {g.lower()}") for g, c in GRADE_COL.items()] + \ [Line2D([], [], color="black", lw=1.3, label="Road or railway graded damaged")]ax.legend(handles=handles, loc="upper left", fontsize=8, framealpha=0.9)ax.set_title("Paiporta and its neighbours along the Poyo ravine: buildings in the flood and EMS damage grading", fontsize=10)ax.text(0, -0.02, CREDIT, transform=ax.transAxes, fontsize=6.5, color="#555555", va="top")save(fig, "02-buildings-damage-paiporta.png")
# 3: the two population grids around the flood, and both against INEfig = plt.figure(figsize=(14, 5.6), layout="constrained")gs = fig.add_gridspec(1, 3, width_ratios=[1, 1, 0.75])map_axes = []for i, name in enumerate(grids): ax = fig.add_subplot(gs[i]) map_axes.append(ax) g = grids[name] a = gpd.GeoSeries([aoi], crs=CRS).to_crs(g["crs"]).iloc[0] bx = a.bounds dens = np.where(g["pop"] > 0, g["pop"], np.nan) h, w = dens.shape ext = [g["transform"].c, g["transform"].c + w * g["transform"].a, g["transform"].f + h * g["transform"].e, g["transform"].f] im = ax.imshow(dens, extent=ext, cmap="magma_r", norm=matplotlib.colors.LogNorm(1, 1000), interpolation="nearest") gpd.GeoSeries([FLOOD], crs=CRS).to_crs(g["crs"]).boundary.plot(ax=ax, color="#1f78b4", lw=0.5) gpd.GeoSeries([a], crs=CRS).boundary.plot(ax=ax, color="black", lw=0.8, ls="--") ax.set_xlim(bx[0], bx[2]) ax.set_ylim(bx[1], bx[3]) ax.set_xticks([]) ax.set_yticks([]) if name == "WorldPop": ax.set_aspect(1 / np.cos(np.radians(39.4))) ax.set_title(f"{name}: {cells[name].bldg_w.sum():,.0f} people in flooded buildings", fontsize=10)cb = fig.colorbar(im, ax=map_axes, shrink=0.5, location="bottom", pad=0.02, aspect=40)cb.set_label("people per grid cell (GHSL 100 m, WorldPop 3 arcsec), log scale; blue: flood extent outline")ax = fig.add_subplot(gs[2])for name, mk, col in [("GHSL", "o", "#1b9e77"), ("WorldPop", "s", "#7570b3")]: ax.scatter(m.pop_ine_2024 / 1000, m[f"grid_{name}"] / 1000, s=22, marker=mk, color=col, alpha=0.8, label=name)lim = [0.05, m.pop_ine_2024.max() / 1000 * 1.5]ax.plot(lim, lim, color="grey", lw=0.8, ls="--", label="1:1")ax.set_xscale("log")ax.set_yscale("log")ax.set_xlim(lim)ax.set_ylim(lim)ax.set_xlabel("INE Padron, 1 January 2024 (thousand residents)")ax.set_ylabel("sum of the grid (thousand people)")ax.set_title(f"Grid totals for the {len(m)} municipalities", fontsize=10)ax.legend(fontsize=8)fig.get_layout_engine().set(w_pad=0.1)fig.text(0.5, -0.02, "Population: JRC GHSL GHS-POP E2025 R2023A (CC BY 4.0); WorldPop 2024 constrained R2025A (CC BY 4.0); INE. " "Flood extent outline: © European Union, Copernicus EMS, EMSR773.", ha="center", fontsize=6.5, color="#555555")save(fig, "03-population-grids.png")
# 4: choropleth and bar chart for respondersfig, (ax, ax2) = plt.subplots(1, 2, figsize=(15, 6.2), gridspec_kw={"width_ratios": [1.3, 1]}, layout="constrained")choro = gpd.GeoDataFrame(m, crs=CRS).clip(aoi)bins = [0, 1, 5, 10, 20, 40, 100]cmap = ListedColormap(["#fff5eb", "#fdd0a2", "#fdae6b", "#f16913", "#d94801", "#7f2704"])cmap.set_over("#3f0f00")norm = BoundaryNorm(bins, cmap.N)choro.plot(ax=ax, column="affected_pct", cmap=cmap, norm=norm, edgecolor="#666666", lw=0.6, zorder=1)gpd.GeoSeries([FLOOD], crs=CRS).plot(ax=ax, facecolor="none", edgecolor="#08519c", lw=0.35, zorder=2)gpd.GeoSeries([aoi], crs=CRS).boundary.plot(ax=ax, color="black", lw=0.8, ls="--", zorder=3)top = table.head(14).reset_index(drop=True)for i, r in top.iterrows(): # numbers on the map match the bar chart p = choro.loc[choro["name"] == r["name"]].geometry.iloc[0].representative_point() ax.annotate(str(i + 1), (p.x, p.y), fontsize=7.5, weight="bold", ha="center", va="center", zorder=4, bbox=dict(boxstyle="circle,pad=0.25", fc="white", ec="#333333", lw=0.6))ax.set_xlim(xmin, xmax)ax.set_ylim(ymin, ymax)ax.set_xticks([])ax.set_yticks([])ax.plot([xmax - 5800, xmax - 800], [ymin + 900, ymin + 900], color="black", lw=2)ax.text(xmax - 3300, ymin + 1250, "5 km", ha="center", fontsize=8)sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)cb = fig.colorbar(sm, ax=ax, shrink=0.6, ticks=bins, location="bottom", pad=0.02, aspect=35, extend="max")cb.set_label("residents in flooded buildings, % of INE population (blue outline: flood extent)")ax.set_title("Share of each municipality's residents living in a flooded building", fontsize=10)y = np.arange(len(top))[::-1]ax2.barh(y, top.affected_mid, color="#f16913", height=0.6)ax2.errorbar(top.affected_mid, y, xerr=[top.affected_mid - top.affected_low, top.affected_high - top.affected_mid], fmt="none", ecolor="black", lw=1, capsize=3)ax2.set_yticks(y, [f"{i + 1}. {n}" + (f" ({p:.0%} mapped)" if p < 0.9 else "") for i, (n, p) in enumerate(zip(top["name"], top.share_in_aoi))])ax2.set_xlabel("residents in flooded buildings\n(bar: mean of GHSL and WorldPop; whiskers: the two estimates)")ax2.set_title("People affected by municipality, EMSR773 AOI03", fontsize=10)ax2.grid(axis="x", color="#e0e0e0")ax2.set_axisbelow(True)fig.text(0.5, -0.03, "Only the part of each municipality inside AOI03 (dashed) was mapped by Copernicus EMS. " + CREDIT, ha="center", fontsize=6.5, color="#555555")save(fig, "04-municipality-choropleth.png")for f in sorted(OUT.glob("*.png")): print(f"{f.name}: {plt.imread(f).shape[1]} x {plt.imread(f).shape[0]} px")