Post-disaster impact estimation
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 1 km WorldPop cell the damage touches.
Temporal evolution — measure the footprint of every published Copernicus EMS product, in delivery order.
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 queriesSource
# Parameters
run_id = "2f2ff7cd-3559-48d0-a139-4bae9ed541dd"
inputs_dir = "/app/data/work/2f2ff7cd-3559-48d0-a139-4bae9ed541dd/inputs"
output_dir = "/app/data/work/2f2ff7cd-3559-48d0-a139-4bae9ed541dd/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/2f2ff7cd-3559-48d0-a139-4bae9ed541dd/inputs/area.geojson"
subdivisions_geojson = "/app/data/work/2f2ff7cd-3559-48d0-a139-4bae9ed541dd/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-stage.ifrc.org/stac/collections/cems-events", "type": "application/json", "auth:refs": ["oidc"]}, {"rel": "parent", "href": "https://montandon-eoapi-stage.ifrc.org/stac/collections/cems-events", "type": "application/json", "auth:refs": ["oidc"]}, {"rel": "root", "href": "https://montandon-eoapi-stage.ifrc.org/stac/", "type": "application/json", "auth:refs": ["oidc"]}, {"rel": "self", "href": "https://montandon-eoapi-stage.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", "auth:refs": ["oidc"]}, {"rel": "via", "href": "https://storymaps.arcgis.com/stories/f76baefadfa74d6d9a18265875f48870", "type": "text/html", "title": "CEMS situational report (StoryMap)", "auth:refs": ["oidc"]}, {"rel": "related", "href": "https://montandon-eoapi-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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-stage.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": "64eb8952-9915-45e6-afd3-3db829934b5d", "monty:corr_id": "20260825-NPL-1061525-MH0603-1-GCDB", "monty:hazard_codes": ["MH0603", "FF", "nat-hyd-flo-fla"], "processing:version": "0.2.6", "monty:country_codes": ["NPL"], "processing:software": {"pystac-monty": "0.2.6"}, "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/2f2ff7cd-3559-48d0-a139-4bae9ed541dd/inputs/stac_item.json"
stac_collection = "cems-events"
stac_api_url = "https://montandon-eoapi-stage.ifrc.org/stac"
stac_catalog_profile = "montandon"
filters = {"hazard": ["flood"], "use_case": ["uc2"]}
hazard = "flood"
damage_grades = ["Destroyed", "Damaged", "Possibly damaged"]
bbox_buffer_deg = 0.05
aggregation_level = 2
infrastructure_layers = ["health"]
Source
import json, os, re, tempfile, 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 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 = gpd.read_file(area_geojson)
has_subs = subdivisions_geojson and Path(subdivisions_geojson).exists()
return area_gdf, (gpd.read_file(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 WorldPop’s 1 km country raster, downloaded once per country into the scratch cache.
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
from rasterstats import zonal_stats
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_URL = "https://data.worldpop.org/GIS/Population/Global_2000_2020_1km/2020/{ISO}/{iso}_ppp_2020_1km_Aggregated.tif"
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")
# ---- 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"{len(layers)} CEMS layers cached in {CEMS_DIR}")
_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):
frame = gpd.read_file(path)
return frame.set_crs("EPSG:4326") if frame.crs is None else frame
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({"layers_used": len(vector_layers), "features_loaded": len(impact_all), "impact_features": len(impact),
"bbox": [round(v, 3) for v in BBOX], "subdivisions_in_extent": len(admin)})36 CEMS layers cached in /tmp/notebook-factory-cache/cems/EMSR927
{'layers_used': 22, 'features_loaded': 6085, 'impact_features': 5357, 'bbox': [84.893, 27.748, 85.429, 28.329], 'subdivisions_in_extent': 2}
3 · Population and hospitals¶
Source
def get_population(iso):
"""WorldPop 1 km raster for a country. Downloaded on first use, then read from the cache.
(The server ignores HTTP range requests, so we can't read just a window of it remotely.)"""
path = CACHE_DIR / "worldpop" / f"{iso.lower()}_ppp_2020_1km_Aggregated.tif"
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
url = WORLDPOP_URL.format(iso=iso.lower(), ISO=iso.upper())
tmp = path.with_suffix(f".{uuid.uuid4().hex}.part") # unique per run: runs for one country can overlap
print(f"Downloading {url}")
try:
urllib.request.urlretrieve(url, tmp)
except Exception as e:
tmp.unlink(missing_ok=True)
raise RuntimeError(f"Could not download WorldPop population for {iso!r} from {url}: {e}") from e
tmp.replace(path) # only a complete download ever gets the final name
return path
def clip_raster(source, destination, bbox):
"""Write a WGS84 window of the country raster (bbox = west, south, east, north)."""
west, south, east, north = bbox
with rasterio.open(source) as src:
window = from_bounds(west, south, east, north, transform=src.transform)
window = window.round_offsets().round_lengths().intersection(rasterio.windows.Window(0, 0, src.width, src.height))
data = src.read(window=window)
profile = src.profile.copy()
profile.update(height=data.shape[1], width=data.shape[2], transform=src.window_transform(window))
destination.parent.mkdir(parents=True, exist_ok=True)
with rasterio.open(destination, "w", **profile) as dst:
dst.write(data)
POPULATION_RASTER = CACHE_DIR / "uc2" / f"population_{uuid.uuid4().hex}.tif" # this run's window; removed at the end
clip_raster(get_population(iso), POPULATION_RASTER, BBOX)
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, 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", "geometry"], geometry="geometry", crs=4326))
print({"population_raster": str(POPULATION_RASTER.name), "hospitals_in_extent": len(infrastructure)}){'population_raster': 'population_a3c9d92435af43f5bab6f51de98e6bd0.tif', 'hospitals_in_extent': 39}
4 · Exposure by subdivision¶
For each subdivision: the number of damaged features, their footprint area, and the population of the 1 km WorldPop 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()
def population_under_impact(admin, impact, raster_path, *, all_touched=True):
"""Sum population raster cells that touch the impact mask, by subdivision.
Building footprints are much smaller than a 1 km WorldPop cell. ``all_touched`` counts a cell if any damaged
feature overlaps it, which is the intended settlement-level exposure estimate for grading products."""
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 impact extent, then mask cells that touch damage.
bounds = impact.to_crs(src.crs).total_bounds
window = from_bounds(*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
zones = admin.to_crs(src.crs)
total_stats = zonal_stats(zones, pop, affine=transform, stats=["sum"], nodata=0, geojson_out=False)
exposed_stats = zonal_stats(zones, exposed, affine=transform, stats=["sum"], nodata=0, geojson_out=False)
return pd.DataFrame({
ID_COL: admin[ID_COL].values,
"pop_total": [r["sum"] if r["sum"] is not None else 0.0 for r in total_stats],
"pop_exposed": [r["sum"] if r["sum"] is not None else 0.0 for r in exposed_stats],
})
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({"analysis_crs": analysis_crs, "subdivisions": len(impact_admin), "damaged_features": int(impact_admin["impact_feature_count"].sum()),
"pop_exposed_sum": round(float(impact_admin["pop_exposed"].sum())), "hospitals_in_impact": 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}"}){'analysis_crs': 'EPSG:32645', 'subdivisions': 2, 'damaged_features': 5357, 'pop_exposed_sum': 37554, 'hospitals_in_impact': 1}
Hospitals: OpenStreetMap via Layercake, file last updated Sun, 08 Nov 2026 14:49:28 GMT (Layercake's build date, not the date of the OSM data beneath it)
Results¶
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
from lonboard import 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}"
fac_stats = [Stat(label=f"{LAYER_LABELS[l]} in impact", value=len(exposed_infra[exposed_infra.infra_type == "hospital"])) for l in infrastructure_layers]
Row(
Stat(label="Damaged features", value=fmt_int(impact_admin["impact_feature_count"].sum())),
Stat(label="Subdivisions affected", value=int((impact_admin["impact_feature_count"] > 0).sum())),
Stat(label="Population in damaged 1 km cells", value=fmt_int(impact_admin["pop_exposed"].sum())),
*fac_stats,
gap="16px",
)Map — damaged features and exposed population¶
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 1 km 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"]]
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}
layers_on_map = [count_layer, pop_layer, boundary_layer, *feature_layers.values(), *fac_layers.values()]
Map(layers_on_map, view_state=view)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()]
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")
Row(Column(*toggles, gap="6px"), grade_legend,
legend_for("OrRd", 0, cmax, title="Damaged features (subdivision)"), legend_for("PuBu", 0, pmax, title="Exposed population (subdivision)"),
gap="24px", align="start")Population in damaged cells, by subdivision¶
Source
top = ranked[ranked["pop_exposed"] > 0].sort_values("pop_exposed", ascending=False).head(15)
bar_chart(top[NAME_COL], top["pop_exposed"], title=f"{event_props.get('title', ACTIVATION)} · population in damaged 1 km cells", y_label="Population")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.
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")))
temporal_charts = None
if plotted.empty:
print("No product with a parseable delivery time to plot")
else:
labels = [d.strftime("%Y-%m-%d %H:%M") for d in plotted["date"]]
def line_chart(values, title, y_label, color):
chart = Chart(title=title, y_label=y_label, height=300, legend_enabled=False)
chart.set_options(scales={"x": {"type": "category", "ticks": {"autoSkip": True, "maxRotation": 60, "minRotation": 30}}})
chart.add_series(x=labels, y=[float(v) for v in values], name=y_label, color=color)
return chart
area_chart = line_chart(plotted["impact_area_km2"], "Footprint area per delivery date", "Impact area (km²)", "#E4572E")
count_chart = line_chart(plotted["feature_count"], "Damaged features per delivery date", "Features", "#2E6FB0")
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)
temporal_charts = Column(area_chart, count_chart, gap="12px")
temporal_charts # a widget is only displayed when it is the cell's last top-level expressionReproduce 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.