Population & infrastructure risk exposure
Question: how many people and which facilities are exposed to a given hazard before any event?
Method (after INFORM / the MapAction–IFRC children-exposure work):
Hazard mask — compare the hazard raster to the intensity threshold → 1 exposed / 0 not.
Overlay population — resample the mask to the population grid and multiply.
Zonal statistics — sum exposed population per subdivision for every return period, then combine them into an annual average (each return period’s extra exposure weighted by 1 / return period).
Facilities — read the hazard value at each facility and record the lowest return period that exposes it.
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); unused by this template
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": ["uc1"]}
hazard = ""
# --- User parameters ---
hazard = "flood"
intensity_threshold = None # None = the hazard's default (flood 0.5, cyclone 33, earthquake 0.22)
return_period = 100 # years; earthquakes only have 475
climate_scenario = "current" # current | future (ignored for earthquakes)
aggregation_level = 2
infrastructure_layers = ["health"]
datasets_url = "" # hazard rasters: a folder or URL (https://, s3://, az://) holding the hazard .tif files
Source
# Parameters
run_id = "b51eb302-ab69-48c2-8074-154dc14c4d9e"
inputs_dir = "/app/data/work/b51eb302-ab69-48c2-8074-154dc14c4d9e/inputs"
output_dir = "/app/data/work/b51eb302-ab69-48c2-8074-154dc14c4d9e/outputs"
area = {"id": 3, "code": "NPL.2_1", "name": "East", "level": 1, "country": "NPL", "country_name": "Nepal", "bbox": [86.1334, 26.3475, 88.204, 28.1128]}
area_geojson = "/app/data/work/b51eb302-ab69-48c2-8074-154dc14c4d9e/inputs/area.geojson"
subdivisions_geojson = "/app/data/work/b51eb302-ab69-48c2-8074-154dc14c4d9e/inputs/subdivisions.geojson"
stac_item = {}
stac_item_json = ""
stac_collection = ""
stac_api_url = ""
stac_catalog_profile = ""
filters = {"hazard": ["flood"], "use_case": ["uc1"]}
hazard = "flood"
datasets_url = "https://goplaygroundstorage.blob.core.windows.net/notebook-factory-playground-static-datasets-container/mapaction/216-hazard"
return_period = 100
climate_scenario = "current"
aggregation_level = 2
infrastructure_layers = ["health"]
Source
import json, os, warnings
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
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()
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")
subdivisions[["code", "name", "level"]].head()Area: East (NPL) · 3 subdivisions
1 · Datasets¶
Hazard rasters are global GeoTIFFs (ideally Cloud-Optimized) directly inside the folder or URL given as the
datasets_urlparameter (https://,s3://,az://). Only the part inside the area is read.Population is WorldPop’s 1 km country raster, downloaded once per country into a scratch cache (under
TMPDIR).Health facilities are read straight from OpenStreetMap’s Layercake GeoParquet (no local copy).
Source
import tempfile
import uuid
import urllib.request
import duckdb
import rasterio
from rasterio.mask import mask as rio_mask
from rasterio.warp import Resampling, reproject
from rasterstats import zonal_stats
# Where the hazard rasters live: the `datasets_url` parameter, a folder or a URL (https://, s3://, az://) that holds
# the hazard .tif files directly. The files are too big to ship in a template bundle, so the template points at them.
# A private bucket's credentials must be template secrets, never part of this value.
DATASETS_DIR = datasets_url.strip().rstrip("/")
if not DATASETS_DIR:
raise ValueError("Set the `datasets_url` parameter to the folder or URL that holds the hazard rasters")
DATASETS_REMOTE = "://" in DATASETS_DIR
if not DATASETS_REMOTE and not Path(DATASETS_DIR).is_dir():
raise FileNotFoundError(f"datasets_url is not a folder: {DATASETS_DIR!r}")
# Scratch space for files we download (WorldPop). 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"
# Remote rasters: don't list the bucket folder on every open, and only treat .tif files as rasters.
os.environ.setdefault("GDAL_DISABLE_READDIR_ON_OPEN", "EMPTY_DIR")
os.environ.setdefault("CPL_VSIL_CURL_ALLOWED_EXTENSIONS", ".tif")
# (hazard, climate scenario) -> file pattern, return periods (years), default threshold.
# File names inside `datasets_url`; `{rp}` is the return period.
RPS = [10, 50, 100, 500, 1000]
HAZARDS = {
("flood", "current"): ("wrl_risk_ras_wri_flood-rp{rp}y.tif", RPS, 0.5),
("flood", "future"): ("wrl_risk_ras_wri_flood-future-rp{rp}y.tif", RPS, 0.5),
("cyclone", "current"): ("wrl_risk_ras_4tu_cyclone-rp{rp}y.tif", RPS, 33.0),
("cyclone", "future"): ("wrl_risk_ras_4tu_cyclone-future-rp{rp}y.tif", RPS, 33.0),
("earthquake", "current"): ("wrl_risk_ras_gem_earthquake-rp{rp}y.tif", [475], 0.22),
}
# Cloud-hosted datasets: WorldPop 1 km (one small file per country) and OpenStreetMap Layercake (one global GeoParquet).
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"
HEALTH_AMENITIES = ("hospital", "clinic", "doctors", "dentist", "pharmacy") # older tagging; healthcare=* is the newer one
SCHOOL_AMENITIES = ("school", "kindergarten", "college", "university")
LAYER_LABELS = {"health": "Health facilities", "schools": "Schools"}
LAYER_COLORS = {"health": [31, 36, 48], "schools": [30, 120, 200]} # map colour of each infrastructure layer
def get_dataset(pattern, **fmt):
"""Location (path or URL) of a hazard file inside `datasets_url`."""
rel = pattern.format(**fmt)
if DATASETS_REMOTE:
return f"{DATASETS_DIR}/{rel}" # existence is checked when the raster is opened
path = Path(DATASETS_DIR) / rel
if not path.exists():
raise FileNotFoundError(f"dataset not found: {path}")
return str(path)
def open_raster(path):
"""rasterio.open with the location in the error (remote failures are otherwise hard to read)."""
try:
return rasterio.open(path)
except rasterio.errors.RasterioIOError as e:
raise RuntimeError(f"Cannot open raster {path}: {e}") from e
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 load_layercake_points(bbox, where):
"""OSM points inside bbox (xmin, ymin, xmax, ymax) from Layercake's POIs layer, via DuckDB range reads.
`where` is an SQL filter on the POIs columns. A feature is the centre of its OSM bounding box, so
building polygons (a hospital, a school campus) become a single point."""
xmin, ymin, xmax, ymax = bbox
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs;")
df = con.execute(f"""
SELECT type || '/' || id AS osm_id,
(bbox.xmin + bbox.xmax) / 2 AS x, (bbox.ymin + bbox.ymax) / 2 AS y
FROM read_parquet('{LAYERCAKE_POIS}')
WHERE bbox.xmin <= {xmax} AND bbox.xmax >= {xmin} AND bbox.ymin <= {ymax} AND bbox.ymax >= {ymin}
AND ({where})
""").df()
return gpd.GeoDataFrame(df[["osm_id"]], geometry=gpd.points_from_xy(df.x, df.y), crs=4326)
def _in(values):
return ", ".join(f"'{v}'" for v in values)
def load_health_facilities(bbox):
return load_layercake_points(bbox, f"healthcare IS NOT NULL OR amenity IN ({_in(HEALTH_AMENITIES)})")
def load_schools(bbox):
"""Schools, kindergartens, colleges and universities."""
return load_layercake_points(bbox, f"amenity IN ({_in(SCHOOL_AMENITIES)})")
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_health_facilities, "schools": load_schools} # layer -> loader(bbox) returning points with an `osm_id` column
def read_window(path, geoms):
"""Read only the part of a raster inside `geoms`; pixels outside (or nodata) become 0."""
with open_raster(path) as src:
data, transform = rio_mask(src, geoms, crop=True, filled=True)
nodata, crs = src.nodata, src.crs
arr = data[0].astype("float64")
invalid = ~np.isfinite(arr)
if nodata is not None:
invalid |= arr == nodata
arr[invalid] = 0.0
return arr, transform, crs
def match_grid(arr, transform, crs, shape, like_transform, like_crs):
"""Resample `arr` onto another raster's grid (nearest neighbour keeps hazard values intact)."""
out = np.zeros(shape, dtype="float64")
reproject(source=arr, destination=out, src_transform=transform, src_crs=crs,
dst_transform=like_transform, dst_crs=like_crs, resampling=Resampling.nearest)
return out
def zonal_sum(arr, transform, zones):
"""Sum raster values inside each zone polygon (pixel centres)."""
stats = zonal_stats(list(zones.geometry), arr, affine=transform, stats="sum", nodata=-999)
return np.array([s["sum"] or 0.0 for s in stats])
def sample_raster(path, points):
"""Raster value at each point (0 for nodata / outside the raster)."""
with open_raster(path) as src:
vals = np.array([v[0] for v in src.sample([(p.x, p.y) for p in points])], dtype="float64")
nodata = src.nodata
vals[~np.isfinite(vals)] = 0.0
if nodata is not None:
vals[vals == nodata] = 0.0
return vals
# Resolve the parameters. No data for the requested combination is an error, never fake data.
scenario = "current" if hazard == "earthquake" else climate_scenario
if (hazard, scenario) not in HAZARDS:
raise ValueError(f"No dataset for hazard={hazard!r}, climate_scenario={scenario!r} yet")
pattern, return_periods, default_threshold = HAZARDS[(hazard, scenario)]
threshold = default_threshold if intensity_threshold is None else intensity_threshold
chosen_rp = return_periods[0] if len(return_periods) == 1 else return_period
if chosen_rp not in return_periods:
raise ValueError(f"return_period must be one of {return_periods}, got {return_period}")
print(f"{hazard} · {scenario} · threshold {threshold} · {chosen_rp}-yr (all of {return_periods} are computed)")flood · current · threshold 0.5 · 100-yr (all of [10, 50, 100, 500, 1000] are computed)
2 · Population exposure¶
For every return period: mask the hazard where it exceeds the threshold, multiply by population, and sum per subdivision. The annual average adds each return period’s extra exposure divided by that return period.
Source
pop, pop_tf, pop_crs = read_window(get_population(iso), list(area_gdf.geometry))
stats = subdivisions.copy()
stats["population"] = zonal_sum(pop, pop_tf, stats)
annual, prev = np.zeros(len(stats)), None
for rp in sorted(return_periods):
haz, haz_tf, haz_crs = read_window(get_dataset(pattern, rp=rp), list(area_gdf.geometry))
haz = match_grid(haz, haz_tf, haz_crs, pop.shape, pop_tf, pop_crs)
exposed_rp = zonal_sum(pop * (haz > threshold), pop_tf, stats)
stats[f"exposed_rp{rp}"] = exposed_rp
# the first return period counts in full; later ones only add the people newly exposed
annual += exposed_rp / rp if prev is None else (exposed_rp - prev) / rp
prev = exposed_rp
stats["exposed"] = stats[f"exposed_rp{chosen_rp}"]
stats["exposed_share"] = (stats["exposed"] / stats["population"].replace(0, np.nan)).fillna(0)
stats["exposed_annual_avg_pct"] = np.where(stats["population"] > 0, annual / stats["population"] * 100, 0.0)
print(f"Population: {stats['population'].sum():,.0f} · exposed at {chosen_rp}-yr: {stats['exposed'].sum():,.0f}")Population: 10,127,225 · exposed at 100-yr: 260,171
3 · Facilities¶
Health facilities and schools come from OpenStreetMap (Layercake). Each facility is assigned to a subdivision, then the hazard raster is read at its location for every return
period. lowest_rp is the most frequent (lowest) return period that exposes it; empty means not exposed.
Source
fac_frames = []
for layer in infrastructure_layers:
if layer not in INFRASTRUCTURE:
raise ValueError(f"No dataset for infrastructure layer {layer!r} yet")
fac_id = "osm_id"
fac = INFRASTRUCTURE[layer](tuple(area_gdf.total_bounds))
fac = gpd.sjoin(fac[[fac_id, "geometry"]], stats[["code", "geometry"]], how="inner").drop(columns="index_right")
fac = fac.drop_duplicates(subset=fac_id).reset_index(drop=True)
fac["layer"] = layer
fac["lowest_rp"] = np.nan
for rp in sorted(return_periods):
hit = sample_raster(get_dataset(pattern, rp=rp), fac.geometry) > threshold
fac[f"exposed_rp{rp}"] = hit
fac.loc[hit & fac["lowest_rp"].isna(), "lowest_rp"] = rp
fac["exposed"] = fac[f"exposed_rp{chosen_rp}"]
fac_frames.append(fac)
facilities = gpd.GeoDataFrame(pd.concat(fac_frames, ignore_index=True), crs=4326) if fac_frames else gpd.GeoDataFrame(
columns=["layer", "code", "exposed", "geometry"], crs=4326)
for layer in infrastructure_layers:
f = facilities[facilities.layer == layer]
stats[f"{layer}_total"] = f.groupby("code").size().reindex(stats["code"]).fillna(0).astype(int).values
stats[f"{layer}_exposed"] = f[f.exposed].groupby("code").size().reindex(stats["code"]).fillna(0).astype(int).values
print(f"{layer}: {len(f):,} facilities · exposed at {chosen_rp}-yr: {int(f.exposed.sum()):,}")
if infrastructure_layers:
print(f"Facilities: OpenStreetMap via Layercake, file last updated {layercake_last_modified()} "
"(Layercake's build date, not the date of the OSM data beneath it)")health: 634 facilities · exposed at 100-yr: 20
Facilities: OpenStreetMap via Layercake, file last updated Sun, 22 Nov 2026 15:52:36 GMT (Layercake's build date, not the date of the OSM data beneath it)
Source
cols = ["name", "population", "exposed", "exposed_share", "exposed_annual_avg_pct"]
cols += [c for c in stats.columns if c.endswith("_exposed") or c.endswith("_total")]
table = stats[cols].sort_values("exposed", ascending=False)
table["population"] = table["population"].round(0); table["exposed"] = table["exposed"].round(0)
table["exposed_annual_avg_pct"] = table["exposed_annual_avg_pct"].round(2)
table.to_csv(Path(output_dir) / "exposure_by_subdivision.csv", index=False)
stats.to_file(Path(output_dir) / "exposure_by_subdivision.geojson", driver="GeoJSON")
facilities.drop(columns="geometry").to_csv(Path(output_dir) / "facilities_exposure.csv", index=False)
table.style.format({"population": "{:,.0f}", "exposed": "{:,.0f}", "exposed_share": "{:.1%}"}).background_gradient(subset=["exposed_share"], cmap="OrRd")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, PolygonLayer, ScatterplotLayer
from manywidgets import Chart, Column, Legend, Row, Slider, 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="{:.0%}"):
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]} exposed", value=int(stats[f"{l}_exposed"].sum())) for l in infrastructure_layers]
Row(
Stat(label="Population", value=fmt_int(stats["population"].sum())),
Stat(label="Exposed population", value=fmt_int(stats["exposed"].sum())),
Stat(label="Share exposed", value=f"{stats['exposed'].sum() / max(stats['population'].sum(), 1):.1%}"),
*fac_stats,
gap="16px",
)Map — exposed population share per subdivision¶
Source
vmax = max(float(stats["exposed_share"].max()), 0.01)
zones_layer = PolygonLayer.from_geopandas(stats[["name", "population", "exposed", "exposed_share", "geometry"]], get_fill_color=colors_for(stats["exposed_share"], "OrRd", 0, vmax), get_line_color=[60, 60, 60], line_width_min_pixels=1, opacity=0.75)
layers = [zones_layer]
fac_layers = {}
for layer in infrastructure_layers:
fx = facilities[(facilities.layer == layer) & facilities.exposed]
if len(fx):
fac_layers[layer] = ScatterplotLayer.from_geopandas(fx[["layer", "geometry"]], get_fill_color=LAYER_COLORS[layer], radius_min_pixels=3)
layers.append(fac_layers[layer])
Map(layers)Source
toggles = [LayerToggle(layer=zones_layer, label="Exposed share")] + [LayerToggle(layer=l, label=f"Exposed {LAYER_LABELS[k].lower()}") for k, l in fac_layers.items()]
Row(Column(*toggles, gap="6px"), legend_for("OrRd", 0, vmax, title="Exposed population share"), gap="24px", align="start")Exposed population by subdivision¶
Source
bar_chart(table["name"], table["exposed"], title=f"{area_name} · {hazard} ≥ {threshold} · {chosen_rp}-yr · {scenario}", y_label="Exposed population")Reproduce or adapt¶
Download this notebook, set datasets_url to your hazard data (a folder or URL), set area_geojson / subdivisions_geojson to your own
boundaries and re-run it with standard Jupyter tooling. The published page is a frozen artefact; the method is not.