Post-disaster impact estimation
Dive deeper¶
How the picture changed as maps were delivered¶
One group of bars per Copernicus mapped area (AOI). Update bars show what a re-mapping added.
Copernicus figures by area¶
Latest product per area.
Where the damage is¶
Infrastructure in the damage zone¶
How this was produced¶
Question: who and what fall within the observed extent of an actual disaster?
Method (Copernicus EMS Rapid Mapping products, read through Montandon):
Impact zone — the latest Copernicus EMS grading layers of the chosen event; features graded Destroyed, Damaged or Possibly damaged are kept. Their bounding box (plus a small buffer) is the study extent.
Overlay — count damaged features and sum their footprint per subdivision; keep hospitals that intersect the damage; sum the population of every 100 m GHSL cell the damage touches.
Temporal evolution — measure the footprint of every published Copernicus EMS product, in delivery order.
Parameters used for this run¶
Sources and related records¶
Source
# --- Reserved parameters (injected by the Notebook Factory; defaults keep the notebook runnable standalone) ---
run_id = ""
inputs_dir = ""
output_dir = "outputs"
area = {} # {id, code, name, level, country, country_name, bbox}
area_geojson = "" # FeatureCollection with the target area
subdivisions_geojson = "" # FeatureCollection with the aggregation subdivisions
stac_item = {} # the run's STAC item (dict): a Copernicus EMS event from the Montandon catalog
stac_item_json = ""
stac_collection = ""
stac_api_url = "" # root of the item's catalog
stac_catalog_profile = "" # "generic" | "montandon"
filters = {} # the run's filter tags, e.g. {"hazard": ["flood"], "use_case": ["uc2"]}
hazard = ""
# --- User parameters ---
damage_grades = ["Destroyed", "Damaged", "Possibly damaged"] # which Copernicus damage grades count as impact
aggregation_level = 2
infrastructure_layers = ["health"]
bbox_buffer_deg = 0.05 # degrees added around the damage extent for the population and hospital queries
ghsl_epoch = 2020 # GHS-POP epoch: a five-year step from 1975 to 2030 (2025 and 2030 are model projections)Source
# Parameters
run_id = "ee6da11d-2e05-4e66-a7c7-5d8582e58ed0"
inputs_dir = "/app/data/work/ee6da11d-2e05-4e66-a7c7-5d8582e58ed0/inputs"
output_dir = "/app/data/work/ee6da11d-2e05-4e66-a7c7-5d8582e58ed0/outputs"
area = {"id": 1, "code": "NPL", "name": "Nepal", "level": 0, "country": "NPL", "country_name": "Nepal", "bbox": [80.0601, 26.3475, 88.204, 30.447]}
area_geojson = "/app/data/work/ee6da11d-2e05-4e66-a7c7-5d8582e58ed0/inputs/area.geojson"
subdivisions_geojson = "/app/data/work/ee6da11d-2e05-4e66-a7c7-5d8582e58ed0/inputs/subdivisions.geojson"
stac_item = {"id": "cems-event-EMSR927", "bbox": [84.351228, 27.675376, 85.380579, 28.279944], "type": "Feature", "links": [{"rel": "collection", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-events", "type": "application/json", "auth:refs": ["oidc"]}, {"rel": "parent", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-events", "type": "application/json", "auth:refs": ["oidc"]}, {"rel": "root", "href": "https://montandon-eoapi.ifrc.org/stac/", "type": "application/json"}, {"rel": "self", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-events/items/cems-event-EMSR927", "type": "application/geo+json", "auth:refs": ["oidc"]}, {"rel": "via", "href": "https://rapidmapping.emergency.copernicus.eu/EMSR927", "type": "text/html", "title": "CEMS EMSR927 activation"}, {"rel": "via", "href": "https://storymaps.arcgis.com/stories/f76baefadfa74d6d9a18265875f48870", "type": "text/html", "title": "CEMS situational report (StoryMap)"}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/gdacs-events/items/1104124-1", "type": "application/geo+json", "roles": ["event"], "title": "GDACS FL1104124 (episode 1)", "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/charter-events/items/charter-event-1052", "type": "application/geo+json", "roles": ["event"], "title": "Charter activation 1052", "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi01-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi01-landslide", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi02-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi02-landslide", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi03-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi03-landslide", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi04-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi05-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi05-landslide", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR927-aoi06-flood", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi01-dat-worldview3_20260827_0505_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi01-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi02-dat-legion_20260827_0505_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi02-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-dat-satellogic_20260827_0422_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-dat-blacksky_20260827_1209_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-dat-emsr927_aoi03_gramonit01_perusat1_20260827_0447_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-dat-emsr927_aoi03_gramonit01_resursp_20260828_0829_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi03-gra-m1", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi04-dat-17032dd9-a754-4e3b-841e-8bae8a4888f2", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi04-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-dat-pleiades_20260831_0527_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-dat-pneo_20260831_0501_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-dat-legion_20260905_0632_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-dat-pneo_20260905_0457_ortho", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi05-gra-m1", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi06-dat-2dce5040-d05f-4cdc-af40-294cc310cf4f", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-aoi06-gra", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR927-sr", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi01-gra-builtup", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi01-gra-landuse", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi01-gra-facilities", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi01-gra-transportation", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi01-gra-population", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi02-gra-builtup", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi02-gra-landuse", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi02-gra-facilities", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi02-gra-transportation", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi02-gra-population", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-builtup-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-landuse-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-facilities-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-transportation-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-population-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-builtup", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-landuse", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-facilities", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-transportation", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi03-gra-population", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-builtup-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-landuse-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-transportation-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-population-m1", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-builtup", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-landuse", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-transportation", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR927-aoi05-gra-population", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}], "assets": {}, "geometry": {"type": "Point", "coordinates": [85.35376299877846, 28.212231792029492]}, "collection": "cems-events", "properties": {"roles": ["event", "source"], "title": "Flood in Nepal", "datetime": "2026-08-25T22:00:00Z", "keywords": ["EMSR927", "Flash Flooding", "Flash flood", "Flood", "Meteorological & Hydrological", "Water-related"], "description": "On the 26 August 2026, a flash flood reportedly triggered by a Glacial Lake Outburst Flood (GLOF) in Nepal has caused significant damage in Rasuwa District. Copernicus EMS Rapid Mapping was requested to provide flood extent and damage assessment emergency mapping.", "auth:schemes": {"oidc": {"type": "openIdConnect", "openIdConnectUrl": "https://goadmin.ifrc.org/o/.well-known/openid-configuration"}}, "monty:etl_id": "e3ed3531-46b3-46e6-bfac-5caae004e58c", "monty:corr_id": "20260825-NPL-1061525-MH0603-1-GCDB", "monty:hazard_codes": ["MH0603", "FF", "nat-hyd-flo-fla"], "processing:version": "0.2.7", "monty:country_codes": ["NPL"], "processing:software": {"pystac-monty": "0.2.7"}, "monty:episode_number": 1}, "stac_version": "1.1.0", "stac_extensions": ["https://ifrcgo.org/monty-stac-extension/v1.3.0/schema.json", "https://stac-extensions.github.io/processing/v1.2.0/schema.json", "https://stac-extensions.github.io/authentication/v1.1.0/schema.json"]}
stac_item_json = "/app/data/work/ee6da11d-2e05-4e66-a7c7-5d8582e58ed0/inputs/stac_item.json"
stac_collection = "cems-events"
stac_api_url = "https://montandon-eoapi.ifrc.org/stac"
stac_catalog_profile = "montandon"
filters = {"hazard": ["flood"], "use_case": ["uc2"]}
hazard = "flood"
ghsl_epoch = 2020
damage_grades = ["Destroyed", "Damaged", "Possibly damaged"]
bbox_buffer_deg = 0.05
aggregation_level = 2
infrastructure_layers = ["health"]
Source
import json, os, re, tempfile, time, uuid, urllib.request, warnings
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
import requests
warnings.filterwarnings("ignore", message=".*geographic CRS.*")
Path(output_dir).mkdir(parents=True, exist_ok=True)
def read_geojson(path):
# Plain json rather than gpd.read_file: that loads pyogrio, and pyogrio loaded before rasterio's first remote
# read (the population window below) crashes the process: the two libraries bundle their own copy of GDAL.
return gpd.GeoDataFrame.from_features(json.loads(Path(path).read_text())["features"], crs=4326)
def load_area_and_subdivisions():
"""Read the boundaries prepared by the app. Fails loudly rather than inventing an area."""
if not (area_geojson and Path(area_geojson).exists()):
raise FileNotFoundError(f"area_geojson not found: {area_geojson!r}")
area_gdf = read_geojson(area_geojson)
has_subs = subdivisions_geojson and Path(subdivisions_geojson).exists()
return area_gdf, (read_geojson(subdivisions_geojson) if has_subs else area_gdf.copy())
area_gdf, subdivisions = load_area_and_subdivisions()
subdivisions = subdivisions[["code", "name", "level", "geometry"]].copy()
area_name = area.get("name") or area_gdf.iloc[0].get("name", "Area")
iso = str(area.get("country") or area_gdf.iloc[0]["country"]).upper()
print(f"Area: {area_name} ({iso}) · {len(subdivisions)} subdivisions at admin level {subdivisions['level'].iloc[0]}")
# The disaster: a Copernicus EMS activation from the Montandon STAC catalog (collection `cems-events`).
if not stac_item and stac_item_json and Path(stac_item_json).exists():
stac_item = json.loads(Path(stac_item_json).read_text())
if not stac_item:
raise ValueError("This template needs a Copernicus EMS event: pick an item of the `cems-events` collection")
event_collection = stac_item.get("collection") or stac_collection
if event_collection != "cems-events":
raise ValueError(f"Expected an item of the `cems-events` collection, got {event_collection!r}")
event_props = stac_item.get("properties", {})
ACTIVATION = stac_item["id"].removeprefix("cems-event-")
CORR_ID = event_props.get("monty:corr_id")
if not CORR_ID:
raise ValueError(f"{stac_item['id']} has no monty:corr_id")
event_countries = event_props.get("monty:country_codes") or []
if event_countries and iso not in event_countries:
raise ValueError(f"The selected area is in {iso}, but {ACTIVATION} affects {', '.join(event_countries)}. Pick an area in that country.")
print(f"Event: {event_props.get('title')} · {ACTIVATION} · {event_props.get('datetime')}")Area: Nepal (NPL) · 14 subdivisions at admin level 2
Event: Flood in Nepal · EMSR927 · 2026-08-25T22:00:00Z
1 · Datasets¶
Copernicus EMS products come from the Montandon STAC catalog: the event’s grading products (
cems-response) link to GeoJSON layers hosted by Copernicus, which are downloaded into a scratch cache. The figures Copernicus itself publishes for the event (cems-impacts) are shown for comparison.Administrative boundaries are the subdivisions chosen in the app.
Population is the GHSL GHS-POP R2023A 100 m grid (people per cell,
ghsl_epoch), read straight from Cloud-Optimized GeoTIFF tiles on the Source Cooperative mirror: only the window around the damage is transferred. Schiavina, Freire, Carioli and MacManus (2023), doi:10.2905/2FF68A52-5B5B-4A22-8F40-C41DA8332CFE.Hospitals are read straight from OpenStreetMap’s Layercake GeoParquet (
amenity=hospital), keeping the real footprint geometry (no local copy).
Source
import duckdb
import rasterio
import rasterio.windows
from rasterio.features import rasterize
from rasterio.windows import from_bounds, transform as window_transform
import shapely
from shapely.geometry import box
# Scratch space for files we download. Safe to delete: anything here can be fetched again.
# TMPDIR decides where that is, so a deployment can point it at a scratch volume.
CACHE_DIR = Path(tempfile.gettempdir()) / "notebook-factory-cache"
USER_AGENT = {"User-Agent": "notebook-factory (IFRC Montandon use case 2)"}
# GHS-POP R2023A: people per 100 m cell on the Mollweide grid (ESRI:54009), in 1000 km tiles named R{row}_C{col}.
# A Source Cooperative mirror of the JRC release (the same one the Use Case 1 notebook reads).
GHSL_URL = ("https://data.source.coop/nlebovits/ghsl/pop-{year}/pop-{year}-R{row}_C{col}/"
"GHS_POP_E{year}_GLOBE_R2023A_54009_100_V1_0_R{row}_C{col}.tif")
GHSL_EPOCHS = tuple(range(1975, 2031, 5))
GHSL_CRS = "ESRI:54009"
GHSL_X0, GHSL_Y0 = -18_041_000.0, 9_000_000.0 # top-left corner of the grid
GHSL_TILE_M, GHSL_CELL_M = 1_000_000.0, 100.0
GHSL_NODATA = -200.0
GHSL_MAX_PIXELS = 40_000_000 # about 1.5 GB of arrays while the window is analysed; larger damage extents stop with a message
LAYERCAKE_POIS = "https://data.openstreetmap.us/layercake/pois.parquet"
LAYER_LABELS = {"health": "Hospitals"}
LAYER_COLORS = {"health": [31, 36, 48]}
DAMAGE_COLUMN = "damage_gra" # attribute that holds the Copernicus damage grade in grading layers
if not damage_grades:
raise ValueError("Select at least one damage grade")
ghsl_epoch = int(ghsl_epoch)
if ghsl_epoch not in GHSL_EPOCHS:
raise ValueError(f"ghsl_epoch must be one of {', '.join(map(str, GHSL_EPOCHS))}")
# ---- Montandon STAC ---------------------------------------------------------------------------------------------
STAC_URL = (stac_api_url or os.environ.get("STAC_API_URL", "")).rstrip("/")
STAC_KEY = os.environ.get("STAC_API_KEY", "")
if not STAC_URL or not STAC_KEY:
raise RuntimeError("The Montandon catalog URL / API key are not available to the notebook (STAC_API_URL, STAC_API_KEY)")
STAC_HEADERS = {**USER_AGENT, "Authorization": f"Bearer {STAC_KEY}"}
def stac_search(collection, corr_id):
"""All items of `collection` that share the event's `monty:corr_id` (follows the `next` links)."""
body = {"collections": [collection], "limit": 100, "filter-lang": "cql2-json",
"filter": {"op": "=", "args": [{"property": "monty:corr_id"}, corr_id]}}
r = requests.post(f"{STAC_URL}/search", json=body, headers=STAC_HEADERS, timeout=120)
r.raise_for_status()
page, features = r.json(), []
for _ in range(50):
features += page.get("features", [])
nxt = next((l for l in page.get("links", []) if l.get("rel") == "next"), None)
if not nxt:
break
link_body = nxt.get("body") or {}
if (nxt.get("method") or "GET").upper() == "POST":
# the server's next-page body carries a token but not our filter, so merge it into the original request
r = requests.post(nxt["href"], json={**body, **link_body}, headers=STAC_HEADERS, timeout=120)
else:
r = requests.get(nxt["href"], headers=STAC_HEADERS, timeout=120)
r.raise_for_status()
page = r.json()
return features
hazards_items = stac_search("cems-hazards", CORR_ID)
responses = stac_search("cems-response", CORR_ID)
impacts_items = stac_search("cems-impacts", CORR_ID)
print(f"Montandon items for {ACTIVATION}: {len(hazards_items)} hazards · {len(responses)} responses · {len(impacts_items)} impacts")
def response_table(items):
rows = []
for it in items:
p = it.get("properties", {})
d = p.get("monty:response_detail") or {}
rows.append({"item": it["id"].removeprefix("cems-response-"), "datetime": p.get("datetime"), "type": d.get("type"),
"status": d.get("status"), "monitoring": d.get("monitoring_number")})
return pd.DataFrame(rows).sort_values("datetime", ascending=False)
response_table(responses).head(15)Montandon items for EMSR927: 10 hazards · 21 responses · 28 impacts
Published CEMS impact figures (for comparison)¶
These are the totals Copernicus publishes for the event, as Montandon cems-impacts items. They are not the
subdivision overlay computed below.
Source
def impact_stats_table(items):
rows = []
for it in items:
p = it.get("properties", {})
d = p.get("monty:impact_detail") or {}
rows.append({"item": it["id"].removeprefix("cems-impact-"), "category": d.get("category"), "type": d.get("type"),
"value": d.get("value"), "unit": d.get("unit"), "estimate": d.get("estimate_type")})
return pd.DataFrame(rows)
cems_published = impact_stats_table(impacts_items)
cems_published.to_csv(Path(output_dir) / "cems_published_impacts.csv", index=False)
cems_published.head(20)2 · Copernicus EMS layers¶
Every GeoJSON layer of the event’s response products is cached. The analysis then uses, for each area of interest and
theme, the latest monitoring step and skips notAnalysed extents. The damage grades chosen above are kept.
Source
CEMS_DIR = CACHE_DIR / "cems" / ACTIVATION
def download_geojson(url, dest):
"""Stream a Copernicus-hosted GeoJSON to a unique .part file, then rename it (runs can overlap).
The assets are on public object storage, so the Montandon token is not sent."""
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(f".{uuid.uuid4().hex}.part")
try:
with requests.get(url, stream=True, timeout=(30, 180), headers=USER_AGENT) as r:
r.raise_for_status()
with tmp.open("wb") as fh:
for chunk in r.iter_content(chunk_size=1024 * 256):
fh.write(chunk)
except Exception as e:
tmp.unlink(missing_ok=True)
raise RuntimeError(f"Could not download CEMS layer {url}: {e}") from e
tmp.replace(dest)
layers = [] # one row per downloaded GeoJSON layer
for item in responses:
p = item.get("properties", {})
detail = p.get("monty:response_detail") or {}
for name, asset in (item.get("assets") or {}).items():
href = asset.get("href") or ""
if not (href.startswith("http") and "geo+json" in (asset.get("type") or "").lower()):
continue
leaf = href.rstrip("/").split("/")[-1].split("?")[0]
path = CEMS_DIR / "".join(c if c.isalnum() or c in "-_." else "_" for c in leaf)
if not path.exists() or path.stat().st_size == 0:
download_geojson(href, path)
layers.append({"path": path, "file": path.name, "item": item["id"], "asset": name, "href": href,
"datetime": p.get("datetime"), "monitoring_number": detail.get("monitoring_number")})
if not layers:
raise RuntimeError(f"Montandon lists no GeoJSON layers for {ACTIVATION}: nothing to analyse")
layer_index = pd.DataFrame(layers).drop(columns="path")
layer_index.to_csv(Path(output_dir) / "cems_layers.csv", index=False)
print(f"Copernicus EMS layers found for {ACTIVATION}: {len(layers)}")
_AOI_RE = re.compile(r"AOI(\d+)", re.IGNORECASE)
_MONIT_RE = re.compile(r"MONIT(\d+)", re.IGNORECASE)
_THEME_RE = re.compile(r"(?:PRODUCT|MONIT\d+)_(.+)_v\d+$", re.IGNORECASE)
def layer_identity(path):
"""(aoi, monitoring_number, theme) parsed from a layer filename. A/P/L suffixes (area, point, line) share one theme."""
stem = path.stem
aoi_m, mon_m, theme_m = _AOI_RE.search(stem), _MONIT_RE.search(stem), _THEME_RE.search(stem)
token = theme_m.group(1) if theme_m else stem
family = token[:-1] if len(token) > 1 and token[-1] in {"A", "P", "L"} else token
return (aoi_m.group(1) if aoi_m else stem), (int(mon_m.group(1)) if mon_m else 0), family
def read_layer(path):
return read_geojson(path) # Copernicus layers are WGS84 GeoJSON
def load_latest_vectors():
"""The latest layer for each area of interest and theme (highest monitoring number); `notAnalysed` is skipped."""
grouped = {}
for row in layers:
aoi, monitoring, family = layer_identity(row["path"])
if family.lower() != "notanalysed":
grouped.setdefault((aoi, family), []).append((monitoring, row["path"]))
selected = [p for versions in grouped.values() for m, p in versions if m == max(v[0] for v in versions)]
if not selected:
raise RuntimeError(f"The cached CEMS layers for {ACTIVATION} contain no analysed layers")
return {p.stem: read_layer(p) for p in sorted(selected)}
def concat_layers(vector_layers):
frames = []
for name, layer in vector_layers.items():
frame = layer.to_crs("EPSG:4326").copy()
frame["copernicus_layer"] = name
frames.append(frame)
return gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs="EPSG:4326")
def filter_impact(frame):
"""Keep features whose damage grade is one of `damage_grades`. If there is no grade column at all (typical of a
flood or burnt-area extent) every geometry is kept."""
if DAMAGE_COLUMN not in frame.columns:
return frame.loc[frame.geometry.notna()].copy()
return frame.loc[frame.geometry.notna() & frame[DAMAGE_COLUMN].isin(list(damage_grades))].copy()
def bbox_from_geodataframe(frame, buffer_deg=0.05):
"""[west, south, east, north] in WGS84, padded by buffer_deg."""
west, south, east, north = frame.to_crs("EPSG:4326").total_bounds
return [float(west - buffer_deg), float(south - buffer_deg), float(east + buffer_deg), float(north + buffer_deg)]
vector_layers = load_latest_vectors()
impact_all = concat_layers(vector_layers)
impact = filter_impact(impact_all)
if impact.empty:
raise ValueError(f"No impact features remain after the damage filter ({', '.join(damage_grades)})")
BBOX = bbox_from_geodataframe(impact, float(bbox_buffer_deg))
admin = subdivisions[subdivisions.to_crs("EPSG:4326").intersects(box(*BBOX))].copy()
if admin.empty:
raise ValueError(f"No subdivision of {area_name} intersects the damage extent of {ACTIVATION}. Pick an area that covers it.")
print(f"Impact zone: layers used {len(vector_layers)} · features loaded {len(impact_all):,} · kept as damage ({', '.join(damage_grades)}) {len(impact):,}. "
f"Study extent (west, south, east, north): {', '.join(f'{v:.3f}' for v in BBOX)}. Subdivisions intersecting it: {len(admin)}.")Copernicus EMS layers found for EMSR927: 36
Impact zone: layers used 22 · features loaded 6,085 · kept as damage (Destroyed, Damaged, Possibly damaged) 5,357. Study extent (west, south, east, north): 84.893, 27.748, 85.429, 28.329. Subdivisions intersecting it: 2.
3 · Population and hospitals¶
Source
def read_ghsl_tile(url, minx, miny, maxx, maxy):
"""One GHSL tile's part of a window: (array, window transform, nodata), or None if the tile doesn't exist
(open sea). The host now and then answers with an error page instead of the file, so other failures are retried."""
for attempt in range(4):
try:
with rasterio.open(url) as src:
win = from_bounds(minx, miny, maxx, maxy, transform=src.transform).round_offsets().round_lengths()
win = win.intersection(rasterio.windows.Window(0, 0, src.width, src.height))
if win.width <= 0 or win.height <= 0:
return None
return src.read(1, window=win), src.window_transform(win), src.nodata
except rasterio.errors.RasterioIOError as e:
if "404" in str(e):
return None
if attempt == 3:
raise RuntimeError(f"Cannot read GHSL population tile {url}: {e}") from e
time.sleep(3 * (attempt + 1))
def fetch_ghsl_population(bbox, year, destination):
"""Write the GHS-POP window around a WGS84 box (west, south, east, north) as a GeoTIFF in ESRI:54009 (people per 100 m cell).
Only the part of each 1000 km tile the box touches is transferred."""
west, south, east, north = bbox
# Meridians curve on the Mollweide grid: take the envelope of the box edges, sampled, then snap it to the 100 m cells.
edges = shapely.segmentize(box(west, south, east, north), (east - west) / 16)
bx0, by0, bx1, by1 = gpd.GeoSeries([edges], crs=4326).to_crs(GHSL_CRS).total_bounds
minx = GHSL_X0 + np.floor((bx0 - GHSL_X0) / GHSL_CELL_M) * GHSL_CELL_M
maxx = GHSL_X0 + np.ceil((bx1 - GHSL_X0) / GHSL_CELL_M) * GHSL_CELL_M
maxy = GHSL_Y0 - np.floor((GHSL_Y0 - by1) / GHSL_CELL_M) * GHSL_CELL_M
miny = GHSL_Y0 - np.ceil((GHSL_Y0 - by0) / GHSL_CELL_M) * GHSL_CELL_M
width, height = int(round((maxx - minx) / GHSL_CELL_M)), int(round((maxy - miny) / GHSL_CELL_M))
if width * height > GHSL_MAX_PIXELS:
raise ValueError(f"The population window is {width} x {height} cells of 100 m; the damage extent is too large for this notebook")
mosaic = np.full((height, width), GHSL_NODATA, dtype="float32")
rows = range(int((GHSL_Y0 - maxy) // GHSL_TILE_M) + 1, int((GHSL_Y0 - miny - 1) // GHSL_TILE_M) + 2)
cols = range(int((minx - GHSL_X0) // GHSL_TILE_M) + 1, int((maxx - 1 - GHSL_X0) // GHSL_TILE_M) + 2)
found = 0
with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif", GDAL_HTTP_MAX_RETRY="5", GDAL_HTTP_RETRY_DELAY="2"):
for row in rows:
for col in cols:
got = read_ghsl_tile(GHSL_URL.format(year=year, row=row, col=col), minx, miny, maxx, maxy)
if got is None:
continue
data, tf, _ = got
c0, r0 = int(round((tf.c - minx) / GHSL_CELL_M)), int(round((maxy - tf.f) / GHSL_CELL_M))
mosaic[r0:r0 + data.shape[0], c0:c0 + data.shape[1]] = data
found += 1
if found == 0:
raise RuntimeError(f"No GHSL population tile covers the damage extent {[round(v, 3) for v in bbox]} (epoch {year})")
destination.parent.mkdir(parents=True, exist_ok=True)
with rasterio.open(destination, "w", driver="GTiff", height=height, width=width, count=1, dtype="float32", crs=GHSL_CRS,
transform=rasterio.transform.from_origin(minx, maxy, GHSL_CELL_M, GHSL_CELL_M), nodata=GHSL_NODATA, compress="deflate") as dst:
dst.write(mosaic, 1)
return found
POPULATION_RASTER = CACHE_DIR / "uc2" / f"population_{uuid.uuid4().hex}.tif" # this run's window; removed at the end
_t0 = time.time()
n_tiles = fetch_ghsl_population(BBOX, ghsl_epoch, POPULATION_RASTER)
print(f"GHS-POP {ghsl_epoch}: {n_tiles} tile(s) read in {time.time() - _t0:.0f}s")
def load_layercake_hospitals(bbox):
"""OSM hospitals (amenity=hospital) inside bbox (xmin, ymin, xmax, ymax) from Layercake's POIs layer, via DuckDB
range reads. The real OSM geometry is kept (points and building outlines), so the overlay with the damage
layers intersects footprints, not just a point per facility."""
xmin, ymin, xmax, ymax = bbox
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs;")
df = con.execute(f"""
SELECT type AS osm_type, id AS osm_id, name[1] AS name, names['en'][1] AS name_en, ST_AsWKB(geometry) AS wkb
FROM read_parquet('{LAYERCAKE_POIS}')
WHERE bbox.xmin <= {xmax} AND bbox.xmax >= {xmin} AND bbox.ymin <= {ymax} AND bbox.ymax >= {ymin}
AND amenity = 'hospital'
""").df()
geometry = gpd.GeoSeries.from_wkb(df["wkb"].map(bytes), crs=4326)
out = gpd.GeoDataFrame(df.drop(columns="wkb"), geometry=geometry, crs=4326)
out["infra_type"] = "hospital"
return out.drop_duplicates(subset=["osm_id", "osm_type"]).reset_index(drop=True)
def layercake_last_modified():
"""When the Layercake file was last rebuilt (HTTP Last-Modified). This is Layercake's update time,
not the date of the OpenStreetMap data inside it, which is probably a little older."""
try:
req = urllib.request.Request(LAYERCAKE_POIS, method="HEAD", headers={"User-Agent": "notebook-factory"}) # default urllib UA gets a 403
with urllib.request.urlopen(req, timeout=30) as r:
return r.headers.get("Last-Modified", "unknown")
except Exception:
return "unknown"
INFRASTRUCTURE = {"health": load_layercake_hospitals} # layer -> loader(bbox) returning a GeoDataFrame
frames = []
for layer_name in infrastructure_layers:
if layer_name not in INFRASTRUCTURE:
raise ValueError(f"No dataset for infrastructure layer {layer_name!r} yet")
frames.append(INFRASTRUCTURE[layer_name](tuple(BBOX)))
infrastructure = (gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs=4326) if frames else
gpd.GeoDataFrame(columns=["osm_id", "osm_type", "infra_type", "name", "name_en", "geometry"], geometry="geometry", crs=4326))
print(f"Infrastructure features in the study extent ({', '.join(infrastructure_layers)}): {len(infrastructure):,}")GHS-POP 2020: 1 tile(s) read in 6s
Infrastructure features in the study extent (health): 39
4 · Exposure by subdivision¶
For each subdivision: the number of damaged features, their footprint area, and the population of the 100 m GHSL cells the damage touches. Footprint area is measured in a local metric projection; points and lines have no area.
Source
ID_COL, NAME_COL = "code", "name"
def choose_analysis_crs(gdf):
"""A local UTM CRS from the geometry centroid, for metric calculations."""
if gdf.empty or gdf.crs is None:
raise ValueError("A non-empty GeoDataFrame with a CRS is required")
return gdf.estimate_utm_crs().to_string()
def summarize_impact_by_admin(impact, admin, *, target_crs):
"""One row per subdivision with damaged-feature counts and footprint area."""
admin_metric = admin.to_crs(target_crs).copy()
if impact.empty:
summary = admin_metric.copy()
summary["impact_feature_count"] = 0
summary["impact_area_km2"] = 0.0
return summary.to_crs("EPSG:4326")
# Spatial join in metres, then count features and sum footprint area per subdivision.
impact_metric = impact.to_crs(target_crs).copy()
impact_metric["_impact_area_m2"] = impact_metric.geometry.area
joined = gpd.sjoin(impact_metric[["_impact_area_m2", "geometry"]], admin_metric[[ID_COL, NAME_COL, "geometry"]],
predicate="intersects", how="inner")
stats = (joined.groupby(ID_COL, dropna=False)
.agg(impact_feature_count=("_impact_area_m2", "count"), impact_area_km2=("_impact_area_m2", "sum"))
.reset_index())
stats["impact_area_km2"] = stats["impact_area_km2"] / 1_000_000
summary = admin_metric.merge(stats, on=ID_COL, how="left")
summary["impact_feature_count"] = summary["impact_feature_count"].fillna(0).astype(int)
summary["impact_area_km2"] = summary["impact_area_km2"].fillna(0.0)
return summary.to_crs("EPSG:4326")
def clip_features_to_impact(features, impact):
"""Keep infrastructure features that intersect the impact layer."""
if features.empty or impact.empty:
return features.iloc[0:0].copy()
left = features.loc[features.geometry.notna()].copy()
right = impact.to_crs(left.crs)[["geometry"]]
hits = gpd.sjoin(left, right, predicate="intersects", how="inner")
return left.loc[left.index.isin(hits.index.unique())].copy()
exposed_cells = {} # the damage mask of the last population_under_impact call (cells, transform, CRS), for the map
def population_under_impact(admin, impact, raster_path, *, all_touched=True):
"""Sum population raster cells that touch the impact mask, by subdivision.
GHS-POP cells are 100 m. A building footprint can still be smaller than one cell, so ``all_touched`` counts a cell
when any damaged feature overlaps it. The raster is on the Mollweide grid, so the subdivisions are densified in
degrees first to keep their edges true once reprojected."""
if impact.empty:
return pd.DataFrame({ID_COL: admin[ID_COL], "pop_total": np.nan, "pop_exposed": 0.0})
with rasterio.open(raster_path) as src:
# Clip the raster to the damage bounding box (a rectangle in degrees, as before), then mask cells that touch damage.
# On the Mollweide grid that rectangle is slanted, so read its envelope and zero the cells outside the rectangle.
minx, miny, maxx, maxy = impact.total_bounds
extent = gpd.GeoSeries([shapely.segmentize(box(minx - 1e-6, miny - 1e-6, maxx + 1e-6, maxy + 1e-6), 0.005)], crs=impact.crs).to_crs(src.crs)
window = from_bounds(*extent.total_bounds, transform=src.transform).round_offsets().round_lengths()
window = window.intersection(rasterio.windows.Window(0, 0, src.width, src.height))
if window.width <= 0 or window.height <= 0:
return pd.DataFrame({ID_COL: admin[ID_COL], "pop_total": np.nan, "pop_exposed": 0.0})
transform = window_transform(window, src.transform)
pop = src.read(1, window=window).astype("float64")
if src.nodata is not None:
pop = np.where(pop == src.nodata, 0.0, pop)
pop = np.nan_to_num(pop, nan=0.0)
shapes = [(g, 1) for g in impact.to_crs(src.crs).geometry if g is not None and not g.is_empty]
mask = rasterize(shapes, out_shape=pop.shape, transform=transform, fill=0, dtype="uint8", all_touched=all_touched)
exposed = pop * mask # 0 outside the damage mask
exposed_cells.update(mask=mask.astype(bool), people=exposed.astype("float32"), transform=transform, crs=src.crs)
pop = np.where(rasterize([(extent.iloc[0], 1)], out_shape=pop.shape, transform=transform, fill=0, dtype="uint8").astype(bool), pop, 0.0) # total: inside the rectangle only
zones = admin.assign(geometry=shapely.segmentize(admin.geometry.values, 0.01)).to_crs(src.crs)
# Label every cell with its subdivision (cell centre inside the polygon), then add up people per label.
labels = rasterize([(g, i + 1) for i, g in enumerate(zones.geometry) if g is not None and not g.is_empty],
out_shape=pop.shape, transform=transform, fill=0, dtype="int32").ravel()
keep = [i for i, g in enumerate(zones.geometry) if g is not None and not g.is_empty]
n_zones = len(zones)
total, in_damage = np.zeros(n_zones), np.zeros(n_zones)
total[keep] = np.bincount(labels, weights=pop.ravel(), minlength=len(keep) + 1)[1:]
in_damage[keep] = np.bincount(labels, weights=exposed.ravel(), minlength=len(keep) + 1)[1:]
return pd.DataFrame({ID_COL: admin[ID_COL].values, "pop_total": total, "pop_exposed": in_damage})
analysis_crs = choose_analysis_crs(admin)
impact_admin = summarize_impact_by_admin(impact, admin, target_crs=analysis_crs)
exposed_infra = clip_features_to_impact(infrastructure, impact)
population = population_under_impact(admin, impact, POPULATION_RASTER)
impact_admin = impact_admin.merge(population, on=ID_COL, how="left")
impact_admin["pop_exposed"] = impact_admin["pop_exposed"].fillna(0)
impact_admin["pop_total"] = impact_admin["pop_total"].fillna(0)
POPULATION_RASTER.unlink(missing_ok=True)
table_cols = [ID_COL, NAME_COL, "impact_feature_count", "impact_area_km2", "pop_exposed", "pop_total"]
ranked = impact_admin.drop(columns="geometry").sort_values("impact_feature_count", ascending=False)[table_cols]
ranked.to_csv(Path(output_dir) / "impact_by_admin.csv", index=False)
impact_admin.to_file(Path(output_dir) / "impact_by_admin.geojson", driver="GeoJSON")
exposed_infra.assign(geometry_type=exposed_infra.geom_type).drop(columns="geometry").to_csv(Path(output_dir) / "infrastructure_in_impact.csv", index=False)
print(f"Measured in {analysis_crs}: damaged features {int(impact_admin['impact_feature_count'].sum()):,} · subdivisions {len(impact_admin)} · "
f"people in the 100 m cells the damage touches {round(float(impact_admin['pop_exposed'].sum())):,} · "
f"infrastructure features in the damage zone {len(exposed_infra):,}.")
print(f"Hospitals: OpenStreetMap via Layercake, file last updated {layercake_last_modified()} "
"(Layercake's build date, not the date of the OSM data beneath it)")
(ranked.head(25).style
.format({"impact_area_km2": "{:,.2f}", "pop_exposed": "{:,.0f}", "pop_total": "{:,.0f}"})
.background_gradient(subset=["impact_feature_count"], cmap="OrRd") # same ramps as the map choropleths
.background_gradient(subset=["pop_exposed"], cmap="PuBu"))Measured in EPSG:32645: damaged features 5,357 · subdivisions 2 · people in the 100 m cells the damage touches 11,359 · infrastructure features in the damage zone 1.
Hospitals: OpenStreetMap via Layercake, file last updated Sun, 22 Nov 2026 15:52:36 GMT (Layercake's build date, not the date of the OSM data beneath it)
Results¶
The figures, map and charts are in the Overview above. These cells build the map layers.
Source
# Visualisation: lonboard for maps, manywidgets for charts, controls and stats.
# All of these are anywidgets, so they stay interactive in the published (kernel-free) page.
from matplotlib import colormaps
import base64, io
from PIL import Image
from rasterio.warp import Resampling, reproject, transform_bounds
from lonboard import BitmapLayer, Map, PathLayer, PolygonLayer, ScatterplotLayer
from manywidgets import Chart, Column, Legend, Row, Stat
from manywidgets.lonboard import LayerToggle
def colors_for(values, cmap="OrRd", vmin=None, vmax=None):
v = np.asarray(values, dtype=float)
vmin = np.nanmin(v) if vmin is None else vmin
vmax = np.nanmax(v) if vmax is None else vmax
norm = (v - vmin) / (vmax - vmin) if vmax > vmin else np.zeros_like(v)
rgba = colormaps[cmap](np.nan_to_num(norm))
return (rgba * 255).astype(np.uint8)
def legend_for(cmap, vmin, vmax, title="", n=5, fmt="{:.0f}"):
stops = np.linspace(vmin, vmax, n)
rgb = colors_for(stops, cmap, vmin, vmax)[:, :3]
return Legend(entries=[[[int(c) for c in rgb[i]], fmt.format(stops[i])] for i in range(n)], title=title)
def bar_chart(names, values, title, y_label, color="#E4572E"):
chart = Chart(chart_type="bar", title=title, y_label=y_label, height=max(280, 22 * len(names) + 120), legend_enabled=False)
chart.set_options(scales={"x": {"type": "category", "ticks": {"autoSkip": False, "maxRotation": 60, "minRotation": 30}}})
chart.add_series(x=[str(n) for n in names], y=[float(v) for v in values], name=y_label, series_type="bar", color=color)
return chart
def fmt_int(v):
return f"{float(v):,.0f}"
Map — damaged features and exposed population¶
The map is in the Overview; expand it for the layer list.
The damaged features themselves (points, lines and areas, coloured by damage grade) and the hospitals they touch. The subdivision choropleths (damaged-feature count, exposed population) are in the layer list and start switched off. Population is a settlement-scale estimate: every 100 m cell touched by a damaged feature is counted in full.
Source
def with_alpha(rgba, values):
out = rgba.copy()
out[np.asarray(values) <= 0, 3] = 25 # subdivisions without damage stay faint
return out
cmax = max(float(impact_admin["impact_feature_count"].max()), 1.0)
pmax = max(float(impact_admin["pop_exposed"].max()), 1.0)
cols = ["name", "impact_feature_count", "pop_exposed", "geometry"]
count_layer = PolygonLayer.from_geopandas(impact_admin[cols], get_fill_color=with_alpha(colors_for(impact_admin["impact_feature_count"], "OrRd", 0, cmax), impact_admin["impact_feature_count"]),
get_line_color=[60, 60, 60], line_width_min_pixels=1, opacity=0.75)
pop_layer = PolygonLayer.from_geopandas(impact_admin[cols], get_fill_color=with_alpha(colors_for(impact_admin["pop_exposed"], "PuBu", 0, pmax), impact_admin["pop_exposed"]),
get_line_color=[60, 60, 60], line_width_min_pixels=1, opacity=0.75, visible=False)
count_layer.visible = False # the choropleths start off: the damaged features below are the main picture
boundary_layer = PolygonLayer.from_geopandas(impact_admin[["name", "geometry"]], filled=False, stroked=True,
get_line_color=[70, 70, 70, 200], line_width_min_pixels=1)
# The damaged features themselves, coloured by damage grade (blue when the layer has no grade).
GRADE_COLORS = {"Destroyed": [153, 0, 13, 230], "Damaged": [239, 101, 72, 230], "Possibly damaged": [254, 196, 79, 230]}
UNGRADED = [49, 130, 189, 150]
EXTENT_COLOR = [49, 130, 189, 28]
def grade_colors(frame):
grades = frame[DAMAGE_COLUMN] if DAMAGE_COLUMN in frame.columns else [None] * len(frame)
return np.array([GRADE_COLORS.get(g, UNGRADED) for g in grades], dtype=np.uint8).reshape(-1, 4)
POLYGONS = ["Polygon", "MultiPolygon"]
# The observed event (observedEvent* layers: the flood or burnt-area extent seen on imagery) gets its own layer, on by default.
observed_rows = impact_all["copernicus_layer"].map(lambda n: layer_identity(Path(n))[2] == "observedEvent")
observed = impact_all[observed_rows & impact_all.geometry.notna() & impact_all.geom_type.isin(POLYGONS)][["geometry"]]
observed = observed.assign(geometry=observed.geometry.simplify(0.0001, preserve_topology=True)) # display only: ~10 m
kinds = impact.geom_type
keep = [c for c in (DAMAGE_COLUMN,) if c in impact.columns] + ["geometry"]
points = impact[kinds.isin(["Point", "MultiPoint"])][keep]
lines = impact[kinds.isin(["LineString", "MultiLineString"])][keep]
areas = impact[kinds.isin(POLYGONS) & ~observed_rows.reindex(impact.index, fill_value=False)][keep] # observed event is drawn on its own
feature_layers = {} # label -> layer, drawn bottom to top
if DAMAGE_COLUMN in impact_all.columns:
# Other layers without a damage grade (modelled or maximum flood extent, flood depth, ground movement, ...). Drawn for
# context, off by default; they are not in the statistics.
graded = impact_all.groupby("copernicus_layer")[DAMAGE_COLUMN].transform(lambda s: s.notna().any())
extent = impact_all[~graded & ~observed_rows & impact_all.geometry.notna() & impact_all.geom_type.isin(POLYGONS)][["geometry"]]
if len(extent):
feature_layers["Other extent layers (not in the statistics)"] = PolygonLayer.from_geopandas(
extent, get_fill_color=EXTENT_COLOR, get_line_color=[49, 130, 189, 110], line_width_min_pixels=1, visible=False)
if len(areas):
feature_layers["Damaged areas"] = PolygonLayer.from_geopandas(
areas, get_fill_color=grade_colors(areas), get_line_color=[60, 60, 60, 70], line_width_min_pixels=0.5, opacity=0.85)
if len(observed):
feature_layers["Observed event (flood or burnt-area extent)"] = PolygonLayer.from_geopandas(
observed, get_fill_color=[31, 120, 180, 110], get_line_color=[31, 120, 180, 220], line_width_min_pixels=1)
if len(lines):
feature_layers["Damaged lines (roads, ...)"] = PathLayer.from_geopandas(lines, get_color=grade_colors(lines), get_width=2, width_min_pixels=2)
if len(points):
feature_layers["Damaged points (buildings, ...)"] = ScatterplotLayer.from_geopandas(
points, get_fill_color=grade_colors(points), get_radius=15, radius_min_pixels=3, radius_max_pixels=12)
fac_layers = {}
for name in infrastructure_layers:
fx = exposed_infra[exposed_infra.infra_type == "hospital"]
if len(fx):
marks = fx[["geometry"]].copy()
marks["geometry"] = marks.geometry.representative_point() # footprints are drawn as one point each
fac_layers[name] = ScatterplotLayer.from_geopandas(marks, get_fill_color=LAYER_COLORS[name], radius_min_pixels=7,
stroked=True, get_line_color=[255, 255, 255], line_width_min_pixels=1.5)
# Open on the damage, not on the whole subdivision.
west, south, east, north = impact.total_bounds
pad_x, pad_y = max((east - west) * 0.1, 0.005), max((north - south) * 0.1, 0.005)
west, east, south, north = west - pad_x, east + pad_x, south - pad_y, north + pad_y
zoom = float(np.clip(min(np.log2(640 * 360 / (512 * (east - west))), np.log2(400 * 170 / (512 * (north - south)))), 2, 16))
view = {"longitude": (west + east) / 2, "latitude": (south + north) / 2, "zoom": zoom}
# The cells whose people are added up as "population in damaged cells", as one image under everything else (off by default).
# Cells are shaded by the people in them (log scale); touched cells with fewer than one person are a faint tint, so the damage
# footprint stays visible even where nobody lives. The grid is 100 m Mollweide: resample to degrees, keeping the largest value
# where the image is coarser than the grid (display only), and send it as an embedded PNG.
cells_layer, cells_legend = None, None
if exposed_cells and exposed_cells["mask"].any():
mask_m, people_m, tf_m, crs_m = exposed_cells["mask"], exposed_cells["people"], exposed_cells["transform"], exposed_cells["crs"]
cw, cs, ce, cn = transform_bounds(crs_m, "EPSG:4326", *rasterio.transform.array_bounds(*mask_m.shape, tf_m))
res = max((ce - cw) / 2000, (cn - cs) / 2000, 0.0009) # at most ~2000 px across; ~100 m at the finest
cols_px, rows_px = int(np.ceil((ce - cw) / res)), int(np.ceil((cn - cs) / res))
dst_tf = rasterio.transform.from_origin(cw, cn, res, res)
touched, people = np.zeros((rows_px, cols_px), dtype="uint8"), np.zeros((rows_px, cols_px), dtype="float32")
for src_arr, dst_arr in ((mask_m.astype("uint8"), touched), (people_m, people)):
reproject(src_arr, dst_arr, src_transform=tf_m, src_crs=crs_m, dst_transform=dst_tf, dst_crs="EPSG:4326", resampling=Resampling.max)
top = max(float(people.max()), 1.0)
def cell_rgb(p):
rgba_ramp = np.asarray(colormaps["Purples"](0.2 + 0.8 * np.log10(1 + np.asarray(p, dtype=float)) / np.log10(1 + top)))
return (rgba_ramp[..., :3] * 255).astype(np.uint8)
rgba = np.zeros((rows_px, cols_px, 4), dtype=np.uint8)
rgba[touched > 0] = [123, 50, 148, 45]
has_people = people >= 1
rgba[has_people, :3] = cell_rgb(people[has_people])
rgba[has_people, 3] = 210
png = io.BytesIO()
Image.fromarray(rgba, "RGBA").save(png, format="PNG")
cells_layer = BitmapLayer(image="data:image/png;base64," + base64.b64encode(png.getvalue()).decode(),
bounds=[cw, cs, ce, cn], visible=False)
stops = [s for s in (1, 10, 100, 1000, 10000) if s <= top]
cells_legend = Legend(entries=[[[233, 223, 238], "touched, under 1 person"], *[[cell_rgb(s).tolist(), f"{s:,}+"] for s in stops]],
title="People per damaged cell (log)")
layers_on_map = [*([cells_layer] if cells_layer else []), count_layer, pop_layer, boundary_layer, *feature_layers.values(), *fac_layers.values()]
m = Map(layers_on_map, view_state=view) # drawn in the Overview (the map card near the top of the page)
Source
def toggle(layer, label):
return LayerToggle(layer=layer, label=label, value=bool(layer.visible)) # the switch starts where the layer starts
toggles = [toggle(boundary_layer, "Subdivision boundaries")]
toggles += [toggle(l, label) for label, l in feature_layers.items()]
toggles += [toggle(l, f"{LAYER_LABELS[k]} in impact") for k, l in fac_layers.items()]
if cells_layer:
toggles.append(toggle(cells_layer, "Damaged 100 m cells, shaded by people"))
toggles += [toggle(count_layer, "Subdivisions by damaged features"), toggle(pop_layer, "Subdivisions by exposed population")]
grade_legend = Legend(entries=[[c[:3], g] for g, c in GRADE_COLORS.items()], title="Damage grade")
legends = [grade_legend, *([cells_legend] if cells_legend else []),
legend_for("OrRd", 0, cmax, title="Damaged features (subdivision)"),
legend_for("PuBu", 0, pmax, title="Exposed population (subdivision)")]
# The toggles and legends are laid out in the full-screen map of the Overview (see the cells at the end).
5 · Temporal evolution¶
The footprint of every published product (not only the latest), in delivery order. The delivery time is the Montandon item’s
datetime. Point and line layers have little or no polygon area, so the area can stay near zero while the feature count changes.
The chart is in the Overview, grouped by area.
Source
def snapshot_date(delivery_time):
parsed = pd.to_datetime(delivery_time, errors="coerce", utc=True)
return parsed.tz_localize(None) if pd.notna(parsed) else pd.NaT
def measure_footprint(footprint, source_label, delivery_time):
if footprint.empty or footprint.crs is None:
return None
crs = choose_analysis_crs(footprint)
return {"date": snapshot_date(delivery_time), "impact_area_km2": footprint.to_crs(crs).geometry.area.sum() / 1_000_000,
"feature_count": len(footprint), "source": source_label}
timeline = []
for row in layers:
aoi, monitoring, family = layer_identity(row["path"])
if family.lower() == "notanalysed":
continue
timeline.append({**row, "aoi": aoi, "family": family, "monitoring": monitoring})
timeline.sort(key=lambda r: (r["datetime"] or "", r["monitoring"], r["path"].stem))
records = []
for row in timeline:
record = measure_footprint(filter_impact(read_layer(row["path"])), row["path"].stem, row["datetime"])
if record:
records.append(record)
temporal = pd.DataFrame(records, columns=["date", "impact_area_km2", "feature_count", "source"])
if not temporal.empty:
temporal = temporal.sort_values("date", na_position="last")
temporal.to_csv(Path(output_dir) / "temporal_impact.csv", index=False, encoding="utf-8-sig")
print(f"{len(temporal)} product footprints measured")
temporal.style.format({"impact_area_km2": "{:,.3f}"})32 product footprints measured
Source
plotted = (temporal.dropna(subset=["date"]).groupby("date", as_index=False)
.agg(impact_area_km2=("impact_area_km2", "sum"), feature_count=("feature_count", "sum")))
if plotted.empty:
print("No product with a parseable delivery time to plot")
else:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(plotted["date"], plotted["impact_area_km2"], marker="o"); ax.set_ylabel("Impact area (km²)"); ax.grid(alpha=0.25)
ax.set_title("Post-disaster footprint over time"); fig.autofmt_xdate(); fig.tight_layout()
fig.savefig(Path(output_dir) / "temporal_impact.png", dpi=150); plt.close(fig)
Reproduce or adapt¶
Download this notebook, set stac_item to a cems-events item of the Montandon catalog (and STAC_API_URL / STAC_API_KEY in
the environment), point area_geojson / subdivisions_geojson at your own boundaries and re-run it with standard Jupyter
tooling. The published page is a frozen artefact; the method is not.