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. The bounding box of those features and of the observed event extent (plus a small buffer) is the study extent.
Overlay — count damaged features and sum their footprint per subdivision; keep the selected infrastructure (health facilities, schools, airports, ports) that intersects the damage; sum the population of every 100 m WorldPop cell the damage touches, and of every cell the observed event extent (the flood or burnt-area polygons Copernicus mapped) touches, each with children under 5 and under 15 as breakouts and split by sex.
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"] # any of: health, schools, airports, ports
bbox_buffer_deg = 0.05 # degrees added around the damage extent for the population and infrastructure queries
population_year = 2025 # WorldPop R2025A population year, 2015 to 2030Source
# Parameters
run_id = "12ab3bf1-1a77-4877-8b3a-70c102715987"
inputs_dir = "/app/data/work/12ab3bf1-1a77-4877-8b3a-70c102715987/inputs"
output_dir = "/app/data/work/12ab3bf1-1a77-4877-8b3a-70c102715987/outputs"
area = {"id": 49145, "code": "VEN", "name": "Venezuela", "level": 0, "country": "VEN", "country_name": "Venezuela", "bbox": [-73.3521, 0.6488, -59.8072, 15.6729]}
area_geojson = "/app/data/work/12ab3bf1-1a77-4877-8b3a-70c102715987/inputs/area.geojson"
subdivisions_geojson = "/app/data/work/12ab3bf1-1a77-4877-8b3a-70c102715987/inputs/subdivisions.geojson"
stac_item = {"id": "cems-event-EMSR884", "bbox": [-69.165602, 9.790538, -66.194695, 10.848623], "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-EMSR884", "type": "application/geo+json", "auth:refs": ["oidc"]}, {"rel": "via", "href": "https://rapidmapping.emergency.copernicus.eu/EMSR884", "type": "text/html", "title": "CEMS EMSR884 activation"}, {"rel": "via", "href": "https://storymaps.arcgis.com/stories/717d0c07ec434b54ab6b2e0bbd7bc9f6", "type": "text/html", "title": "CEMS situational report (StoryMap)"}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/gdacs-events/items/1548377-1714328", "type": "application/geo+json", "roles": ["event"], "title": "GDACS EQ1548377 (episode 1714328)", "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/charter-events/items/charter-event-1036", "type": "application/geo+json", "roles": ["event"], "title": "Charter activation 1036", "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi00-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi01-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi02-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi03-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi04-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi05-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi06-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi07-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi08-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi09-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi10-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi11-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-hazards/items/cems-hazard-EMSR884-aoi12-earthquake", "type": "application/geo+json", "roles": ["hazard"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR884-aoi00-dat-sentinel1_20260625_2242_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-EMSR884-aoi00-dat-sentinel1_20260624_2249_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-EMSR884-aoi00-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-EMSR884-aoi01-dat-legion_20260627_1348_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-EMSR884-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-EMSR884-aoi02-dat-pneo_20260625_1459_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-EMSR884-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-EMSR884-aoi02-dat-pneo_20260626_1519_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-EMSR884-aoi02-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-EMSR884-aoi03-dat-legion_20260625_1517_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-EMSR884-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-EMSR884-aoi04-dat-worldview3_20260627_1530_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-EMSR884-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-EMSR884-aoi05-dat-worldview3_20260626_1510_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-EMSR884-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-EMSR884-aoi05-dat-worldview3_20260627_1530_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-EMSR884-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-EMSR884-aoi06-dat-legion_20260625_2036_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-EMSR884-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-EMSR884-aoi06-dat-legion_20260626_1511_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-EMSR884-aoi06-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-EMSR884-aoi07-dat-legion_20260626_1403_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-EMSR884-aoi07-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-EMSR884-aoi07-dat-legion_20260627_1516_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-EMSR884-aoi07-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-EMSR884-aoi08-dat-pneo_20260625_1500_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-EMSR884-aoi08-dat-legion_20260625_2037_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-EMSR884-aoi08-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-EMSR884-aoi08-dat-legion_20260626_2020_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-EMSR884-aoi08-dat-pneo_20260626_1518_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-EMSR884-aoi08-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-EMSR884-aoi08-dat-worldview2_20260705_1517_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-EMSR884-aoi08-gra-m2", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR884-aoi09-dat-legion_20260626_1404_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-EMSR884-aoi09-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-EMSR884-aoi10-dat-pneo_20260625_1459_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-EMSR884-aoi10-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-EMSR884-aoi11-dat-pneo_20260626_1519_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-EMSR884-aoi11-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-EMSR884-aoi12-dat-legion_20260626_1510_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-EMSR884-aoi12-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-EMSR884-aoi12-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-EMSR884-aoi12-dat-geoeye1_20260705_1505_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-EMSR884-aoi12-gra-m2", "type": "application/geo+json", "roles": ["response"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-response/items/cems-response-EMSR884-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-EMSR884-aoi00-gra-total", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra->-0.5-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-<-0.5-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0-m-to-0.05-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.05-m-to-0-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.1-m-to-0.2-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.2-m-to-0.5-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.05-m-to-0.1-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.2-m-to-0.1-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.5-m-to-0.2-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi00-gra-0.1-m-to-0.05-m", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-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-EMSR884-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-EMSR884-aoi02-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-EMSR884-aoi02-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-EMSR884-aoi02-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-EMSR884-aoi02-gra-roads-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-EMSR884-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-EMSR884-aoi05-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-EMSR884-aoi06-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-EMSR884-aoi06-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-EMSR884-aoi06-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-EMSR884-aoi06-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-EMSR884-aoi08-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-EMSR884-aoi08-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-EMSR884-aoi08-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-EMSR884-aoi08-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-EMSR884-aoi12-gra-builtup-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-gra-facilities-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-gra-camps-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-gra-transportation-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-gra-population-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-gra-roads-m2", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi.ifrc.org/stac/collections/cems-impacts/items/cems-impact-EMSR884-aoi12-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-EMSR884-aoi12-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-EMSR884-aoi12-gra-camps-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-EMSR884-aoi12-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-EMSR884-aoi12-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-EMSR884-aoi12-gra-roads-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-EMSR884-aoi12-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-EMSR884-aoi12-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-EMSR884-aoi12-gra-population", "type": "application/geo+json", "roles": ["impact"], "auth:refs": ["oidc"]}], "assets": {}, "geometry": {"type": "Point", "coordinates": [-67.80859040143667, 10.277062692317687]}, "collection": "cems-events", "properties": {"roles": ["event", "source"], "title": "Earthquake in Venezuela", "datetime": "2026-06-24T16:04:00Z", "keywords": ["EMSR884", "Earthquake", "Geological", "Ground shaking", "Seismic"], "description": "On 24 Jun 2026 22:05 UTC a 7.5M earthquake, preceded by a strong foreshock, occurred in Venezuela. The impact on population was deemed high at the beginning, with low visibility on the extent of the damage. This is why Copernicus EMS Rapid Mapping was requested to provide damage assessment emergency mapping.", "auth:schemes": {"oidc": {"type": "openIdConnect", "openIdConnectUrl": "https://goadmin.ifrc.org/o/.well-known/openid-configuration"}}, "monty:etl_id": "fcab5189-880e-47d5-bf10-d4b3a0f0fb93", "monty:corr_id": "20260624-VEN-902362-GH0101-1-GCDB", "monty:hazard_codes": ["GH0101", "EQ", "nat-geo-ear-gro"], "processing:version": "0.2.7", "monty:country_codes": ["VEN"], "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/12ab3bf1-1a77-4877-8b3a-70c102715987/inputs/stac_item.json"
stac_collection = "cems-events"
stac_api_url = "https://montandon-eoapi.ifrc.org/stac"
stac_catalog_profile = "montandon"
filters = {"hazard": ["earthquake"], "use_case": ["uc2"]}
hazard = "earthquake"
damage_grades = ["Destroyed", "Damaged", "Possibly damaged"]
bbox_buffer_deg = 0.05
population_year = 2025
aggregation_level = 2
infrastructure_layers = ["health", "schools", "airports", "ports"]
Source
import json, os, re, shutil, tempfile, time, uuid, warnings
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
import requests
from manywidgets import Table
warnings.filterwarnings("ignore", message=".*geographic CRS.*")
def table_of(frame, labels=None, digits=0, title="", max_height="420px", sortable=True):
"""A DataFrame as a manywidgets Table: numbers right-aligned with `digits` decimals (one number, or a dict per column), the rest as text,
column headers from `labels`. Used for every table in the notebook, so they all look alike."""
labels = labels or {}
columns = []
for col in frame.columns:
numeric = pd.api.types.is_numeric_dtype(frame[col]) and not pd.api.types.is_bool_dtype(frame[col])
columns.append({"key": str(col), "label": labels.get(col, str(col)),
**({"format": "number", "align": "right", "digits": digits.get(col, 0) if isinstance(digits, dict) else digits} if numeric else {})})
return Table(frame.to_dict("records"), columns, title=title, max_height=max_height, sortable=sortable)
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: Venezuela (VEN) · 338 subdivisions at admin level 2
Event: Earthquake in Venezuela · EMSR884 · 2026-06-24T16:04: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 WorldPop R2025A (Global2, constrained estimates), people per 100 m cell for
population_year, through the WorldPop API v3 (POST /raster, one GeoTIFF over the study extent). Six rasters are read: all ages (population) and, fromagesex, women, children under 5, girls under 5, children under 15 and girls under 15 (whole age classes 0-4 and 0-14); men are everyone minus women, because WorldPop’s sexes add up exactly. Age and sex come from each administrative unit’s age-sex shares, so the share of children is the same for every cell of a WorldPop unit. Licence CC BY 4.0. Cite WorldPop, University of Southampton: population R2025A v1, DOI 10.5258 /SOTON /WP00839; age and sex R2025A v1, DOI 10 .5258 /SOTON /WP00841. Infrastructure is OpenStreetMap, from the Humanitarian OpenStreetMap Team (HOT) per-country GeoParquet extracts listed on HDX: health facilities (
healthcareset, oramenityhospital, clinic, doctors, dentist, pharmacy), schools (amenity=school), airports (aeroway=aerodrome: the whole airport, not runways) and ports (industrial=port,harbour=yes, orlanduseport / harbour). The files are read remotely, only the rows inside the study extent, and the real footprint geometry is kept (no local copy). OpenStreetMap contributors, ODbL.
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)"}
# WorldPop R2025A through API v3: people per 100 m cell (3 arc-seconds) as a GeoTIFF in EPSG:4326, one request per layer.
# The key (optional) raises the limits; it is read from the environment, sent as a header and never printed.
WORLDPOP_API = "https://api.worldpop.org/v3"
WORLDPOP_YEARS = tuple(range(2015, 2031))
WORLDPOP_API_KEY = os.environ.get("WORLDPOP_API_KEY", "").strip()
WORLDPOP_CELL_DEG = 3 / 3600 # the 100 m grid is 3 arc-seconds
WORLDPOP_MAX_CELLS = 25_000_000 if WORLDPOP_API_KEY else 12_500_000 # per file; anonymous requests may read half as much
WORLDPOP_LAT_RANGE = (-60.0, 84.0) # the data does not cover other latitudes
# The rule of the SME notebooks (esa-montandon, D2.4.2 spatial_analysis.py): a 100 m cell counts when any damaged feature touches it, whole, as a
# settlement-level estimate. The same rule is used for the people in the observed event extent.
COUNT_ALL_TOUCHED = True
# OpenStreetMap infrastructure from HOT's per-country GeoParquet extracts (HDX publishes them as `hotosm_{iso3}_{layer}`).
# `where` is the OSM tag filter on the extract's columns; `kind` is what the feature is called in the lists.
HOT_FILE_URL = "https://production-raw-data-api.s3.amazonaws.com/ISO3/{iso3}/_layers/osm/{layer}.parquet"
HDX_PACKAGE_URL = "https://data.humdata.org/api/3/action/package_show?id=hotosm_{iso3}_{layer}"
HOT_LAYERS = {
"health": {"file": "health_facilities", "kind": "COALESCE(amenity, healthcare)",
"where": "healthcare IS NOT NULL OR amenity IN ('hospital', 'clinic', 'doctors', 'dentist', 'pharmacy')"},
"schools": {"file": "education_facilities", "kind": "'school'", "where": "amenity = 'school'"},
"airports": {"file": "airports", "kind": "'airport'", "where": "aeroway = 'aerodrome'"},
"ports": {"file": "sea_ports", "kind": "'port'",
"where": "industrial = 'port' OR harbour = 'yes' OR landuse IN ('port', 'harbour')"},
}
LAYER_LABELS = {"health": "Health facilities", "schools": "Schools", "airports": "Airports", "ports": "Ports"}
LAYER_COLORS = {"health": [31, 36, 48], "schools": [0, 128, 96], "airports": [117, 107, 177], "ports": [166, 97, 26]}
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")
population_year = int(population_year)
if population_year not in WORLDPOP_YEARS:
raise ValueError(f"population_year must be between {WORLDPOP_YEARS[0]} and {WORLDPOP_YEARS[-1]}")
# ---- 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)
table_of(response_table(responses).head(15), title="Montandon response items for the event (latest 15)",
labels={"item": "Item", "datetime": "Delivered", "type": "Type", "status": "Status", "monitoring": "Monitoring step"})Montandon items for EMSR884: 13 hazards · 45 responses · 42 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)
table_of(cems_published.head(20), title="Figures Copernicus publishes for the event (Montandon cems-impacts, first 20)",
labels={"item": "Item", "category": "Category", "type": "Type", "value": "Value", "unit": "Unit", "estimate": "Estimate"}, digits={"value": 1})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. The observed event (observedEvent* polygons: the flood or burnt-area extent seen on imagery) is read from the same layers.
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)})")
def observed_event_polygons(frame):
"""The observed event (observedEvent* layers: the flood or burnt-area extent Copernicus saw on imagery), polygons only,
each with the mapped area (AOI) its layer belongs to."""
if frame.empty or "copernicus_layer" not in frame.columns:
return frame.iloc[0:0]
is_event = frame["copernicus_layer"].map(lambda name: layer_identity(Path(name))[2] == "observedEvent")
polygons = frame[is_event & frame.geometry.notna() & frame.geom_type.isin(["Polygon", "MultiPolygon"])].copy()
polygons["aoi"] = polygons["copernicus_layer"].map(lambda name: layer_identity(Path(name))[0])
return polygons[["aoi", "copernicus_layer", "geometry"]]
observed_event = observed_event_polygons(impact_all)
BBOX = bbox_from_geodataframe(impact, float(bbox_buffer_deg))
EVENT_NOTE = ""
if len(observed_event):
# The flood or burnt-area extent can reach beyond the damaged features: the study extent holds both, if one WorldPop request can.
both = gpd.GeoDataFrame(pd.concat([impact[["geometry"]], observed_event[["geometry"]]], ignore_index=True), geometry="geometry", crs="EPSG:4326")
wider = bbox_from_geodataframe(both, float(bbox_buffer_deg))
wider_cells = np.ceil((wider[2] - wider[0]) / WORLDPOP_CELL_DEG) * np.ceil((wider[3] - wider[1]) / WORLDPOP_CELL_DEG)
if wider_cells <= WORLDPOP_MAX_CELLS:
BBOX = wider
else:
EVENT_NOTE = (f"The observed event extent is too large for one WorldPop request ({wider_cells:,.0f} cells of 100 m, at most "
f"{WORLDPOP_MAX_CELLS:,}), so the people inside it are not counted.")
observed_event = observed_event.iloc[0:0]
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)}.")
if EVENT_NOTE:
print(EVENT_NOTE)
elif len(observed_event):
print(f"Observed event extent: {len(observed_event):,} polygon features in {observed_event['aoi'].nunique()} mapped area(s), inside the study extent.")Copernicus EMS layers found for EMSR884: 40
Impact zone: layers used 16 · features loaded 29,671 · kept as damage (Destroyed, Damaged, Possibly damaged) 3,127. Study extent (west, south, east, north): -68.905, 10.162, -66.502, 10.677. Subdivisions intersecting it: 61.
3 · Population and infrastructure¶
Source
def worldpop_error(response):
"""A short message for a WorldPop error answer (JSON: error, message, details). Never includes request headers."""
try:
body = response.json()
return f"{response.status_code} {body.get('error')}: {body.get('message')}"
except ValueError:
return f"{response.status_code} {response.text[:200]}"
def fetch_worldpop(bbox, year, destination, layer="population", age_range=None, sex=None):
"""Write one WorldPop R2025A raster (people per 100 m cell, EPSG:4326, nodata -99999) for a WGS84 box
(west, south, east, north) to `destination` and return the people the API counted in it.
`layer` is "population" (all ages, both sexes) or "agesex" with `age_range` [min, max] (widened to whole age classes; none = all ages)
and `sex` "female", "male" or "both"."""
west, south, east, north = bbox
if south < WORLDPOP_LAT_RANGE[0] or north > WORLDPOP_LAT_RANGE[1]:
raise ValueError(f"WorldPop covers latitudes {WORLDPOP_LAT_RANGE[0]:g} to {WORLDPOP_LAT_RANGE[1]:g}; the damage extent is at {south:.2f} to {north:.2f}")
cells = np.ceil((east - west) / WORLDPOP_CELL_DEG) * np.ceil((north - south) / WORLDPOP_CELL_DEG)
if cells > WORLDPOP_MAX_CELLS:
hint = "" if WORLDPOP_API_KEY else " (set WORLDPOP_API_KEY to double the limit)"
raise ValueError(f"The population window is about {cells:,.0f} cells of 100 m; WorldPop returns at most {WORLDPOP_MAX_CELLS:,} per file{hint}. "
"Reduce the extent buffer or pick a smaller damage extent")
body = {"geojson": {"type": "Polygon", "coordinates": [[[west, south], [east, south], [east, north], [west, north], [west, south]]]},
"year": year, "layer": layer, "resolution": "100m"}
if layer == "agesex":
body.update(sex=sex or "both", bands="sum") # one band: the people of the chosen ages and sex
if age_range:
body["age_range"] = list(age_range)
headers = {**USER_AGENT, **({"X-API-Key": WORLDPOP_API_KEY} if WORLDPOP_API_KEY else {})}
for attempt in range(4):
try:
r = requests.post(f"{WORLDPOP_API}/raster", json=body, headers=headers, timeout=(30, 180))
except requests.RequestException as e:
if attempt == 3:
raise RuntimeError(f"Cannot reach the WorldPop API: {type(e).__name__}") from None
time.sleep(3 * (attempt + 1))
continue
try:
code = r.json().get("error", "")
except ValueError:
code = ""
# 5xx and the per-minute / concurrency 429s are worth waiting for; the daily quota (rate_limit_exceeded) is not
if (r.status_code >= 500 or code in ("minute_limit_exceeded", "concurrency_limit_exceeded")) and attempt < 3:
time.sleep(min(float(r.headers.get("Retry-After", 3 * (attempt + 1))), 65))
continue
if r.status_code != 200:
raise RuntimeError(f"WorldPop API error ({layer}{'' if not age_range else ' ' + str(age_range)}{'' if not sex else ' ' + sex}): {worldpop_error(r)}")
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(r.content)
return float(r.headers.get("X-Total-Population", "nan")), float(r.headers.get("X-Agesex-Coverage", "1") or 1)
# One raster per population layer, all on the same 3 arc-second grid. Files live in the scratch cache and are removed at the end.
# raster key -> the WorldPop request, how it reads in text and menus, and the exposure column it fills. Everyone first, then women and men,
# then children under 5 and under 15 (both sexes, then women and men). These names are used in the tables, the map and every export.
# Men are not requested: WorldPop's two sexes add up to everyone exactly, so "derive" gives the two rasters to subtract.
POPULATION_LAYERS = {
"total": {"layer": "population", "age_range": None, "sex": None, "label": "all ages", "title": "All people", "column": "pop_exposed"},
"women": {"layer": "agesex", "age_range": None, "sex": "female", "label": "women", "title": "Women", "column": "pop_women_exposed"},
"men": {"derive": ("total", "women"), "label": "men", "title": "Men", "column": "pop_men_exposed"},
"under5": {"layer": "agesex", "age_range": [0, 4], "sex": "both", "label": "children under 5", "title": "Under 5", "column": "pop_u5_exposed"},
"women_u5": {"layer": "agesex", "age_range": [0, 4], "sex": "female", "label": "girls under 5", "title": "Under 5 · women", "column": "pop_u5_women_exposed"},
"men_u5": {"derive": ("under5", "women_u5"), "label": "boys under 5", "title": "Under 5 · men", "column": "pop_u5_men_exposed"},
"under15": {"layer": "agesex", "age_range": [0, 14], "sex": "both", "label": "children under 15", "title": "Under 15", "column": "pop_u15_exposed"},
"women_u15": {"layer": "agesex", "age_range": [0, 14], "sex": "female", "label": "girls under 15", "title": "Under 15 · women", "column": "pop_u15_women_exposed"},
"men_u15": {"derive": ("under15", "women_u15"), "label": "boys under 15", "title": "Under 15 · men", "column": "pop_u15_men_exposed"},
}
def derive_raster(minuend, subtrahend, destination):
"""Write minuend - subtrahend (never below zero) as a GeoTIFF on the same grid."""
with rasterio.open(minuend) as a, rasterio.open(subtrahend) as b:
profile, nodata = a.profile, a.nodata
va, vb = a.read(1).astype("float32"), b.read(1).astype("float32")
gap = (va == nodata) | (vb == nodata) if nodata is not None else np.zeros(va.shape, dtype=bool)
with rasterio.open(destination, "w", **profile) as out:
out.write(np.where(gap, nodata if nodata is not None else 0.0, np.clip(va - vb, 0, None)).astype("float32"), 1)
RASTER_DIR = CACHE_DIR / "uc2" / f"worldpop_{uuid.uuid4().hex}"
POPULATION_RASTERS = {}
_t0 = time.time()
for key, spec in POPULATION_LAYERS.items():
if "derive" in spec:
continue
path = RASTER_DIR / f"{key}.tif"
counted, coverage = fetch_worldpop(BBOX, population_year, path, spec["layer"], spec["age_range"], spec["sex"])
POPULATION_RASTERS[key] = path
note = f" (age-sex coverage {coverage:.0%})" if coverage < 0.999 else ""
print(f"WorldPop R2025A {population_year}, {spec['label']}: {counted:,.0f} people in the study extent{note}")
for key, spec in POPULATION_LAYERS.items():
if "derive" in spec:
both, women = spec["derive"]
POPULATION_RASTERS[key] = RASTER_DIR / f"{key}.tif"
derive_raster(POPULATION_RASTERS[both], POPULATION_RASTERS[women], POPULATION_RASTERS[key])
print(f"WorldPop: {sum(1 for spec in POPULATION_LAYERS.values() if 'derive' not in spec)} rasters read in {time.time() - _t0:.0f}s" + (" with an API key" if WORLDPOP_API_KEY else " (anonymous)") + "; men are everyone minus women")
def hot_file_url(iso3, layer):
"""The GeoParquet file of one HOT country layer. The URL is looked up on HDX (where HOT publishes it as the GeoParquet
resource of `hotosm_{iso3}_{layer}`); HOT's S3 path is the fallback if HDX does not answer or lists no such resource."""
try:
r = requests.get(HDX_PACKAGE_URL.format(iso3=iso3.lower(), layer=layer), headers=USER_AGENT, timeout=30)
r.raise_for_status()
for res in r.json()["result"]["resources"]:
url = str(res.get("url") or "")
if str(res.get("format", "")).lower() == "geoparquet" and url.startswith("https://") and url.endswith(".parquet"):
return url
except Exception:
pass
return HOT_FILE_URL.format(iso3=iso3.upper(), layer=layer)
def hot_last_modified(url):
"""When HOT last rebuilt the file (HTTP Last-Modified). This is HOT's build time, not the date of the OpenStreetMap
data inside it, which is a little older."""
try:
r = requests.head(url, headers=USER_AGENT, timeout=30, allow_redirects=True)
return r.headers.get("Last-Modified", "unknown")
except requests.RequestException:
return "unknown"
HOT_SOURCES = {} # layer -> {"file", "url", "last_modified"}, filled by load_hot_layer, for the printed source line
def load_hot_layer(layer, bbox):
"""OSM features of one infrastructure layer inside bbox (xmin, ymin, xmax, ymax), read from HOT's per-country GeoParquet
through DuckDB range reads (the bbox column prunes the file). The real OSM geometry is kept (points, footprints, areas), so
the overlay with the damage layers intersects footprints, not just a point per facility."""
spec = HOT_LAYERS[layer]
url = hot_file_url(iso, spec["file"])
xmin, ymin, xmax, ymax = bbox
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs;")
try:
df = con.execute(f"""
SELECT split_part(id, '/', 1) AS osm_type, CAST(split_part(id, '/', 2) AS BIGINT) AS osm_id, name, name_en,
{spec['kind']} AS kind, ST_AsWKB(geom) AS wkb
FROM read_parquet(?)
WHERE bbox.xmin <= {float(xmax)} AND bbox.xmax >= {float(xmin)} AND bbox.ymin <= {float(ymax)} AND bbox.ymax >= {float(ymin)}
AND ({spec['where']})
""", [url]).df()
except duckdb.Error as e:
raise RuntimeError(f"Could not read HOT's OpenStreetMap layer {spec['file']!r} for {iso} from {url} ({type(e).__name__}: {str(e)[:200]}). "
"HOT publishes these layers for about 250 countries (https://data.humdata.org/organization/hot)") from None
HOT_SOURCES[layer] = {"file": spec["file"], "url": url, "last_modified": hot_last_modified(url)}
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"] = layer
return out.drop_duplicates(subset=["osm_id", "osm_type"]).reset_index(drop=True)
frames = []
for layer_name in infrastructure_layers:
if layer_name not in HOT_LAYERS:
raise ValueError(f"No dataset for infrastructure layer {layer_name!r}; choose from {', '.join(HOT_LAYERS)}")
frames.append(load_hot_layer(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", "kind", "name", "name_en", "geometry"], geometry="geometry", crs=4326))
print(f"Infrastructure features in the study extent ({', '.join(infrastructure_layers)}): {len(infrastructure):,}")WorldPop R2025A 2025, all ages: 6,985,084 people in the study extent
WorldPop R2025A 2025, women: 3,602,289 people in the study extent
WorldPop R2025A 2025, children under 5: 393,368 people in the study extent
WorldPop R2025A 2025, girls under 5: 193,483 people in the study extent
WorldPop R2025A 2025, children under 15: 1,423,494 people in the study extent
WorldPop R2025A 2025, girls under 15: 698,666 people in the study extent
WorldPop: 6 rasters read in 7s with an API key; men are everyone minus women
Infrastructure features in the study extent (health, schools, airports, ports): 2,577
4 · Exposure by subdivision¶
For each subdivision: the number of damaged features, their footprint area, and the population of the 100 m WorldPop cells the damage touches (all ages, plus children under 5 and under 15, each by sex), and, separately, of the cells inside the observed event extent. 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 cells the damage touches (mask, people per cell, transform, CRS), for the map
POP_COLUMNS = {key: spec["column"] for key, spec in POPULATION_LAYERS.items()} # raster key -> exposed column
EVENT_COLUMNS = {col: col.replace("pop_", "pop_event_", 1) for col in POP_COLUMNS.values()} # damaged-cell column -> observed-event column
ALL_AOIS = "all (counted once)"
def exposure_from(rasters, admin, shape_sets, *, with_extent_total=False):
"""People per WorldPop group in the 100 m cells that named sets of geometries touch (WGS84), each person counted once.
`shape_sets` maps a name (here a Copernicus mapped area) to its geometries. A cell counts when any geometry touches it (COUNT_ALL_TOUCHED);
only cells whose centre is inside a subdivision of `admin` count. Returns (by_zone, by_set, cells): `by_zone` has one row per subdivision over
all sets together (with `with_extent_total`, also `pop_total`: everyone inside the bounding box of the geometries); `by_set` maps each name and
"all" to {raster key: people}; `cells` is the union mask and the people in it per cell, for the map."""
geoms = [g for gs in shape_sets.values() for g in gs if g is not None and not g.is_empty]
nobody = pd.DataFrame({ID_COL: admin[ID_COL].values, "pop_total": np.nan, **{col: 0.0 for col in POP_COLUMNS.values()}})
if not geoms:
return nobody, {}, {}
with rasterio.open(rasters["total"]) as src:
west, south, east, north = gpd.GeoSeries(geoms, crs=4326).to_crs(src.crs).total_bounds
window = from_bounds(west - 1e-6, south - 1e-6, east + 1e-6, north + 1e-6, 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 nobody, {}, {}
transform, crs, shape = window_transform(window, src.transform), src.crs, (int(window.height), int(window.width))
grid = (src.crs, src.width, src.height, tuple(src.transform))
def read(key):
with rasterio.open(rasters[key]) as band:
if (band.crs, band.width, band.height) != grid[:3] or not np.allclose(tuple(band.transform), grid[3], atol=1e-9):
raise RuntimeError(f"The WorldPop {key} raster is not on the same grid as the total-population raster")
values = band.read(1, window=window).astype("float64")
if band.nodata is not None:
values = np.where(values == band.nodata, 0.0, values) # outside the data: nobody counted
return np.nan_to_num(values, nan=0.0)
people = {key: read(key) for key in POP_COLUMNS}
zones = admin.to_crs(crs)
keep = [i for i, g in enumerate(zones.geometry) if g is not None and not g.is_empty]
# Label every cell with its subdivision (cell centre inside the polygon); label 0 is outside all of them.
labels = rasterize([(zones.geometry.iloc[i], i + 1) for i in keep], out_shape=shape, transform=transform, fill=0, dtype="int32")
def mask_of(geometries):
shapes = [(g, 1) for g in gpd.GeoSeries(geometries, crs=4326).to_crs(crs) if g is not None and not g.is_empty]
return rasterize(shapes, out_shape=shape, transform=transform, fill=0, dtype="uint8", all_touched=COUNT_ALL_TOUCHED).astype(bool) & (labels > 0)
union = mask_of(geoms)
by_set = {name: {key: float(values[mask_of(gs)].sum()) for key, values in people.items()} for name, gs in shape_sets.items()}
by_set["all"] = {key: float(values[union].sum()) for key, values in people.items()}
by_zone = nobody.assign(pop_total=0.0)
by_label = np.array(keep) + 1 # a subdivision's label is its position + 1
for key, col in POP_COLUMNS.items():
by_zone.loc[keep, col] = np.bincount(labels.ravel(), weights=(people[key] * union).ravel(), minlength=len(zones) + 1)[by_label]
if with_extent_total:
rectangle = rasterize([(box(west, south, east, north), 1)], out_shape=shape, transform=transform, fill=0, dtype="uint8").astype(bool)
by_zone.loc[keep, "pop_total"] = np.bincount(labels.ravel(), weights=np.where(rectangle, people["total"], 0.0).ravel(), minlength=len(zones) + 1)[by_label]
return by_zone, by_set, {"mask": union, "people": (people["total"] * union).astype("float32"), "transform": transform, "crs": crs}
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)
# ---- people in the cells the damage touches (the headline), and in the cells the observed event extent touches -------------------------
# The observed event is the flood or burnt-area extent Copernicus saw on imagery. Both use the same counting rule; the columns of the second
# are named like the first, with `event` added. Everything is also split per Copernicus mapped area (AOI), each person counted once in "all".
aoi_of = lambda frame: frame["copernicus_layer"].map(lambda name: layer_identity(Path(name))[0])
damage_sets = {a: list(g.geometry) for a, g in impact.assign(aoi=aoi_of(impact)).groupby("aoi")}
damage_zone, damage_by_aoi, cells = exposure_from(POPULATION_RASTERS, admin, damage_sets, with_extent_total=True)
exposed_cells.update(cells)
impact_admin = impact_admin.merge(damage_zone, on=ID_COL, how="left")
for col in ["pop_total", *POP_COLUMNS.values()]:
impact_admin[col] = impact_admin[col].fillna(0)
has_event = bool(len(observed_event))
event_sets = {a: list(g.geometry) for a, g in observed_event.groupby("aoi")} if has_event else {}
if has_event:
event_zone, event_by_aoi, _ = exposure_from(POPULATION_RASTERS, admin, event_sets)
impact_admin = impact_admin.merge(event_zone[[ID_COL, *EVENT_COLUMNS]].rename(columns=EVENT_COLUMNS), on=ID_COL, how="left")
for col in EVENT_COLUMNS.values():
impact_admin[col] = impact_admin[col].fillna(0)
else:
event_by_aoi = {}
for col in EVENT_COLUMNS.values():
impact_admin[col] = np.nan # no observed event layer: not zero, not available
rows = []
for key in [*sorted(set(damage_sets) | set(event_sets), key=lambda k: (not str(k).isdigit(), str(k))), "all"]:
nobody = {k: 0.0 for k in POP_COLUMNS}
d = damage_by_aoi.get(key, nobody)
e = event_by_aoi.get(key) or ({} if not has_event else nobody)
label = ALL_AOIS if key == "all" else ("AOI" + str(key) if str(key).isdigit() else str(key))
rows.append({"aoi": label, **{POP_COLUMNS[k]: d[k] for k in POP_COLUMNS}, **{EVENT_COLUMNS[POP_COLUMNS[k]]: e.get(k, np.nan) for k in POP_COLUMNS}})
exposure_by_aoi = pd.DataFrame(rows)
shutil.rmtree(RASTER_DIR, ignore_errors=True)
table_cols = [ID_COL, NAME_COL, "impact_feature_count", "impact_area_km2", *POP_COLUMNS.values(), *EVENT_COLUMNS.values(), "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"(under 5: {round(float(impact_admin['pop_u5_exposed'].sum())):,}, under 15: {round(float(impact_admin['pop_u15_exposed'].sum())):,}) · "
+ (f"people in the observed event extent {round(float(impact_admin['pop_event_exposed'].sum())):,} "
f"(under 5: {round(float(impact_admin['pop_event_u5_exposed'].sum())):,}, under 15: {round(float(impact_admin['pop_event_u15_exposed'].sum())):,}) · " if has_event else "")
+
f"infrastructure features in the damage zone {len(exposed_infra):,}.")
for layer_name, src_info in HOT_SOURCES.items():
print(f"{LAYER_LABELS[layer_name]}: OpenStreetMap via HOT ({src_info['file']}), file last updated {src_info['last_modified']} "
"(HOT's build date, not the date of the OSM data beneath it)")
# The by-sex columns are in impact_by_admin.csv and .geojson; the table here shows the main ones.
shown = [ID_COL, NAME_COL, "impact_feature_count", "impact_area_km2", "pop_exposed", "pop_u5_exposed", "pop_u15_exposed",
"pop_event_exposed", "pop_event_u5_exposed", "pop_event_u15_exposed", "pop_total"]
table_of(ranked[shown].head(25), title="Exposure by subdivision: the 25 with the most damaged features (all columns, including women and men, are in impact_by_admin.csv)",
labels={"code": "Code", "name": "Subdivision", "impact_feature_count": "Damaged features", "impact_area_km2": "Footprint (km²)",
"pop_exposed": "People in damaged cells", "pop_u5_exposed": "Under 5", "pop_u15_exposed": "Under 15",
"pop_event_exposed": "People in event extent", "pop_event_u5_exposed": "Under 5 (event)", "pop_event_u15_exposed": "Under 15 (event)",
"pop_total": "People in damage extent"}, digits={"impact_area_km2": 2})Measured in EPSG:32619: damaged features 3,105 · subdivisions 61 · people in the 100 m cells the damage touches 83,421 (under 5: 4,527, under 15: 16,485) · infrastructure features in the damage zone 13.
Health facilities: OpenStreetMap via HOT (health_facilities), file last updated Tue, 03 Nov 2026 08:48:11 GMT (HOT's build date, not the date of the OSM data beneath it)
Schools: OpenStreetMap via HOT (education_facilities), file last updated Tue, 03 Nov 2026 08:47:43 GMT (HOT's build date, not the date of the OSM data beneath it)
Airports: OpenStreetMap via HOT (airports), file last updated Tue, 03 Nov 2026 08:49:36 GMT (HOT's build date, not the date of the OSM data beneath it)
Ports: OpenStreetMap via HOT (sea_ports), file last updated Tue, 03 Nov 2026 08:50:00 GMT (HOT'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 ipywidgets import jsdlink
from manywidgets import Chart, Column, Legend, Row, Stat, Toggle
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}"
def layer_switch(layer, label, value=None):
"""A switch for a layer's visibility: a plain manywidgets Toggle (it takes the page theme) linked in the browser to the layer's `visible`."""
layer.visible = bool(layer.visible) if value is None else bool(value)
switch = Toggle(value=layer.visible, label=label)
jsdlink((switch, "value"), (layer, "visible"))
return switchMap — 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 selected infrastructure 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 == name]
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 WorldPop grid is 3 arc-seconds (about 100 m): resample to the image's pixels, 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 layer_switch(layer, label) # 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")
table_of(temporal.assign(date=pd.to_datetime(temporal["date"], errors="coerce").dt.strftime("%Y-%m-%d %H:%M")), title="Footprint of every Copernicus product, in delivery order",
labels={"date": "Delivered (UTC)", "impact_area_km2": "Footprint (km²)", "feature_count": "Damaged features", "source": "Product"}, digits={"impact_area_km2": 3})21 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.