Population & infrastructure risk exposure
Dive deeper¶
How exposure grows with the return period¶
Rarer events reach more people. The bars show, for each return period, the share of each group that lives where the hazard exceeds the threshold.
Exposure by subdivision¶
Every subdivision; click a column header to sort. The same numbers are in exposure_by_subdivision.csv and exposure_by_subdivision.geojson.
Facilities¶
How this was produced¶
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 1 km population grid and multiply. Everyone is counted first; children under 5 and under 15 are then broken out of the same grid.
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’s centroid and record the lowest return period that exposes it.
Parameters used for this run¶
Sources¶
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"] # health | schools | airports | ports
population_year = 2025 # WorldPop R2025A covers 2015-2030 (later years are projections)
datasets_url = "" # hazard rasters: a folder or URL (https://, s3://, az://) holding the hazard .tif filesSource
# Parameters
run_id = "4dc50e40-acef-407e-bb16-9dab1edcfc1d"
inputs_dir = "/app/data/work/4dc50e40-acef-407e-bb16-9dab1edcfc1d/inputs"
output_dir = "/app/data/work/4dc50e40-acef-407e-bb16-9dab1edcfc1d/outputs"
area = {"id": 18260, "code": "HTI", "name": "Haiti", "level": 0, "country": "HTI", "country_name": "Haiti", "bbox": [-74.4812, 18.0218, -71.6181, 20.0904]}
area_geojson = "/app/data/work/4dc50e40-acef-407e-bb16-9dab1edcfc1d/inputs/area.geojson"
subdivisions_geojson = "/app/data/work/4dc50e40-acef-407e-bb16-9dab1edcfc1d/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
population_year = 2025
climate_scenario = "current"
aggregation_level = 2
infrastructure_layers = ["health", "schools", "airports", "ports"]
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: Haiti (HTI) · 41 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 R2025A: people per 1 km cell for the year
population_year. It is read through the WorldPop API, which sends only the cells inside the area (for an area over its limits, or if it does not answer, the notebook reads WorldPop’s own 1 km files of the country instead and crops them). Children are WorldPop’s age classes 0–4 (under 5) and 0–14 (under 15). TheWORLDPOP_API_KEYsecret raises the API’s limits. © WorldPop, University of Southampton, CC BY 4.0: population doi:10.5258/SOTON/WP00839, age and sex doi:10.5258/SOTON/WP00841.Health facilities, schools, airports and ports are OpenStreetMap features from the per-country GeoParquet extracts that the Humanitarian OpenStreetMap Team (HOT) publishes on HDX each month, read straight from the file (no local copy). Every feature becomes one point, its centroid. Health is
healthcare=*or hospital, clinic, doctors, dentist, pharmacy; schools areamenity=school; airportsaeroway=aerodrome; portsindustrial=port,harbour=yesorlanduse=port|harbour.
Source
import hashlib
import tempfile
import time
import uuid
import urllib.request
import duckdb
import rasterio
import requests
import shapely
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 the population rasters we fetch. 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 (through its API) and OpenStreetMap (HOT's GeoParquet extracts, one file per country and theme).
WORLDPOP_API = "https://api.worldpop.org/v3"
WORLDPOP_KEY = os.environ.get("WORLDPOP_API_KEY", "") # optional: a key raises the API's area and request limits
WORLDPOP_NODATA = -99999.0
USER_AGENT = {"User-Agent": "notebook-factory (IFRC Montandon use case 1)"}
HDX_PACKAGE = "https://data.humdata.org/api/3/action/package_show?id=hotosm_{iso}_{theme}"
HOT_URL = "https://production-raw-data-api.s3.amazonaws.com/ISO3/{ISO}/_layers/osm/{theme}.parquet"
HEALTH_AMENITIES = ("hospital", "clinic", "doctors", "dentist", "pharmacy") # older tagging; healthcare=* is the newer one
def _in(values):
return ", ".join(f"'{v}'" for v in values)
# infrastructure layer -> (HOT theme = file name, SQL filter on its columns; the columns are OpenStreetMap tags)
OSM_LAYERS = {
"health": ("health_facilities", f"healthcare IS NOT NULL OR amenity IN ({_in(HEALTH_AMENITIES)})"),
"schools": ("education_facilities", "amenity = 'school'"),
"airports": ("airports", "aeroway = 'aerodrome'"), # the airport itself, not its runways, taxiways or helipads
"ports": ("sea_ports", "industrial = 'port' OR harbour = 'yes' OR landuse IN ('port', 'harbour')"),
}
OSM_SOURCES = {} # layer -> URL of the HOT file that was read
LAYER_LABELS = {"health": "Health facilities", "schools": "Schools", "airports": "Airports", "ports": "Ports"}
LAYER_COLORS = {"health": [31, 36, 48], "schools": [30, 120, 200], "airports": [120, 60, 170], "ports": [0, 140, 130]} # map colour of each layer
# Population groups: key -> (WorldPop layer, age range). Everyone is the headline; children are broken out of the same grid.
POP_GROUPS = {"": ("population", None), "under5": ("agesex", (0, 4)), "under15": ("agesex", (0, 14))}
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
class WorldPopNoAnswer(Exception):
"""The API cannot give this area: it is over its limits (`reason` is its error code), or it did not answer."""
def __init__(self, reason):
super().__init__(reason)
self.reason = reason
API_LIMIT_KM2 = 500_000 if WORLDPOP_KEY else 100_000 # the API's area limit for this caller (a key raises it)
API_MAX_PARTS = 900 # it refuses more than 1,000 parts in one request
# WorldPop's age classes as (file code, first age, last age). An age range takes the classes inside it, as the API does.
AGE_CLASSES = [(f"{start:02d}", start, end) for start, end in [(0, 0), (1, 4), *[(a, a + 4) for a in range(5, 90, 5)], (90, 120)]]
def worldpop_raster_request(geom, year, layer, age_range):
"""One POST /raster call: (GeoTIFF bytes of people per 1 km cell for the cells whose centre is inside `geom`, people counted).
Raises WorldPopNoAnswer when the API refuses the area as too large or too complex, or keeps dropping the connection."""
body = {"geojson": json.loads(shapely.to_geojson(geom)), "year": int(year), "layer": layer, "resolution": "1km"}
if layer == "agesex":
body["bands"] = "sum" # one band: the people of the chosen ages, both sexes
body["age_range"] = list(age_range)
headers = {**USER_AGENT, **({"X-API-Key": WORLDPOP_KEY} if WORLDPOP_KEY else {})}
dropped = ""
for attempt in range(4):
try:
r = requests.post(f"{WORLDPOP_API}/raster", json=body, headers=headers, timeout=(30, 300))
except requests.RequestException as e: # a dropped connection or a timeout: wait, then try again
dropped = type(e).__name__
time.sleep(3 * (attempt + 1))
continue
if r.status_code in (429, 502, 503, 504) and attempt < 3:
error = r.json().get("error") if "json" in r.headers.get("content-type", "") else ""
if error == "rate_limit_exceeded":
break # the day's quota is used up: waiting a few seconds won't help
time.sleep(min(float(r.headers.get("Retry-After", 3 * (attempt + 1))), 60))
continue
break
else:
raise WorldPopNoAnswer(f"no answer: {dropped}")
if r.ok:
return r.content, float(r.headers.get("X-Total-Population", "nan"))
try:
err = r.json()
except ValueError:
err = {}
if r.status_code == 413 and err.get("error") in ("area_limit_exceeded", "too_many_parts", "geometry_too_complex", "raster_too_large"):
raise WorldPopNoAnswer(err["error"])
raise RuntimeError(f"WorldPop API {r.status_code} {err.get('error', '')}: {err.get('message', r.text[:200])}")
def _polygons(geom):
return shapely.MultiPolygon([p for p in shapely.get_parts(geom) if p.geom_type == "Polygon"])
def _lean(geom, max_vertices=40_000):
"""Simplify until the API's 50,000-vertex limit is safe: a few hundred metres of edge are far below a 1 km cell."""
tolerance = 0.0005
while shapely.get_num_coordinates(geom) > max_vertices:
geom = shapely.simplify(geom, tolerance)
tolerance *= 2
return geom
def download(url, destination):
"""Fetch a whole file into the cache (the server ignores range requests), under a temporary name so runs can overlap."""
if destination.exists():
return destination
destination.parent.mkdir(parents=True, exist_ok=True)
tmp = destination.with_suffix(f".{uuid.uuid4().hex}.part")
failure = ""
for attempt in range(4):
try:
with requests.get(url, stream=True, headers=USER_AGENT, timeout=(30, 300)) as r:
r.raise_for_status()
with open(tmp, "wb") as out:
for chunk in r.iter_content(1 << 20):
out.write(chunk)
tmp.replace(destination) # only a complete file ever gets the final name
return destination
except requests.RequestException as e:
failure = type(e).__name__
tmp.unlink(missing_ok=True)
time.sleep(3 * (attempt + 1))
raise RuntimeError(f"Could not download {url}: {failure}")
def worldpop_country_urls(iso, year):
"""URLs of WorldPop's own 1 km files of a country: the total-population file and the age-sex bands (f_00 ... m_90). The API lists them;
if it does not answer, the usual paths are used."""
headers = {**USER_AGENT, **({"X-API-Key": WORLDPOP_KEY} if WORLDPOP_KEY else {})}
try:
r = requests.get(f"{WORLDPOP_API}/countries/{iso.upper()}/files", params={"year": int(year)}, headers=headers, timeout=60)
r.raise_for_status()
listing = r.json()
return listing["population"]["1km"], listing["agesex"]["1km"]["bands"]
except (requests.RequestException, KeyError, ValueError, TypeError):
pass
base = f"https://data.worldpop.org/GIS/%s/Global_2015_2030/R2025A/{year}/{iso.upper()}/v1/1km_ua/constrained/{iso.lower()}_%s_{year}_CN_1km_R2025A_UA_v1.tif"
return base % ("Population", "pop"), {f"{sex}_{c}": base % ("AgeSex_structures", f"{sex}_{c}") for sex in ("f", "m") for c, _, _ in AGE_CLASSES}
def worldpop_from_files(iso, year, layer, age_range):
"""The raster the API would send, built from WorldPop's own files of the country (EPSG:4326, nodata -99999), cached: the total-population file, or
the age-sex bands of women and men summed (there are no both-sex bands). Whole files are fetched (no range reads), but the area has no limit;
the caller crops the result to the area."""
if not iso:
raise ValueError("The area's country is needed to read WorldPop's country files")
classes = [] if layer == "population" else [c for c, start, end in AGE_CLASSES if start >= age_range[0] and end <= age_range[1]]
path = CACHE_DIR / "worldpop" / f"files_{iso.lower()}_{year}_{layer}_{'-'.join(classes) or 'all'}.tif"
if path.exists():
return path
pop_url, bands = worldpop_country_urls(iso, year)
urls = [pop_url] if layer == "population" else [bands[f"{sex}_{c}"] for sex in ("f", "m") for c in classes]
folder = CACHE_DIR / "worldpop-files" / f"{iso.lower()}_{year}"
sources = [download(u, folder / u.rsplit("/", 1)[-1]) for u in urls]
total = nobody = profile = None
for source in sources:
with rasterio.open(source) as src:
values = src.read(1).astype("float64")
gap = ~np.isfinite(values) | ((values == src.nodata) if src.nodata is not None else False)
if total is None:
profile, total, nobody = src.profile, np.zeros(values.shape), np.ones(values.shape, dtype=bool)
elif values.shape != total.shape or tuple(src.transform) != tuple(profile["transform"]):
raise RuntimeError(f"{source.name} is not on the same grid as {sources[0].name}")
total += np.where(gap, 0.0, values)
nobody &= gap
for key in ("blockxsize", "blockysize", "tiled", "interleave"):
profile.pop(key, None)
profile.update(driver="GTiff", dtype="float32", count=1, nodata=WORLDPOP_NODATA, compress="deflate")
tmp = path.with_suffix(f".{uuid.uuid4().hex}.part") # unique per run: runs can overlap
with rasterio.open(tmp, "w", **profile) as dst:
dst.write(np.where(nobody, WORLDPOP_NODATA, total).astype("float32"), 1)
tmp.replace(path)
print(f"WorldPop {layer}{tuple(age_range) if age_range else ''} {year}: {len(sources)} file(s) of {iso} ({sum(s.stat().st_size for s in sources) / 1e6:.1f} MB)")
return path
def fetch_worldpop(geom, year, layer, age_range=None, iso=None):
"""Path of a GeoTIFF of WorldPop people per 1 km cell for an area (EPSG:4326, nodata -99999), cached. It covers the area; the caller crops it.
The API sends only the cells inside the area. When the area is over its limits (too big, too many parts), or the API does not answer, the same
raster is built from WorldPop's own file of the area's country (`iso`) instead."""
geom = _lean(_polygons(geom))
area_km2 = gpd.GeoSeries([geom], crs=4326).to_crs("ESRI:54009").area.iloc[0] / 1e6
parts = len(shapely.get_parts(geom))
key = hashlib.sha1(f"{shapely.to_wkb(geom).hex()}|{year}|{layer}|{age_range}".encode()).hexdigest()[:16]
path = CACHE_DIR / "worldpop" / f"{layer}_{year}_{key}.tif"
if path.exists():
return path
if area_km2 > API_LIMIT_KM2:
why = f"the area is {area_km2:,.0f} km², over the API's {API_LIMIT_KM2:,} km² limit"
elif parts > API_MAX_PARTS:
why = f"the area has {parts:,} parts, over the API's limit of 1,000"
else:
try:
content, people = worldpop_raster_request(geom, year, layer, age_range)
except WorldPopNoAnswer as e:
why = f"the API gave no raster ({e.reason})"
else:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(f".{uuid.uuid4().hex}.part") # unique per run: runs can overlap
tmp.write_bytes(content)
tmp.replace(path) # only a complete file ever gets the final name
print(f"WorldPop {layer}{age_range or ''} {year}: 1 request, {people:,.0f} people in the area's cells")
return path
print(f"WorldPop: {why}; reading WorldPop's own file of {iso or 'the country'} instead")
return worldpop_from_files(iso, year, layer, age_range)
def hot_layer_url(iso, theme):
"""URL of HOT's GeoParquet for one country and theme. HDX lists it as that dataset's GeoParquet resource, so ask HDX first
(the path is HOT's to change) and fall back to the usual path."""
usual = HOT_URL.format(ISO=iso.upper(), theme=theme)
try:
r = requests.get(HDX_PACKAGE.format(iso=iso.lower(), theme=theme), headers=USER_AGENT, timeout=30)
r.raise_for_status()
for resource in r.json()["result"]["resources"]:
if (resource.get("format") or "").lower() == "geoparquet":
return resource["url"]
except (requests.RequestException, KeyError, ValueError):
pass
return usual
def hot_last_modified(url):
"""When HOT last rebuilt this file (HTTP Last-Modified), which is the date of its OpenStreetMap snapshot."""
try:
req = urllib.request.Request(url, method="HEAD", headers=USER_AGENT)
with urllib.request.urlopen(req, timeout=30) as r:
return r.headers.get("Last-Modified", "unknown")
except Exception:
return "unknown"
def load_osm_points(iso, bbox, layer):
"""OpenStreetMap features of one infrastructure layer inside bbox (xmin, ymin, xmax, ymax), each reduced to its centroid.
HOT cuts one extract per country and theme (the columns are the OSM tags); DuckDB reads only the rows in the box."""
theme, where = OSM_LAYERS[layer]
url = OSM_SOURCES[layer] = hot_layer_url(iso, theme)
xmin, ymin, xmax, ymax = bbox
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs; INSTALL spatial; LOAD spatial;")
try:
df = con.execute(f"""
SELECT id AS osm_id, name, name_en, ST_X(ST_Centroid(geom)) AS x, ST_Y(ST_Centroid(geom)) AS y
FROM read_parquet('{url}')
WHERE bbox.xmin <= {xmax} AND bbox.xmax >= {xmin} AND bbox.ymin <= {ymax} AND bbox.ymax >= {ymin}
AND ({where})
""").df()
except duckdb.Error as e:
raise RuntimeError(f"No usable HOT OpenStreetMap '{theme}' layer for {iso} ({url}): {e}") from e
return gpd.GeoDataFrame(df[["osm_id", "name", "name_en"]], geometry=gpd.points_from_xy(df.x, df.y), crs=4326)
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, first for everyone and then for children under 5 and under 15 (the same mask on the same grid). The annual average adds each return period’s extra exposure divided by that return period.
Source
area_geom = shapely.union_all(list(area_gdf.geometry))
geoms = list(area_gdf.geometry)
# People per 1 km cell: everyone, then children under 5 and under 15 (all on the same grid).
pops, pop_tf, pop_crs = {}, None, None
for group, (wp_layer, ages) in POP_GROUPS.items():
arr, tf, crs = read_window(fetch_worldpop(area_geom, population_year, wp_layer, ages, iso), geoms)
if pop_tf is None:
pop_tf, pop_crs = tf, crs
elif arr.shape != pops[""].shape or tf != pop_tf:
raise RuntimeError(f"WorldPop grid for {group!r} does not match the total population grid")
pops[group] = arr
def col(base, group):
"""Column of a statistic for a population group: the total keeps the plain name (exposed), a group adds its key (exposed_under5)."""
return f"{base}_{group}" if group else base
stats = subdivisions.copy()
for group, pop in pops.items():
stats[col("population", group)] = zonal_sum(pop, pop_tf, stats)
annual, prev = {g: np.zeros(len(stats)) for g in pops}, {g: None for g in pops}
for rp in sorted(return_periods):
haz, haz_tf, haz_crs = read_window(get_dataset(pattern, rp=rp), geoms)
hit = match_grid(haz, haz_tf, haz_crs, pops[""].shape, pop_tf, pop_crs) > threshold
for group, pop in pops.items():
exposed_rp = zonal_sum(pop * hit, pop_tf, stats)
stats[f"{col('exposed', group)}_rp{rp}"] = exposed_rp
# the first return period counts in full; later ones only add the people newly exposed
annual[group] += exposed_rp / rp if prev[group] is None else (exposed_rp - prev[group]) / rp
prev[group] = exposed_rp
for group in pops:
pop_col, exp_col = col("population", group), col("exposed", group)
stats[exp_col] = stats[f"{exp_col}_rp{chosen_rp}"]
stats[f"{exp_col}_share"] = (stats[exp_col] / stats[pop_col].replace(0, np.nan)).fillna(0)
stats[f"{exp_col}_annual_avg_pct"] = np.where(stats[pop_col] > 0, annual[group] / stats[pop_col] * 100, 0.0)
print(f"Population: {stats['population'].sum():,.0f} · exposed at {chosen_rp}-yr: {stats['exposed'].sum():,.0f}")
print(f"Children exposed at {chosen_rp}-yr: under 5 {stats['exposed_under5'].sum():,.0f} · under 15 {stats['exposed_under15'].sum():,.0f}")
if not stats["exposed_under5"].sum() <= stats["exposed_under15"].sum() <= stats["exposed"].sum() * 1.001:
print("Warning: the age groups are not nested (under 5 <= under 15 <= everyone); check the WorldPop rasters")WorldPop population 2025: 1 request, 11,837,258 people in the area's cells
WorldPop agesex(0, 4) 2025: 1 request, 1,227,242 people in the area's cells
WorldPop agesex(0, 14) 2025: 1 request, 3,668,478 people in the area's cells
Population: 11,693,557 · exposed at 100-yr: 21,345
Children exposed at 100-yr: under 5 2,214 · under 15 6,618
3 · Facilities¶
Health facilities, schools, airports and ports come from OpenStreetMap (HOT’s per-country extracts); each is one point, its centroid. 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 OSM_LAYERS:
raise ValueError(f"No dataset for infrastructure layer {layer!r} yet")
fac_id = "osm_id"
fac = load_osm_points(iso, tuple(area_gdf.total_bounds), layer)
fac = gpd.sjoin(fac[[fac_id, "name", "name_en", "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", "name", "name_en", "lowest_rp", "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()):,}")
HOT_MODIFIED = {layer: hot_last_modified(OSM_SOURCES[layer]) for layer in infrastructure_layers} # the date of each OpenStreetMap snapshot
if infrastructure_layers:
print("Facilities: OpenStreetMap via HOT's per-country extracts, files updated " + ", ".join(f"{layer} {HOT_MODIFIED[layer]}" for layer in infrastructure_layers))health: 2,236 facilities · exposed at 100-yr: 4
schools: 5,212 facilities · exposed at 100-yr: 5
airports: 16 facilities · exposed at 100-yr: 0
ports: 9 facilities · exposed at 100-yr: 0
Facilities: OpenStreetMap via HOT's per-country extracts, files updated health Mon, 02 Nov 2026 15:05:26 GMT, schools Mon, 02 Nov 2026 15:03:59 GMT, airports Mon, 02 Nov 2026 15:12:26 GMT, ports Mon, 02 Nov 2026 15:12:50 GMT
Source
cols = ["name", "population", "exposed", "exposed_share", "exposed_annual_avg_pct",
"population_under5", "exposed_under5", "exposed_under5_share", "population_under15", "exposed_under15", "exposed_under15_share"]
cols += [c for c in stats.columns if c.endswith("_exposed") or c.endswith("_total")]
table = stats[cols].sort_values("exposed", ascending=False)
for c in ("population", "exposed", "population_under5", "exposed_under5", "population_under15", "exposed_under15"):
table[c] = table[c].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)Results¶
The figures, map and charts are in the Overview above. These cells build them.
Source
# Visualisation: lonboard for the map, manywidgets for the figures, tables, charts and controls.
# 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 lonboard.layer_extension import DataFilterExtension
from ipywidgets import jsdlink
from manywidgets import Chart, Column, Dropdown, Grid, Legend, Stat, Table, Text, Toggle
from manywidgets.lonboard import FilterBinder
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 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 switchSource
# ======================= Overview (presentation only) =======================================================
# Nothing from here down analyses anything. These cells turn the results above into the Overview at the top of the
# page. Each cell with a `label` is tagged `remove-cell`, so it shows only where an {embed} directive near the top
# of the notebook places it: that is how a notebook, which shows cells in the order they run, can lead with its answer.
# A failure in this layer never fails the run (see safe()).
import html
try:
from manywidgets import Fullscreen
except ImportError: # manywidgets < 0.2 has no full-screen panels: the figures still show, without drill-downs
Fullscreen = None
esc = html.escape # every string that comes from OpenStreetMap or a parameter goes through this before it reaches a Text
NUM = {"format": "number", "align": "right", "digits": 0}
ONE = {"format": "number", "align": "right", "digits": 1}
TWO = {"format": "number", "align": "right", "digits": 2}
def n(x, digits=0):
return f"{float(x):,.{digits}f}"
def short(x):
"""A big number in words for a caption: 5.2 million."""
x = float(x)
for limit, word in ((1e9, "billion"), (1e6, "million")):
if x >= limit:
return f"{x / limit:,.1f} {word}"
return n(x)
def link(text, href):
"""A link that reads in light and dark mode (Text renders markdown with no link styling), safe for strings from parameters."""
return f'<a href="{esc(str(href), quote=True)}" target="_blank" rel="noopener" style="color:inherit;text-decoration:underline">{esc(str(text))}</a>'
def fmt_name(local, english):
"""'Baireni Hospital (बैरेनी अस्पताल)': the English name first when OpenStreetMap has one, the local name in brackets."""
local = str(local).strip() if pd.notna(local) else ""
english = str(english).strip() if pd.notna(english) else ""
if english and local and english != local:
return f"{english} ({local})"
return english or local or "(unnamed)"
def md_text(markdown):
return Text(value=markdown, markdown=True)
def safe(build, what):
"""Run a builder; if the data for it is missing or odd, show a one-line note instead of failing the run."""
try:
return build()
except Exception as exc:
return md_text(f"*{what} is not available for this run ({type(exc).__name__}).*")
def expandable(child, panel, widget_id):
"""`child`, with a button that opens `panel` full screen. The widget_id also makes a shareable link: ?fullscreen=<id>."""
if not Fullscreen:
return child
return Fullscreen(child, fullscreen=panel, widget_id=widget_id) if panel is not None else Fullscreen(child, widget_id=widget_id)
def panel(title, body, *extras):
return Column(md_text(f"## {title}\n\n{body}"), *extras, gap="16px")
STAT_STYLE = {"--mw-color-border": "transparent", "--mw-color-surface": "transparent", "--mw-stat-min-width": "0",
"--mw-stat-value-size": "clamp(1.5rem, 6vw, 2.1rem)", "--mw-font-size-sm": "12px", "--mw-panel-padding-x": "14px", "--mw-panel-padding-y": "4px"}
def figure(label, value, caption, detail, widget_id):
"""A headline figure: the number, one muted line of context under it, and a button that opens `detail` full screen."""
card = Column(Stat(label=label, value=value, style=STAT_STYLE),
md_text(f'<span style="display:block;padding:0 14px 8px;font-size:13px;opacity:.7">{caption}</span>'), gap="0")
return expandable(card, detail, widget_id)
# ---- the numbers, each from a variable the analysis already made ----------------------------------------------------------------
run_at = pd.Timestamp.now(tz="UTC") # when this notebook ran
hazard_label = {"flood": "riverine flood", "cyclone": "tropical cyclone", "earthquake": "earthquake"}.get(hazard, hazard)
GROUP_NAMES = {"": "Everyone", "under5": "Under 5", "under15": "Under 15"}
pop_t = {g: float(stats[col("population", g)].sum()) for g in GROUP_NAMES} # people in the area
exp_t = {g: float(stats[col("exposed", g)].sum()) for g in GROUP_NAMES} # exposed at the chosen return period
share_t = {g: exp_t[g] / pop_t[g] if pop_t[g] else 0.0 for g in GROUP_NAMES}
annual_t = {g: float(annual[g].sum()) for g in GROUP_NAMES} # expected people exposed in an average year
rps = sorted(return_periods)
exp_rp = {g: [float(stats[f"{col('exposed', g)}_rp{rp}"].sum()) for rp in rps] for g in GROUP_NAMES}
n_sub, n_hit = len(stats), int((stats["exposed"] > 0).sum())
selected = list(infrastructure_layers)
selected_labels = ", ".join(LAYER_LABELS[k] for k in selected)
fac_by_layer = {k: facilities[facilities["layer"] == k] for k in selected}
fac_total = {k: len(f) for k, f in fac_by_layer.items()}
fac_exposed = {k: int(f["exposed"].sum()) for k, f in fac_by_layer.items()}
fac_frequent = {k: int(f[f"exposed_rp{rps[0]}"].sum()) if len(f) else 0 for k, f in fac_by_layer.items()} # reached even by the most frequent return period
n_fac_total, n_fac_exposed, n_fac_frequent = sum(fac_total.values()), sum(fac_exposed.values()), sum(fac_frequent.values())
event = f"{chosen_rp}-year {hazard_label}"Source
def top_subdivisions(order, group="", limit=10, title=""):
"""The `limit` subdivisions with the most people exposed (or the highest share) as a Table."""
ranked = stats.sort_values(order, ascending=False).head(limit)
if group:
rows = [{"code": r["code"], "name": str(r["name"]), "group": r[col("exposed", group)], "share": r[f"{col('exposed', group)}_share"] * 100, "all": r["exposed"]}
for _, r in ranked.iterrows()]
columns = [{"key": "name", "label": "Subdivision"}, {"key": "group", "label": f"{GROUP_NAMES[group]} exposed", **NUM},
{"key": "share", "label": "Share (%)", **ONE}, {"key": "all", "label": "Everyone exposed", **NUM}]
else:
rows = [{"code": r["code"], "name": str(r["name"]), "all": r["exposed"], "share": r["exposed_share"] * 100, "u5": r["exposed_under5"], "u15": r["exposed_under15"]}
for _, r in ranked.iterrows()]
columns = [{"key": "name", "label": "Subdivision"}, {"key": "all", "label": "Exposed", **NUM}, {"key": "share", "label": "Share (%)", **ONE},
{"key": "u5", "label": "Under 5", **NUM}, {"key": "u15", "label": "Under 15", **NUM}]
return Table(rows, columns, id_key="code", title=title, sortable=False)
def groups_table():
rows = [{"group": GROUP_NAMES[g], "population": pop_t[g], "exposed": exp_t[g], "share": share_t[g] * 100} for g in GROUP_NAMES]
return Table(rows, [{"key": "group", "label": ""}, {"key": "population", "label": "Population", **NUM}, {"key": "exposed", "label": f"Exposed ({chosen_rp}-yr)", **NUM},
{"key": "share", "label": "Share (%)", **ONE}], id_key="group", title="By age group", sortable=False)
def rp_chart(height=300):
chart = Chart(chart_type="bar", title="Share of each group exposed, by return period", y_label="% of the group's population", height=height, legend_enabled=True)
chart.set_options(scales={"x": {"type": "category"}, "y": {"beginAtZero": True}})
colors = {"": "#E4572E", "under5": "#1f4e79", "under15": "#7f8ea3"}
for g in GROUP_NAMES:
chart.add_series(x=[f"{rp}-yr" for rp in rps], y=[round(100 * e / pop_t[g], 2) if pop_t[g] else 0.0 for e in exp_rp[g]], name=GROUP_NAMES[g], series_type="bar", color=colors[g])
return chart
def rp_table():
rows = [{"rp": f"{rp} years", "all": exp_rp[""][i], "share": 100 * exp_rp[""][i] / pop_t[""] if pop_t[""] else 0.0, "u5": exp_rp["under5"][i], "u15": exp_rp["under15"][i]}
for i, rp in enumerate(rps)]
return Table(rows, [{"key": "rp", "label": "Return period"}, {"key": "all", "label": "People exposed", **NUM}, {"key": "share", "label": "Share (%)", **ONE},
{"key": "u5", "label": "Under 5", **NUM}, {"key": "u15", "label": "Under 15", **NUM}], id_key="rp", title="People exposed", sortable=False)
def annual_table():
"""How the yearly average is built: each return period adds the people newly exposed, weighted by 1 / return period."""
rows, prev = [], 0.0
for i, rp in enumerate(rps):
added = exp_rp[""][i] - prev
rows.append({"rp": f"{rp} years", "exposed": exp_rp[""][i], "added": added, "year": added / rp})
prev = exp_rp[""][i]
rows.append({"rp": "Average per year", "exposed": None, "added": None, "year": annual_t[""]})
return Table(rows, [{"key": "rp", "label": "Return period"}, {"key": "exposed", "label": "People exposed", **NUM}, {"key": "added", "label": "Added by this period", **NUM},
{"key": "year", "label": "Per year (added ÷ period)", **NUM}], id_key="rp", title="Average yearly exposure", sortable=False)
def top_yearly(limit=10):
ranked = pd.DataFrame({"code": stats["code"], "name": stats["name"].astype(str), "people": annual[""], "pct": stats["exposed_annual_avg_pct"]}).sort_values("people", ascending=False).head(limit)
rows = [{"code": r.code, "name": r.name, "people": r.people, "pct": r.pct} for r in ranked.itertuples()]
return Table(rows, [{"key": "name", "label": "Subdivision"}, {"key": "people", "label": "People per year", **NUM}, {"key": "pct", "label": "% of its population", **TWO}],
id_key="code", title="Largest yearly exposure", sortable=False)
def facilities_table():
rows = [{"layer": LAYER_LABELS[k], "total": fac_total[k], "exposed": fac_exposed[k], "share": 100 * fac_exposed[k] / fac_total[k] if fac_total[k] else 0.0, "frequent": fac_frequent[k]}
for k in selected]
return Table(rows, [{"key": "layer", "label": "Layer"}, {"key": "total", "label": "In the area", **NUM}, {"key": "exposed", "label": f"Exposed ({chosen_rp}-yr)", **NUM},
{"key": "share", "label": "Share (%)", **ONE}, {"key": "frequent", "label": f"Exposed ({rps[0]}-yr)", **NUM}], id_key="layer", title="Facilities", sortable=False)
def exposed_lines(limit=8):
"""One line per layer: the exposed facilities that the hazard reaches most often first, named with their return period."""
lines = []
for k in selected:
f = fac_by_layer[k][fac_by_layer[k]["exposed"]].sort_values("lowest_rp")
if f.empty:
continue
named = f[f["name"].notna() | f["name_en"].notna()].head(limit)
shown = [f"{esc(fmt_name(r.name, r.name_en))} ({int(r.lowest_rp)}-yr)" for r in named.itertuples()]
more = len(f) - len(shown)
lines.append(f"**{esc(LAYER_LABELS[k])}** ({len(f):,} exposed at {chosen_rp} years), reached most often first: " + ", ".join(shown) + (f" and {more:,} more" if more > 0 else "") + "."
if shown else f"**{esc(LAYER_LABELS[k])}**: {len(f):,} exposed at {chosen_rp} years, none with a name in OpenStreetMap.")
return lines
def subdivisions_table():
rows = []
for _, r in stats.sort_values("exposed", ascending=False).iterrows():
row = {"code": r["code"], "name": str(r["name"]), "population": r["population"], "exposed": r["exposed"], "share": r["exposed_share"] * 100,
"u5": r["exposed_under5"], "u15": r["exposed_under15"], "year": r["exposed_annual_avg_pct"]}
row.update({f"{k}_exposed": r[f"{k}_exposed"] for k in selected})
rows.append(row)
columns = [{"key": "name", "label": "Subdivision"}, {"key": "population", "label": "Population", **NUM}, {"key": "exposed", "label": "Exposed", **NUM},
{"key": "share", "label": "Share (%)", **ONE}, {"key": "u5", "label": "Under 5", **NUM}, {"key": "u15", "label": "Under 15", **NUM},
{"key": "year", "label": "Per year (% of pop.)", **TWO}]
columns += [{"key": f"{k}_exposed", "label": f"{LAYER_LABELS[k].split()[0]} exposed", **NUM} for k in selected]
return Table(rows, columns, id_key="code", title=f"{len(rows)} subdivisions, most people exposed first", max_height="480px")
# Rarer events should reach at least as many people. When the hazard rasters say otherwise, show it instead of hiding it.
RP_DROPS = [(rps[i - 1], rps[i]) for i in range(1, len(rps)) if exp_rp[""][i] < exp_rp[""][i - 1] * 0.999]
RP_NOTE = "; ".join(f"the {b}-year event reaches fewer people ({n(exp_rp[''][rps.index(b)])}) than the {a}-year event ({n(exp_rp[''][rps.index(a)])})" for a, b in RP_DROPS)
CHILDREN_NOTE = ("Children are WorldPop's age classes 0–4 (under 5) and 0–14 (under 15, which includes under 5). WorldPop splits each administrative unit "
"by age, so the age shares are the same for every cell of a unit.")
BASIS = (f"People living in 1 km cells where the {hazard_label} reaches an intensity of {threshold:g} or more in a {event[: event.index(' ')]} event "
f"(WorldPop {population_year}). Exposure is not harm: it says who could be reached, not who would be hurt.")
def build_people():
return figure("People exposed", n(exp_t[""]), f"{share_t['']:.1%} of {short(pop_t[''])} people",
panel(f"{n(exp_t[''])} people exposed ({share_t['']:.1%})", BASIS, groups_table(), top_subdivisions("exposed", title="Subdivisions with the most people exposed"),
md_text(CHILDREN_NOTE)), "fig-people")
def build_child(group, widget_id):
name = GROUP_NAMES[group].lower()
return figure(f"{GROUP_NAMES[group]} exposed", n(exp_t[group]), f"{share_t[group]:.1%} of {short(pop_t[group])} children {name}",
panel(f"{n(exp_t[group])} children {name} exposed ({share_t[group]:.1%})", BASIS,
top_subdivisions(col("exposed", group), group=group, title=f"Subdivisions with the most children {name} exposed"), md_text(CHILDREN_NOTE)), widget_id)
def build_annual():
if len(rps) < 2: # one return period (earthquakes) gives no yearly average worth showing: give the population instead
return figure("Population", n(pop_t[""]), f"WorldPop {population_year}, all ages", panel(f"{n(pop_t[''])} people in {esc(area_name)}", "WorldPop R2025A.", groups_table()), "fig-annual")
body = (f"On average, about {n(annual_t[''])} people a year are exposed ({annual_t[''] / pop_t['']:.2%} of the population). Each return period adds the people newly exposed, "
"weighted by 1 / return period, so rare events count for little each year. Events more frequent than the shortest period are not modelled."
+ (f"\n\n**Check the hazard data:** {RP_NOTE}. A rarer event should reach at least as many people, so the hazard rasters are not consistent with each other here; "
"the average uses them unchanged." if RP_NOTE else ""))
return figure("Yearly average", n(annual_t[""]), "people exposed in an average year",
panel(f"About {n(annual_t[''])} people exposed in an average year", body, annual_table(), top_yearly()), "fig-annual")
def build_infrastructure():
if not selected:
return figure("Facilities exposed", "—", "no infrastructure layers selected", panel("No infrastructure layers selected", "The *Infrastructure layers* parameter was empty for this run."), "fig-infra")
body = (f"**Selected for this run** (the *Infrastructure layers* parameter): {esc(selected_labels)}. Each facility is one point, its centroid, and counts as exposed when the hazard "
f"exceeds the threshold there.\n\n" + "\n\n".join(exposed_lines()) + "\n\nSource: OpenStreetMap, via the Humanitarian OpenStreetMap Team (HOT) country extracts.")
return figure("Facilities exposed", n(n_fac_exposed), f"of {n_fac_total:,} in the area",
panel(f"{plural(n_fac_exposed, 'facility')} exposed" if n_fac_exposed == 1 else f"{n_fac_exposed:,} facilities exposed", body, facilities_table()), "fig-infra")
def build_subdivisions():
return figure("Areas affected", n(n_hit), f"of {n_sub:,} have people exposed (admin level {aggregation_level})",
panel(f"{n_hit:,} of {n_sub:,} subdivisions have people exposed", f"Admin level {aggregation_level}. The ten with the highest share of their people exposed; every subdivision is under *Dive deeper*.",
top_subdivisions("exposed_share", title="Highest share exposed")), "fig-subdivisions")
FIGS = {"people": safe(build_people, "People exposed"), "under5": safe(lambda: build_child("under5", "fig-under5"), "Children under 5"),
"under15": safe(lambda: build_child("under15", "fig-under15"), "Children under 15"), "annual": safe(build_annual, "Yearly exposure"),
"infra": safe(build_infrastructure, "Facilities"), "subdivisions": safe(build_subdivisions, "Subdivisions")}Source
def build_map():
# One Map instance serves the card and the full-screen view (Fullscreen supports that): every lonboard Map inlines a ~3.4 MB script
# into the published page, so a second Map for the overlay would cost about 10 MB. Every subdivision is in the layer once per group
# (everyone, under 5, under 15); the group menu filters the layer to one copy, which also works in the published page.
bounds = stats.total_bounds
tolerance = max(float(np.hypot(bounds[2] - bounds[0], bounds[3] - bounds[1])) / 2000, 1e-4) # shapes for display only: the numbers use the full ones
shapes = stats.geometry.simplify(tolerance, preserve_topology=True).to_numpy()
frames, shades = [], []
for view, (g, title) in enumerate(GROUP_NAMES.items()):
share = stats[f"{col('exposed', g)}_share"].to_numpy(dtype=float)
frames.append(gpd.GeoDataFrame({"name": stats["name"].astype(str).to_numpy(), "group": title, "people exposed": stats[col("exposed", g)].round(0).astype(int).to_numpy(),
"share exposed (%)": np.round(share * 100, 1), "view": view}, geometry=shapes, crs=4326))
shade = colors_for(share, "OrRd", 0, max(float(share.max()), 0.01))
shade[:, 3] = 200
shades.append(shade)
frame = gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs=4326)
zones = PolygonLayer.from_geopandas(frame[["name", "group", "people exposed", "share exposed (%)", "geometry"]], get_fill_color=np.vstack(shades), get_line_color=[90, 90, 90],
line_width_min_pixels=1, extensions=[DataFilterExtension(filter_size=1)], get_filter_value=frame["view"].to_numpy(dtype="float32"),
filter_range=[0, 0])
fac_layers = {}
for k in selected:
fx = fac_by_layer[k][fac_by_layer[k]["exposed"]]
if len(fx):
pts = gpd.GeoDataFrame({"facility": [fmt_name(a, b) for a, b in zip(fx["name"], fx["name_en"])], "type": LAYER_LABELS[k],
"reached from": [f"{int(r)}-year event" for r in fx["lowest_rp"]]}, geometry=fx.geometry.to_numpy(), crs=4326)
fac_layers[k] = ScatterplotLayer.from_geopandas(pts, get_fill_color=LAYER_COLORS[k], get_line_color=[255, 255, 255], line_width_min_pixels=1, radius_min_pixels=4)
m = Map([zones, *fac_layers.values()], show_tooltip=True)
m.height = 420
group_menu = Dropdown(options=[[title, v] for v, title in enumerate(GROUP_NAMES.values())], value=0, label="Group")
binder = FilterBinder(group_menu, [zones], low_field="value", high_field="value", label="group")
switches = [layer_switch(zones, "Share exposed, by subdivision", True), *[layer_switch(l, f"Exposed {LAYER_LABELS[k].lower()}", True) for k, l in fac_layers.items()]]
ramp = Legend(entries=[[colors_for([s], "OrRd", 0, 1)[0, :3].tolist(), t] for s, t in ((0.0, "lowest"), (0.5, "mid"), (1.0, "highest"))],
title="Share exposed: scaled to the highest subdivision of the selected group")
room = Column(md_text(f"## Exposure map\n\nThe share of each group that lives where the {event} exceeds the threshold, by subdivision. Pick a group; hover a subdivision or a facility for its numbers."),
group_menu, Grid(*switches, columns=2, gap="0 16px"), m, ramp, binder, gap="8px")
dot = lambda rgb: (f'<span style="display:inline-block;width:.75em;height:.75em;border-radius:50%;margin-right:.35em;background:rgb({rgb[0]},{rgb[1]},{rgb[2]})"></span>')
key = " ".join(f"{dot(LAYER_COLORS[k])}Exposed {esc(LAYER_LABELS[k].lower())}" for k in fac_layers)
return Column(expandable(m, room, "map"), md_text("Darker subdivisions have a larger share of people exposed." + (f" {key}" if key else "")), gap="4px")
MAP_CARD = safe(build_map, "The map")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.