Who is left behind by Lisbon's public transport?¶

Identifying poorly served neighbourhoods with GTFS, population grids and spatial optimisation¶

Subject 03 · Geospatial analytics · Data Visualization – Data storytelling projects (Prof. Ahlem Drif, UFAS)

Reference paper. H. Wang, B. P. Y. Loo (2024). The public transport disadvantaged in a highly transit-oriented city: An analytical framework, key challenges and opportunities. Journal of Transport Geography, 120.

Research question Which Lisbon residents cannot reach frequent public transport on foot, where do they live, and where would a few new stops help the most people?
Audience Lisbon City Council mobility department and the operators' network planners (Carris, Metro). They want options with evidence, not formulas.
Stakeholders Residents (especially older people, children, people without a car, night-shift workers), operators, the city, the metropolitan authority (TML).
Why it matters Wang & Loo show that even in a city where most people live close to transit, a minority is transport-disadvantaged, and city averages hide them. Lisbon is hilly, so a 500 m walk can be harder there than the map suggests.

Workflow (8 steps): 1 GTFS + population → 2 Explore → 3 Accessibility index → 4 Choropleth maps → 5 Hotspots (Getis-Ord Gi*) → 6 Network analysis → 7 Spatial optimisation → 8 Data story & ethics.

0 · Setup¶

All data are open. src/fetch_osm.py and src/build_lisbon_feed.py download and prepare the raw inputs (run once, see README). The cells below only read local files, so the notebook is reproducible offline.

In [1]:
import json, pathlib, re, textwrap, time, warnings
import numpy as np, pandas as pd, geopandas as gpd
import matplotlib.pyplot as plt, matplotlib.ticker as mtick
import rasterio, rasterio.mask
from shapely.geometry import box
import gtfs_kit as gk, osmnx as ox, networkx as nx
from scipy.spatial import cKDTree
import folium
from folium.plugins import HeatMap
import libpysal, esda, pulp
warnings.filterwarnings("ignore")

ROOT = pathlib.Path(".").resolve()
RAW, PROC = ROOT / "data/raw", ROOT / "data/processed"
FIG, MAPS, OUT = ROOT / "figures", ROOT / "maps", ROOT / "outputs"
for d in (FIG, MAPS, OUT): d.mkdir(exist_ok=True)

DATE = "20261203"            # Thursday 3 Dec 2026 (1 Dec is a public holiday in Portugal)
WALK = 500                   # walking threshold in metres (subject brief)
PEAK = (7, 9)                # morning peak, departures counted in [07:00, 09:00)
LOW = 10                     # < 10 departures/hour within reach = low frequency
CRS = 3763                   # ETRS89 / Portugal TM06, metres
KEY = {}                     # key numbers, saved for the slides

# Storytelling palette (one colour for the message, grey for the rest; colour-blind safe)
TEAL, ORANGE, GREY, INK = "#2F7F86", "#D9682B", "#B9B2A3", "#222222"
SRC_GTFS = "Source: TML regional GTFS feed (Mobility Database mdb-3412), weekday 3 Dec 2026"
SRC_POP = "WorldPop 2025 constrained 100 m grid (CC BY 4.0)"
SRC_OSM = "OpenStreetMap (ODbL)"
plt.rcParams.update({"font.family": "DejaVu Sans", "axes.spines.top": False, "axes.spines.right": False,
                     "axes.edgecolor": "#888", "axes.labelcolor": "#444", "xtick.color": "#444",
                     "ytick.color": "#444", "figure.dpi": 110})

def finish(fig, title, subtitle=None, source=SRC_GTFS, name=None):
    """Action title (the finding), optional subtitle, source line, save to figures/."""
    H = fig.get_figheight()
    y = 1 - 0.10 / H                                   # header laid out in inches, whatever the figure height
    t = textwrap.wrap(title, 82)
    fig.text(0.01, y, "\n".join(t), ha="left", va="top", fontsize=14, fontweight="bold", color=INK)
    y -= len(t) * 0.27 / H + 0.06 / H
    if subtitle:
        sub = [l for s in subtitle.split("\n") for l in textwrap.wrap(s, 112)]
        fig.text(0.01, y, "\n".join(sub), ha="left", va="top", fontsize=10.5, color="#555")
        y -= len(sub) * 0.2 / H
    fig.text(0.01, 0.005, source, ha="left", va="bottom", fontsize=8, color="#777")
    fig.tight_layout(rect=(0, 0.3 / H, 1, y - 0.12 / H))
    if name:
        fig.savefig(FIG / f"{name}.png", dpi=200, bbox_inches="tight", facecolor="white")
    plt.show()

def basemap(ax):
    try:
        import contextily as ctx
        ctx.add_basemap(ax, crs=f"EPSG:{CRS}", source=ctx.providers.CartoDB.PositronNoLabels, attribution=False)
    except Exception as e:
        print("basemap skipped:", e)

def pct(x, d=1):
    return f"{100 * x:.{d}f}%"

1 · Data: GTFS + population + neighbourhoods¶

Dataset What it gives Source / licence Year
TML regional GTFS feed stops, routes, trips and timetables of all 6 operators serving Lisbon (Carris bus & tram, Metro, CP & Fertagus rail, Transtejo ferries, Carris Metropolitana) Mobility Database mdb-3412, published by Transportes Metropolitanos de Lisboa feed of 1 Nov 2026, day analysed: 3 Dec 2026
WorldPop population grid modelled residents per ~100 m cell (constrained to built-up areas) WorldPop R2025A, CC BY 4.0 2025
Parishes (freguesias) the 24 official neighbourhood units of the municipality OpenStreetMap via OSMnx, ODbL 2026
Walking network streets and paths for network walking distances OpenStreetMap via OSMnx, ODbL 2026

Why the regional feed and not only Carris + Metro? A first version used only the two city operators. It ignored suburban trains and ferries that Lisbon residents also use, which would have made some riverside and border parishes look worse than they are. The TML feed is cut to one day and to the stops within Lisbon + 1 km by src/build_lisbon_feed.py, because residents near the border also use stops just outside it.

In [2]:
feed = gk.read_feed(PROC / f"gtfs_lisbon_{DATE}.zip", dist_units="km")
city = gpd.read_file(RAW / "lisbon_boundary.geojson").to_crs(CRS)
parishes = gpd.read_file(RAW / "lisbon_parishes.geojson")
parishes = parishes[parishes.name != "Lisboa"].to_crs(CRS).reset_index(drop=True)[["name", "geometry"]]
parishes["area_km2"] = parishes.area / 1e6

MODE = {0: "Tram", 1: "Metro", 2: "Rail", 3: "Bus", 4: "Ferry"}
routes = feed.routes.merge(feed.agency[["agency_id", "agency_name"]], on="agency_id")
routes["mode"] = routes.route_type.astype(int).map(MODE)
st = (feed.stop_times.merge(feed.trips[["trip_id", "route_id"]], on="trip_id")
      .merge(routes[["route_id", "route_short_name", "mode", "agency_name"]], on="route_id"))
tt = st.departure_time.where(st.departure_time.notna() & (st.departure_time != ""), st.arrival_time)
st["sec"] = tt.str.split(":", expand=True).astype(int).pipe(lambda d: d[0] * 3600 + d[1] * 60 + d[2])
st["hour"] = (st.sec // 3600).astype(int)

stops = gpd.GeoDataFrame(feed.stops, geometry=gpd.points_from_xy(feed.stops.stop_lon, feed.stops.stop_lat), crs=4326).to_crs(CRS)
prio = {"Metro": 0, "Rail": 1, "Tram": 2, "Ferry": 3, "Bus": 4}
stop_mode = st.groupby("stop_id")["mode"].agg(lambda m: min(m, key=prio.get))
stops["mode"] = stops.stop_id.map(stop_mode)
stops["in_city"] = stops.within(city.iloc[0].geometry)

print(f"Operators: {feed.agency.agency_name.nunique()} | routes: {len(routes)} | trips on {DATE}: {len(feed.trips):,} | stop events: {len(st):,}")
print(f"Stops in study area (Lisbon + 1 km): {len(stops):,}, of which inside the city: {stops.in_city.sum():,}")
print(routes.groupby(["mode", "agency_name"]).size().rename("routes").to_frame())
Operators: 6 | routes: 477 | trips on 20261203: 23,154 | stop events: 420,827
Stops in study area (Lisbon + 1 km): 3,154, of which inside the city: 2,441
                            routes
mode  agency_name                 
Bus   CARRIS                   154
      Carris Metropolitana     275
Ferry Transtejo Soflusa          5
Metro Metro de Lisboa            4
Rail  Comboios de Portugal      27
      Fertagus                   2
Tram  CARRIS                    10

Population grid¶

The WorldPop raster is clipped to the municipality. Every cell becomes a polygon (for maps) and a centroid (for distances).

In [3]:
with rasterio.open(RAW / "worldpop_prt_2025.tif") as src:
    nodata = src.nodata
    arr, tr = rasterio.mask.mask(src, [city.to_crs(src.crs).iloc[0].geometry], crop=True, nodata=nodata)
    raw_cells = int((arr[0] != nodata).sum())
a = arr[0]
r, c = np.where(a != nodata)
x0, y0 = rasterio.transform.xy(tr, r, c, offset="ul")
x1, y1 = rasterio.transform.xy(tr, r, c, offset="lr")
cells = gpd.GeoDataFrame({"pop": a[r, c].astype(float)},
                         geometry=[box(*b) for b in zip(x0, y1, x1, y0)], crs=4326).to_crs(CRS)
cells["centroid"] = cells.geometry.centroid
n_zero = int((cells["pop"] <= 0).sum())
cells = cells[cells["pop"] > 0].reset_index(drop=True)

# Assign every cell to a parish (centroid within; nearest parish for the few border cells)
pts = gpd.GeoDataFrame(geometry=cells.centroid, crs=CRS)
j = gpd.sjoin(pts, parishes[["name", "geometry"]], how="left", predicate="within")
j = j[~j.index.duplicated()]
miss = j.name.isna()
if miss.any():
    jn = gpd.sjoin_nearest(pts[miss], parishes[["name", "geometry"]], how="left")
    j.loc[miss, "name"] = jn[~jn.index.duplicated()].name
cells["parish"] = j.name.values

CENSUS_2021 = 545_796   # INE Census 2021, municipality of Lisbon
KEY["population"] = round(cells["pop"].sum())
print(f"Cells with residents: {len(cells):,} | modelled residents: {cells['pop'].sum():,.0f} "
      f"(census 2021: {CENSUS_2021:,}, difference {cells['pop'].sum() / CENSUS_2021 - 1:+.1%})")
Cells with residents: 12,439 | modelled residents: 549,517 (census 2021: 545,796, difference +0.7%)

Correcting the population model: no residents in hospitals or campuses¶

During the analysis, central Avenidas Novas first came out as one of the worst-served parishes. The cells responsible turned out to be Hospital Santa Maria and the university campus. The constrained WorldPop grid spreads residents over every building footprint, including hospitals, schools, industry and rail yards. We correct this with a standard dasymetric step: cells whose centre falls inside an OSM non-residential site lose their modelled residents, and these are redistributed proportionally to the residential cells of the same parish. Parish totals do not change.

In [4]:
NONRES_KINDS = ["hospital", "university", "college", "school", "prison", "industrial", "railway",
                "military", "cemetery", "aerodrome", "stadium"]
nonres = gpd.read_file(RAW / "lisbon_nonresidential.geojson").to_crs(CRS)
nonres = nonres[nonres.kind.isin(NONRES_KINDS)]
inside = gpd.sjoin(gpd.GeoDataFrame(geometry=cells.centroid, crs=CRS), nonres[["kind", "geometry"]], predicate="within")
inside = inside[~inside.index.duplicated()]
cells["nonres"] = cells.index.isin(inside.index)
moved = cells.loc[cells.nonres].assign(kind=inside.kind).groupby("kind")["pop"].sum().sort_values(ascending=False)
par_tot = cells.groupby("parish")["pop"].sum()
par_res = cells[~cells.nonres].groupby("parish")["pop"].sum()
cells.loc[cells.nonres, "pop"] = 0.0
cells["pop"] *= cells.parish.map(par_tot / par_res)
cells = cells[cells["pop"] > 0].reset_index(drop=True)
KEY["pop_moved_nonresidential"] = round(moved.sum())
display(moved.round(0).rename("modelled residents moved").to_frame())
print(f"{moved.sum():,.0f} modelled residents ({moved.sum() / par_tot.sum():.1%}) moved out of {len(inside):,} "
      f"non-residential cells; total still {cells['pop'].sum():,.0f}.")
modelled residents moved
kind
school 20389.0
industrial 8461.0
hospital 7242.0
railway 6905.0
university 6768.0
cemetery 4882.0
military 4224.0
aerodrome 3545.0
stadium 2053.0
prison 721.0
65,190 modelled residents (11.9%) moved out of 1,954 non-residential cells; total still 549,517.

Exploratory data analysis: distributions, missing values, outliers¶

In [5]:
# Missing values and quality checks
qc = pd.DataFrame({
    "check": ["stops without coordinates", "stops with no departure on the day", "duplicate stop_id",
              "trips without shape", "stop events without a time", "population cells with no data (masked)",
              "population cells with 0 residents"],
    "value": [int(feed.stops[["stop_lat", "stop_lon"]].isna().any(axis=1).sum()),
              int((~feed.stops.stop_id.isin(st.stop_id)).sum()),
              int(feed.stops.stop_id.duplicated().sum()),
              int((feed.trips.shape_id.isna() | (feed.trips.shape_id == "")).sum()),
              int(tt.isna().sum() + (tt == "").sum()),
              int(a.size - raw_cells),
              n_zero]})
display(qc)
desc = cells["pop"].describe(percentiles=[.25, .5, .75, .95, .99]).round(1)
display(desc.to_frame("residents per cell").T)
q1, q3 = cells["pop"].quantile([.25, .75]); iqr_hi = q3 + 1.5 * (q3 - q1)
print(f"Outliers (> Q3 + 1.5 IQR = {iqr_hi:.0f} residents per cell): {(cells['pop'] > iqr_hi).sum()} cells. "
      "They are dense apartment blocks, not errors, so we keep them.")
check value
0 stops without coordinates 0
1 stops with no departure on the day 0
2 duplicate stop_id 0
3 trips without shape 0
4 stop events without a time 0
5 population cells with no data (masked) 9660
6 population cells with 0 residents 45
count mean std min 25% 50% 75% 95% 99% max
residents per cell 10485.0 52.4 39.2 0.0 17.7 50.1 80.4 123.8 145.4 169.2
Outliers (> Q3 + 1.5 IQR = 174 residents per cell): 0 cells. They are dense apartment blocks, not errors, so we keep them.
In [6]:
fig, ax = plt.subplots(figsize=(10, 4.8))
ax.hist(cells["pop"], bins=np.arange(0, 150, 5), color=GREY, edgecolor="white")
med = cells["pop"].median()
ax.axvline(med, color=TEAL, lw=2)
ax.annotate(f"median: {med:.0f} residents per cell", xy=(med, ax.get_ylim()[1] * .9), xytext=(med + 12, ax.get_ylim()[1] * .9),
            color=TEAL, fontsize=10, va="center", arrowprops=dict(arrowstyle="->", color=TEAL))
low_share = (cells["pop"] < 10).mean()
ax.annotate(f"{pct(low_share, 0)} of built-up cells hold < 10 residents\n(mixed-use blocks and the edges of built-up areas)",
            xy=(5, ax.get_ylim()[1] * .55), xytext=(30, ax.get_ylim()[1] * .55), fontsize=9.5, color="#444",
            arrowprops=dict(arrowstyle="->", color="#666"))
ax.set_xlabel("Residents per ~100 m grid cell (bin width 5)"); ax.set_ylabel("Number of cells")
finish(fig, f"Residents are spread across {len(cells):,} cells: half hold fewer than {med:.0f} people",
       f"Modelled total {cells['pop'].sum():,.0f} residents vs {CENSUS_2021:,} in the 2021 census",
       source=f"Source: {SRC_POP}", name="01_population_distribution")
No description has been provided for this image

2 · Explore: the network on a map, service frequency by hour¶

In [7]:
# Interactive map of the network: one simplified line per route + all stops, layered by mode
COL = {"Bus": "#0072B2", "Tram": "#E69F00", "Metro": "#009E73", "Rail": "#CC79A7", "Ferry": "#56B4E9"}
shapes = feed.shapes.sort_values(["shape_id", "shape_pt_sequence"])
lines = (shapes.groupby("shape_id")[["shape_pt_lon", "shape_pt_lat"]]
         .apply(lambda d: list(zip(d.shape_pt_lat, d.shape_pt_lon))))
first_shape = feed.trips.groupby("route_id").shape_id.agg(lambda s: s.value_counts().index[0])
m = folium.Map(location=[38.735, -9.15], zoom_start=12, tiles="CartoDB positron")
for mode in ["Bus", "Tram", "Metro", "Rail", "Ferry"]:
    fg = folium.FeatureGroup(name=f"{mode} routes")
    for rid in routes.loc[routes["mode"] == mode, "route_id"]:
        sid = first_shape.get(rid)
        if sid in lines.index:
            pts_ = lines[sid][::3]
            name = routes.set_index("route_id").loc[rid, "route_short_name"]
            folium.PolyLine(pts_, color=COL[mode], weight=4 if mode != "Bus" else 1.5, opacity=.8, tooltip=f"{mode} {name}").add_to(fg)
    fg.add_to(m)
sfg = folium.FeatureGroup(name="Stops", show=False)
for _, s in stops.to_crs(4326).iterrows():
    folium.CircleMarker([s.geometry.y, s.geometry.x], radius=2, color=COL.get(s["mode"], "#555"), fill=True,
                        weight=0, fill_opacity=.8, tooltip=f"{s.stop_name} ({s['mode']})").add_to(sfg)
sfg.add_to(m)
folium.GeoJson(city.to_crs(4326), name="Lisbon boundary", style_function=lambda f: {"color": "#333", "weight": 2, "fill": False}).add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
m.save(MAPS / "map1_network.html")
m
Out[7]:
Make this Notebook Trusted to load map: File -> Trust Notebook
In [8]:
hourly = st[st.stop_id.isin(stops.loc[stops.in_city, "stop_id"])].assign(h=lambda d: d.hour % 24)
by_hour = hourly.groupby("h").size().reindex(range(24), fill_value=0)
by_mode = hourly.groupby("mode").size().sort_values(ascending=False)
display(by_mode.rename("stop departures inside Lisbon").to_frame().assign(share=lambda d: (d.iloc[:, 0] / d.iloc[:, 0].sum()).round(3)))

fig, ax = plt.subplots(figsize=(10, 4.8))
ax.fill_between(by_hour.index, by_hour.values, color=TEAL, alpha=.12)
ax.plot(by_hour.index, by_hour.values, color=TEAL, lw=2.5)
pk = by_hour.idxmax()
ax.annotate(f"peak {pk}:00 – {by_hour[pk]:,} departures", xy=(pk, by_hour[pk]), xytext=(pk + 2.2, by_hour[pk] * 1.02),
            fontsize=10, color=TEAL, arrowprops=dict(arrowstyle="->", color=TEAL))
ev = by_hour[22]
ax.annotate(f"22:00: {ev / by_hour[pk]:.0%} of the peak", xy=(22, ev), xytext=(17.3, ev * .55 + 50),
            fontsize=10, color=ORANGE, arrowprops=dict(arrowstyle="->", color=ORANGE))
ax.set_xticks(range(0, 24, 2)); ax.set_xlim(0, 23); ax.set_ylim(0)
ax.set_xlabel("Hour of the day"); ax.set_ylabel("Departures at stops inside Lisbon")
ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda v, p: f"{v:,.0f}"))
KEY["departures_day"] = int(by_hour.sum()); KEY["peak_hour"] = int(pk); KEY["evening_ratio_22h"] = round(float(ev / by_hour[pk]), 2)
finish(fig, f"Service peaks at {pk}:00 and falls by {1 - ev / by_hour[pk]:.0%} by 22:00: evening travellers get far fewer buses",
       f"{by_hour.sum():,} departures on a weekday; buses make {by_mode.get('Bus', 0) / by_mode.sum():.0%} of them",
       name="02_departures_by_hour")
stop departures inside Lisbon share
mode
Bus 303684 0.880
Tram 20194 0.059
Metro 17301 0.050
Rail 3434 0.010
Ferry 450 0.001
No description has been provided for this image

3 · Accessibility index: residents within a 500 m walk of a stop, weighted by frequency¶

Definition (transparent and reproducible):

  1. Walking distances are computed on the OSM street and path network (OSMnx + NetworkX Dijkstra), not as straight lines. Lisbon has hills, a river, a motorway ring and large parks, so straight lines overstate access.
  2. For each population cell, we find every stop reachable within 500 m of walking.
  3. For each route reachable from the cell, we keep the highest number of departures per hour among those stops (so the two stops of the same line at a corner are not counted twice).
  4. Accessibility index (AI) = the sum over routes of these departures per hour, i.e. "how many vehicles per hour can I catch within a 5–7 minute walk". This is the idea behind London's PTAL index, kept simple.
Class Rule Meaning
No stop no stop within 500 m walk coverage gap → new stop needed
Low AI < 10 dep/h frequency gap → wait often > 6 min
Medium 10 ≤ AI < 30
High AI ≥ 30 a departure every 2 minutes or better

Poorly served = No stop + Low.

In [9]:
t0 = time.time()
G = ox.project_graph(ox.load_graphml(RAW / "lisbon_walk.graphml"), to_crs=f"EPSG:{CRS}")
Gw = nx.Graph()
for u, v, d in G.edges(data=True):          # undirected walking graph, shortest parallel edge
    L = float(d["length"])
    if not Gw.has_edge(u, v) or Gw[u][v]["length"] > L:
        Gw.add_edge(u, v, length=L, highway=d.get("highway"))
nodes = ox.graph_to_gdfs(G, edges=False)[["geometry"]]
tree = cKDTree(np.c_[nodes.geometry.x, nodes.geometry.y])
d_, i_ = tree.query(np.c_[stops.geometry.x, stops.geometry.y]); stops["node"], stops["snapd"] = nodes.index.values[i_], d_
d_, i_ = tree.query(np.c_[cells.centroid.x, cells.centroid.y]); cells["node"], cells["snapd"] = nodes.index.values[i_], d_
print(f"Walk graph: {Gw.number_of_nodes():,} nodes, {Gw.number_of_edges():,} edges. "
      f"Median snap distance: stops {stops.snapd.median():.0f} m, cells {cells.snapd.median():.0f} m")

def reach(sources, cutoff, targets):
    """Network distance from each source node to every target node within cutoff (Dijkstra)."""
    out = []
    for n in sources:
        for m_, dd in nx.single_source_dijkstra_path_length(Gw, n, cutoff=cutoff, weight="length").items():
            if m_ in targets:
                out.append((n, m_, dd))
    return pd.DataFrame(out, columns=["cnode", "tnode", "d"])

pr = reach(cells.node.unique(), 600, set(stops.node))        # 600 m so we can test sensitivity
pairs = (cells.reset_index(names="cell")[["cell", "node", "snapd"]]
         .merge(pr, left_on="node", right_on="cnode")
         .merge(stops[["stop_id", "node", "snapd"]].rename(columns={"node": "tnode", "snapd": "ssnap"}), on="tnode"))
pairs["walk"] = pairs.d + pairs.snapd + pairs.ssnap
pairs = pairs.loc[pairs.walk <= 600, ["cell", "stop_id", "walk"]]
print(f"cell–stop pairs within 600 m: {len(pairs):,} ({time.time() - t0:.0f} s)")
Walk graph: 50,824 nodes, 72,830 edges. Median snap distance: stops 18 m, cells 28 m
cell–stop pairs within 600 m: 139,969 (10 s)
In [10]:
# Departures per hour for every (stop, route, hour)
dph_h = st.assign(h=st.hour % 24).groupby(["stop_id", "route_id", "h"]).size().rename("dep").reset_index()
peak_dph = (st[(st.hour >= PEAK[0]) & (st.hour < PEAK[1])].groupby(["stop_id", "route_id"]).size()
            / (PEAK[1] - PEAK[0])).rename("dph").reset_index()

def access_index(freq, radius=WALK):
    """AI per cell = sum over routes of the best departures/hour at any stop within `radius`."""
    x = pairs[pairs.walk <= radius].merge(freq, on="stop_id")
    return x.groupby(["cell", "route_id"])[freq.columns[-1]].max().groupby("cell").sum().reindex(cells.index, fill_value=0)

def classify(ai, has_stop):
    return np.select([~has_stop, ai < LOW, ai < 30], ["No stop", "Low", "Medium"], "High")

cells["has_stop"] = cells.index.isin(pairs.loc[pairs.walk <= WALK, "cell"])
cells["ai"] = access_index(peak_dph)
cells["cls"] = classify(cells.ai, cells.has_stop)
cells["poor"] = cells.cls.isin(["No stop", "Low"])
cells["nearest_stop_m"] = pairs.groupby("cell").walk.min().reindex(cells.index)

POP = cells["pop"].sum()
cls_pop = cells.groupby("cls")["pop"].sum().reindex(["No stop", "Low", "Medium", "High"])
KEY.update(pop_no_stop=round(cls_pop["No stop"]), pop_low=round(cls_pop["Low"]),
           share_no_stop=round(cls_pop["No stop"] / POP, 4), share_poor=round((cls_pop["No stop"] + cls_pop["Low"]) / POP, 4))
pw_median = cells.sort_values("ai").assign(c=lambda d: d["pop"].cumsum() / POP).query("c >= .5").ai.iloc[0]
KEY["median_resident_ai"] = float(pw_median)
display((cls_pop.to_frame("residents").assign(share=lambda d: (d.residents / POP).map(pct))).round(0))
print(f"The median resident can catch {pw_median:.0f} departures/hour within a 500 m walk at the morning peak.")
residents share
cls
No stop 13483.0 2.5%
Low 47311.0 8.6%
Medium 193025.0 35.1%
High 295699.0 53.8%
The median resident can catch 31 departures/hour within a 500 m walk at the morning peak.
In [11]:
# Validation 1 – straight line vs network distance; Validation 2 – sensitivity to the 500 m threshold
st_tree = cKDTree(np.c_[stops.geometry.x, stops.geometry.y])
eu_d, _ = st_tree.query(np.c_[cells.centroid.x, cells.centroid.y])
cov_eu = cells.loc[eu_d <= WALK, "pop"].sum() / POP
cov_net = cells.loc[cells.has_stop, "pop"].sum() / POP
sens = []
for rad in (400, 500, 600):
    hs = cells.index.isin(pairs.loc[pairs.walk <= rad, "cell"])
    ai_r = access_index(peak_dph, rad)
    sens.append({"walking threshold (m)": rad, "no stop": pct(cells.loc[~hs, "pop"].sum() / POP),
                 "poorly served": pct(cells.loc[pd.Series(classify(ai_r, hs), index=cells.index).isin(["No stop", "Low"]), "pop"].sum() / POP)})
display(pd.DataFrame(sens))
KEY.update(cov_euclid=round(cov_eu, 4), cov_network=round(cov_net, 4))

fig, ax = plt.subplots(figsize=(10, 3.6))
vals = [1 - cov_eu, 1 - cov_net]
b = ax.barh(["Straight-line 500 m", "Walking network 500 m"], vals, color=[GREY, TEAL], height=.55)
for rect, v in zip(b, vals):
    ax.text(v + .001, rect.get_y() + rect.get_height() / 2, f"{pct(v, 2)}  ({v * POP:,.0f} residents)", va="center", fontsize=10.5)
ax.set_xlim(0, max(vals) * 1.6); ax.xaxis.set_major_formatter(mtick.PercentFormatter(1, 1))
ax.set_xlabel("Share of residents with no stop within 500 m")
finish(fig, f"A ruler says only {(1 - cov_eu) * POP:,.0f} residents live beyond 500 m of a stop; along real streets it is {(1 - cov_net) * POP:,.0f}",
       "Why we use OSMnx walking distances rather than circles", source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}",
       name="03_network_vs_straight_line")
walking threshold (m) no stop poorly served
0 400 5.6% 21.7%
1 500 2.5% 11.1%
2 600 1.2% 5.6%
No description has been provided for this image
In [12]:
fig, ax = plt.subplots(figsize=(10, 3.4))
order = ["No stop", "Low", "Medium", "High"]
colors = {"No stop": ORANGE, "Low": "#F0B48C", "Medium": "#D9D4CA", "High": GREY}
left = 0
for k in order:
    v = cls_pop[k] / POP
    ax.barh([0], [v], left=left, color=colors[k], edgecolor="white", height=.6)
    ax.text(left + v / 2, 0.42 if v < .06 else 0, f"{k}\n{pct(v, 1)}", ha="center", va="bottom" if v < .06 else "center",
            fontsize=10, color=INK)
    left += v
poor = KEY["share_poor"]
ax.annotate(f"Poorly served: {pct(poor)} ≈ 1 in {round(1 / poor)} residents\n({cls_pop['No stop'] + cls_pop['Low']:,.0f} people)",
            xy=(poor / 2, -0.3), xytext=(poor + .05, -0.75), fontsize=11, color=ORANGE, fontweight="bold",
            arrowprops=dict(arrowstyle="->", color=ORANGE))
ax.set_xlim(0, 1); ax.set_ylim(-1, .9); ax.axis("off")
finish(fig, f"About 1 in {round(1 / poor)} Lisbon residents is poorly served by public transport at the morning peak",
       f"Residents by accessibility class, weekday 07:00–09:00, 500 m walk on the street network",
       source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}", name="04_population_by_class")
No description has been provided for this image

Does it change during the day? (night-shift and evening workers)¶

In [13]:
hours = list(range(5, 24))
poor_by_hour = []
for h in hours:
    f_h = dph_h[dph_h.h == h][["stop_id", "route_id", "dep"]]
    ai_h = access_index(f_h)
    poor_by_hour.append(cells.loc[(~cells.has_stop) | (ai_h < LOW), "pop"].sum() / POP)
pbh = pd.Series(poor_by_hour, index=hours)
KEY["share_poor_by_hour"] = {int(k): round(float(v), 4) for k, v in pbh.items()}

fig, ax = plt.subplots(figsize=(10, 4.6))
ax.plot(pbh.index, pbh.values, color=ORANGE, lw=2.5, marker="o", ms=4)
best = pbh.idxmin()
ax.annotate(f"best hour {best}:00 – {pct(pbh[best], 0)}", xy=(best, pbh[best]), xytext=(best + 1.5, pbh[best] - .02),
            fontsize=10, color="#444", arrowprops=dict(arrowstyle="->", color="#666"), va="top")
ax.annotate(f"23:00 – {pct(pbh[23], 0)}: about 1 in {round(1 / pbh[23])}", xy=(23, pbh[23]), xytext=(16.2, pbh[23] + .03),
            fontsize=10.5, color=ORANGE, fontweight="bold", arrowprops=dict(arrowstyle="->", color=ORANGE))
ax.set_ylim(0, max(pbh) * 1.25); ax.yaxis.set_major_formatter(mtick.PercentFormatter(1, 0))
ax.set_xticks(hours[::2]); ax.set_xlabel("Hour of the day"); ax.set_ylabel("Residents poorly served")
finish(fig, f"After 21:00 the share of poorly served residents climbs from {pct(pbh[best], 0)} to {pct(pbh[23], 0)}",
       "Share of residents with no stop within 500 m or < 10 departures/hour, by hour (weekday)",
       source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}", name="05_poorly_served_by_hour")
No description has been provided for this image

4 · Choropleth maps: accessibility per neighbourhood (parish)¶

In [14]:
ps = cells.groupby("parish").apply(lambda d: pd.Series({
    "residents": d["pop"].sum(),
    "no_stop": d.loc[d.cls == "No stop", "pop"].sum(),
    "poor": d.loc[d.poor, "pop"].sum(),
    "mean_ai": np.average(d.ai, weights=d["pop"]),
    "mean_walk_m": np.average(d.nearest_stop_m.fillna(600), weights=d["pop"]),
}))
ps["share_poor"] = ps.poor / ps.residents
ps["share_no_stop"] = ps.no_stop / ps.residents
ps["stops"] = gpd.sjoin(stops[stops.in_city], parishes, predicate="within").groupby("name").size().reindex(ps.index, fill_value=0)
ps["stops_per_1000"] = ps.stops / ps.residents * 1000
par = parishes.merge(ps, left_on="name", right_index=True)
par["density"] = par.residents / par.area_km2
display(ps.sort_values("share_poor", ascending=False).round({"residents": 0, "no_stop": 0, "poor": 0, "mean_ai": 1, "mean_walk_m": 0,
                                                            "share_poor": 3, "share_no_stop": 3, "stops_per_1000": 2}))
residents no_stop poor mean_ai mean_walk_m share_poor share_no_stop stops stops_per_1000
parish
Parque das Nações 22568.0 886.0 7176.0 42.8 233.0 0.318 0.039 98 4.34
Lumiar 46847.0 1621.0 10059.0 41.3 206.0 0.215 0.035 174 3.71
Avenidas Novas 23426.0 39.0 4732.0 56.3 186.0 0.202 0.002 101 4.31
São Domingos de Benfica 34179.0 677.0 6156.0 32.4 212.0 0.180 0.020 101 2.96
Olivais 32417.0 906.0 5495.0 25.0 193.0 0.170 0.028 149 4.60
Beato 12225.0 17.0 1795.0 26.4 163.0 0.147 0.001 56 4.58
Belém 16647.0 977.0 2296.0 29.1 224.0 0.138 0.059 131 7.87
Alcântara 13951.0 1262.0 1866.0 49.0 201.0 0.134 0.090 82 5.88
Penha de França 28775.0 486.0 3390.0 25.7 192.0 0.118 0.017 72 2.50
Marvila 35713.0 1726.0 4163.0 20.4 208.0 0.117 0.048 158 4.42
Carnide 18094.0 881.0 2047.0 29.5 204.0 0.113 0.049 89 4.92
Alvalade 33494.0 1577.0 3525.0 37.8 220.0 0.105 0.047 153 4.57
Santa Clara 23824.0 834.0 2452.0 31.0 199.0 0.103 0.035 113 4.74
Campolide 14879.0 89.0 1128.0 54.9 169.0 0.076 0.006 94 6.32
São Vicente 13984.0 388.0 668.0 32.1 161.0 0.048 0.028 72 5.15
Benfica 35633.0 673.0 1150.0 49.3 189.0 0.032 0.019 150 4.21
Estrela 20338.0 80.0 591.0 39.3 168.0 0.029 0.004 124 6.10
Santa Maria Maior 10114.0 0.0 257.0 76.6 138.0 0.025 0.000 90 8.90
Santo António 11244.0 0.0 257.0 76.3 200.0 0.023 0.000 57 5.07
Campo de Ourique 22265.0 128.0 411.0 41.7 167.0 0.018 0.006 72 3.23
Areeiro 21380.0 231.0 388.0 54.2 204.0 0.018 0.011 57 2.67
Arroios 33406.0 0.0 597.0 61.4 158.0 0.018 0.000 101 3.02
Ajuda 14419.0 6.0 152.0 29.7 164.0 0.011 0.000 83 5.76
Misericórdia 9697.0 0.0 43.0 52.1 152.0 0.004 0.000 64 6.60
In [15]:
# Static choropleth (for the slides)
fig, ax = plt.subplots(figsize=(10, 8.2))
par.plot(column="share_poor", cmap="Oranges", vmin=0, vmax=par.share_poor.max(), edgecolor="white", lw=.8, ax=ax,
         legend=True, legend_kwds={"label": "Share of residents poorly served", "shrink": .55, "format": mtick.PercentFormatter(1, 0)})
for _, p in par.iterrows():
    if p.share_poor >= par.share_poor.quantile(.75):
        pt = p.geometry.representative_point()
        ax.text(pt.x, pt.y, f"{p['name']}\n{pct(p.share_poor, 0)}", ha="center", va="center", fontsize=8.5, fontweight="bold", color=INK)
stops[stops.in_city & stops["mode"].isin(["Metro", "Rail"])].plot(ax=ax, color=TEAL, markersize=14, marker="s", label="Metro / rail station")
ax.legend(loc="lower left", frameon=False); ax.set_axis_off()
top = par.sort_values("share_poor", ascending=False).iloc[0]
finish(fig, f"Poor access concentrates in the northern half of the city: up to {pct(top.share_poor, 0)} of residents in {top['name']}",
       "Morning peak, 500 m walking network; labels: the most affected quarter of parishes",
       source=f"{SRC_GTFS}; {SRC_POP}; parishes {SRC_OSM}", name="06_choropleth_parishes")
No description has been provided for this image
In [16]:
# Interactive choropleth with stop layers
par4326 = par.to_crs(4326)
m = folium.Map(location=[38.735, -9.15], zoom_start=12, tiles="CartoDB positron")
ch = folium.Choropleth(par4326, data=par4326, columns=["name", "share_poor"], key_on="feature.properties.name",
                       fill_color="Oranges", fill_opacity=.75, line_color="white", line_weight=1,
                       legend_name="Share of residents poorly served (morning peak)", name="Poorly served (%)").add_to(m)
folium.GeoJson(par4326.assign(sp=(par4326.share_poor * 100).round(1), ns=(par4326.share_no_stop * 100).round(1),
                              ai=par4326.mean_ai.round(1), res=par4326.residents.round(0))[["name", "sp", "ns", "ai", "res", "geometry"]],
               style_function=lambda f: {"fillOpacity": 0, "weight": 0},
               tooltip=folium.GeoJsonTooltip(["name", "res", "sp", "ns", "ai"],
                                             aliases=["Parish", "Residents", "% poorly served", "% no stop ≤500 m", "Mean departures/h"]),
               name="Parish details").add_to(m)
for mode in ["Metro", "Rail", "Tram", "Ferry", "Bus"]:
    fg = folium.FeatureGroup(name=f"{mode} stops", show=mode != "Bus")
    for _, s in stops[stops["mode"] == mode].to_crs(4326).iterrows():
        folium.CircleMarker([s.geometry.y, s.geometry.x], radius=3 if mode != "Bus" else 1.5, color=COL[mode], fill=True,
                            weight=0, fill_opacity=.9, tooltip=s.stop_name).add_to(fg)
    fg.add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
m.save(MAPS / "map2_choropleth_parishes.html")
m
Out[16]:
Make this Notebook Trusted to load map: File -> Trust Notebook

5 · Heatmaps & hotspots: where do poorly served residents cluster? (Getis-Ord Gi*)¶

We test whether high numbers of poorly served residents cluster in space more than chance would produce. Gi* compares each cell plus its neighbours within 250 m with the city-wide distribution (999 permutations). A hotspot is a cell with a significantly high local sum (p < 0.05).

In [17]:
cells["y_poor"] = np.where(cells.poor, cells["pop"], 0.0)
cpts = gpd.GeoDataFrame(cells[["y_poor"]], geometry=cells.centroid, crs=CRS)
w = libpysal.weights.DistanceBand.from_dataframe(cpts, threshold=250, binary=True, silence_warnings=True)
gi = esda.G_Local(cells.y_poor.values, w, transform="B", star=True, permutations=999, seed=42)
cells["gi_z"], cells["gi_p"] = gi.Zs, gi.p_sim
cells["hot"] = (cells.gi_z > 0) & (cells.gi_p < .05)
hot = cells[cells.hot]
clusters = (gpd.GeoDataFrame(geometry=hot.buffer(10), crs=CRS).dissolve().explode(index_parts=False).reset_index(drop=True))
clusters["residents_poor"] = [cells.loc[cells.hot & cells.centroid.within(g), "y_poor"].sum() for g in clusters.geometry]
clusters["parish"] = [cells.loc[cells.hot & cells.centroid.within(g), "parish"].mode().iloc[0] for g in clusters.geometry]
clusters = clusters[clusters.residents_poor > 0].sort_values("residents_poor", ascending=False).reset_index(drop=True)
hot_share = hot.y_poor.sum() / cells.y_poor.sum()
hot_area = hot.geometry.area.sum() / city.area.sum()
KEY.update(hotspot_cells=int(len(hot)), hotspot_share_of_poor=round(hot_share, 3), hotspot_area_share=round(hot_area, 3),
           hotspot_clusters=int(len(clusters)), top_clusters=clusters.head(8)[["parish", "residents_poor"]].round(0).to_dict("records"))
print(f"{len(hot)} hotspot cells in {len(clusters)} clusters cover {pct(hot_area)} of the city's area "
      f"but hold {pct(hot_share)} of all poorly served residents.")
display(clusters.head(10)[["parish", "residents_poor"]].round(0))
1585 hotspot cells in 36 clusters cover 12.2% of the city's area but hold 70.1% of all poorly served residents.
parish residents_poor
0 Parque das Nações 4738.0
1 Beato 4588.0
2 Lumiar 4230.0
3 Avenidas Novas 4068.0
4 São Domingos de Benfica 2931.0
5 Lumiar 2487.0
6 Parque das Nações 2166.0
7 Alvalade 2063.0
8 Olivais 1968.0
9 Penha de França 1504.0
In [18]:
fig, ax = plt.subplots(figsize=(10, 8.2))
parishes.boundary.plot(ax=ax, color="#999", lw=.6)
cells[~cells.hot].plot(ax=ax, color="#ECE9E2", lw=0)
cells[cells.hot].plot(ax=ax, color=ORANGE, lw=0)
for i, cl in clusters.head(5).iterrows():
    pt = cl.geometry.representative_point()
    ax.annotate(f"{cl.parish}: {cl.residents_poor:,.0f}", xy=(pt.x, pt.y), xytext=(pt.x + 900, pt.y + 700 - 350 * i),
                fontsize=9, fontweight="bold", color=INK, arrowprops=dict(arrowstyle="-", color="#555", lw=.8),
                bbox=dict(facecolor="white", edgecolor="none", alpha=.85, pad=1.5))
ax.set_axis_off()
finish(fig, f"{len(clusters)} hotspots covering {pct(hot_area, 0)} of the city hold {pct(hot_share, 0)} of its poorly served residents",
       "Getis-Ord Gi* hotspots (p < 0.05, 250 m neighbourhood, 999 permutations); labels: largest clusters, residents poorly served",
       source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}", name="07_hotspots_gi")
No description has been provided for this image
In [19]:
m = folium.Map(location=[38.735, -9.15], zoom_start=12, tiles="CartoDB positron")
hm = cells[cells.y_poor > 0]
HeatMap([[p.y, p.x, v] for p, v in zip(gpd.GeoSeries(hm.centroid, crs=CRS).to_crs(4326), hm.y_poor / hm.y_poor.max())],
        name="Heatmap: poorly served residents", radius=14, blur=18).add_to(m)
folium.GeoJson(cells[cells.hot][["pop", "ai", "parish", "geometry"]].round(1).to_crs(4326), name="Gi* hotspot cells",
               style_function=lambda f: {"color": ORANGE, "weight": 0, "fillColor": ORANGE, "fillOpacity": .55},
               tooltip=folium.GeoJsonTooltip(["parish", "pop", "ai"], aliases=["Parish", "Residents", "Departures/h"])).add_to(m)
folium.GeoJson(parishes.to_crs(4326), name="Parishes", style_function=lambda f: {"color": "#666", "weight": 1, "fill": False},
               tooltip=folium.GeoJsonTooltip(["name"])).add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
m.save(MAPS / "map3_hotspots.html")
m
Out[19]:
Make this Notebook Trusted to load map: File -> Trust Notebook

6 · Network analysis: stop-to-stop graph, centrality and transfer points¶

Stops less than 100 m apart are merged into stop areas (the two sides of a street, or a metro station and its bus stops). Every pair of consecutive stops on a trip becomes a directed edge, weighted by the scheduled travel time. Betweenness centrality shows which stop areas lie on the most shortest paths: these are the interchanges the network depends on. The number of distinct lines at a stop area shows its transfer potential.

In [20]:
from sklearn.cluster import DBSCAN
lab = DBSCAN(eps=100, min_samples=1).fit_predict(np.c_[stops.geometry.x, stops.geometry.y])
stops["sarea"] = lab
area_name = stops.groupby("sarea").stop_name.agg(lambda s: s.value_counts().index[0])
area_pt = stops.groupby("sarea").geometry.apply(lambda g: g.union_all().centroid)
s2 = st[["trip_id", "stop_id", "stop_sequence", "sec", "route_id", "route_short_name", "mode"]].copy()
s2["stop_sequence"] = s2.stop_sequence.astype(int)
s2 = s2.sort_values(["trip_id", "stop_sequence"])
s2["sarea"] = s2.stop_id.map(stops.set_index("stop_id")["sarea"])
nxt = s2.groupby("trip_id")[["sarea", "sec"]].shift(-1)
e = s2.assign(a2=nxt.sarea, t2=nxt.sec).dropna(subset=["a2"])
e = e[e.sarea != e.a2].assign(a2=lambda d: d.a2.astype(int), mins=lambda d: ((d.t2 - d.sec) / 60).clip(lower=.5))
E = e.groupby(["sarea", "a2"]).agg(trips=("trip_id", "size"), mins=("mins", "median")).reset_index()
SG = nx.DiGraph()
SG.add_weighted_edges_from(E[["sarea", "a2", "mins"]].itertuples(index=False), weight="mins")
nx.set_edge_attributes(SG, {(r.sarea, r.a2): r.trips for r in E.itertuples()}, "trips")
bc = nx.betweenness_centrality(SG, k=min(800, SG.number_of_nodes()), weight="mins", seed=42, normalized=True)
lines_at = s2.groupby("sarea").route_short_name.nunique()
modes_at = s2.groupby("sarea")["mode"].agg(lambda m: ", ".join(sorted(set(m))))
deps_at = s2.groupby("sarea").size()
hubs = pd.DataFrame({"name": area_name, "betweenness": pd.Series(bc), "lines": lines_at, "modes": modes_at,
                     "departures": deps_at, "in_degree": pd.Series(dict(SG.in_degree())), "out_degree": pd.Series(dict(SG.out_degree()))}).dropna(subset=["betweenness"])
hubs = gpd.GeoDataFrame(hubs, geometry=area_pt.reindex(hubs.index), crs=CRS)
hubs = hubs[hubs.within(city.iloc[0].geometry)]
print(f"Stop graph: {SG.number_of_nodes():,} stop areas, {SG.number_of_edges():,} links; "
      f"weakly connected components: {nx.number_weakly_connected_components(SG)}")
display(hubs.sort_values("betweenness", ascending=False).head(12).drop(columns="geometry").round(3))
Stop graph: 1,170 stop areas, 2,945 links; weakly connected components: 1
name betweenness lines modes departures in_degree out_degree
5 Sete Rios 0.282 32 Bus, Metro, Rail 4087 11.0 16.0
330 Alameda D. A. Henriques 0.232 15 Bus, Metro 2065 10.0 12.0
157 Estação Entrecampos 0.201 17 Bus, Rail 1445 7.0 9.0
343 Campo Grande 0.193 59 Bus, Metro 2840 8.0 9.0
978 Estação Benfica 0.163 12 Bus, Rail 1442 8.0 11.0
300 Saldanha 0.157 7 Bus, Metro 958 6.0 5.0
312 Entrecampos 0.133 11 Bus, Metro 1159 6.0 5.0
210 Estação Oriente (Interface) 0.126 43 Bus, Metro, Rail 3713 12.0 12.0
479 Olaias 0.124 5 Bus, Metro 696 5.0 6.0
16 Areeiro 0.121 15 Bus, Metro 1834 9.0 9.0
18 B. Armador 0.120 7 Bus, Metro 1023 7.0 8.0
92 Hosp. Sta. Maria 0.120 11 Bus, Metro 1826 8.0 8.0
In [21]:
top_hubs = hubs.sort_values("betweenness", ascending=False).head(20)
d_hot = top_hubs.geometry.union_all()
cells["dist_hub_km"] = cells.centroid.distance(d_hot) / 1000
dh_poor = np.average(cells.loc[cells.hot, "dist_hub_km"], weights=cells.loc[cells.hot, "pop"])
dh_rest = np.average(cells.loc[~cells.hot, "dist_hub_km"], weights=cells.loc[~cells.hot, "pop"])
KEY.update(dist_hub_hotspot_km=round(dh_poor, 2), dist_hub_other_km=round(dh_rest, 2),
           top_hubs=top_hubs.head(10)[["name", "lines", "betweenness"]].round(3).to_dict("records"))

t10 = top_hubs.head(10).iloc[::-1]
fig, ax = plt.subplots(figsize=(10, 5.6))
ax.barh(t10.name, t10.betweenness, color=[TEAL if i >= 7 else GREY for i in range(10)], height=.65)
for i, (_, r_) in enumerate(t10.iterrows()):
    ax.text(r_.betweenness + t10.betweenness.max() * .01, i, f"{r_.betweenness:.3f} · {int(r_.lines)} lines ({r_.modes})", va="center", fontsize=9)
ax.set_xlim(0, t10.betweenness.max() * 1.55); ax.set_xlabel("Betweenness centrality (share of shortest paths through the stop area)")
h0 = top_hubs.iloc[0]
finish(fig, f"{h0['name']} lies on {h0.betweenness:.0%} of all shortest paths: a few interchanges hold the network together",
       f"Top 10 stop areas by betweenness (travel-time weighted), top 3 highlighted.\nHotspot residents live {dh_poor:.1f} km from a top-20 hub, "
       f"others {dh_rest:.1f} km: the gap is the last few hundred metres, not distance to the network",
       name="08_network_hubs")
print(f"Population-weighted distance to the nearest of the 20 most central stop areas: hotspots {dh_poor:.2f} km, rest {dh_rest:.2f} km. "
      "Poorly served pockets are not remote from the network: railways, motorways and hills cut them off from stops that are close by straight line.")
No description has been provided for this image
Population-weighted distance to the nearest of the 20 most central stop areas: hotspots 1.14 km, rest 1.01 km. Poorly served pockets are not remote from the network: railways, motorways and hills cut them off from stops that are close by straight line.
In [22]:
m = folium.Map(location=[38.735, -9.15], zoom_start=12, tiles="CartoDB positron")
folium.GeoJson(cells[cells.hot][["geometry"]].to_crs(4326), name="Hotspots of poorly served residents",
               style_function=lambda f: {"weight": 0, "fillColor": ORANGE, "fillOpacity": .5}).add_to(m)
fg = folium.FeatureGroup(name="Stop areas (size = betweenness)")
for _, h in hubs.sort_values("betweenness", ascending=False).head(150).to_crs(4326).iterrows():
    folium.CircleMarker([h.geometry.y, h.geometry.x], radius=3 + 22 * (h.betweenness / hubs.betweenness.max()) ** .5,
                        color=TEAL, fill=True, fill_opacity=.6, weight=1,
                        tooltip=f"{h['name']}: betweenness {h.betweenness:.3f}, {int(h.lines)} lines ({h.modes})").add_to(fg)
fg.add_to(m); folium.LayerControl(collapsed=False).add_to(m)
m.save(MAPS / "map4_network_hubs.html")
m
Out[22]:
Make this Notebook Trusted to load map: File -> Trust Notebook

7 · Spatial optimisation: where would new stops cover the most unserved people?¶

Problem (Maximal Covering Location Problem, MCLP). Choose k new stop sites among candidate street corners to maximise the number of residents who today have no stop within 500 m and would have one after.

  • Demand: cells in the No stop class (coverage gap). Low-frequency cells already have a stop: their remedy is more frequency, not more stops.
  • Candidates: street nodes on roads a bus can use (primary to residential), reachable within 500 m of at least one unserved cell.
  • Coverage: network walking distance ≤ 500 m.

We compare three models, from the simplest baseline to the exact optimum:

  1. Random baseline: k random candidates (mean of 200 draws).
  2. Greedy heuristic: repeatedly add the site that covers the most still-uncovered people (what a planner would do by hand).
  3. Integer linear programme (PuLP + HiGHS): the proven optimum.

$\max \sum_i p_i y_i \quad \text{s.t.} \quad y_i \le \sum_{j \in N_i} x_j,\;\; \sum_j x_j = k,\;\; x_j, y_i \in \{0,1\}$

In [23]:
BUS_ROADS = {"primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link",
             "residential", "unclassified", "living_street", "trunk", "trunk_link"}
def busable(hw):
    hw = hw if isinstance(hw, list) else [hw]
    return any(h in BUS_ROADS for h in hw)
cand_nodes = {n for u, v, d in Gw.edges(data=True) if busable(d.get("highway")) for n in (u, v)}
cand_nodes &= set(nodes.index[nodes.geometry.within(city.iloc[0].geometry.buffer(200))])
U = cells[cells.cls == "No stop"].copy()
cov = reach(U.node.unique(), WALK, cand_nodes)
cov = U.reset_index(names="cell")[["cell", "node", "snapd"]].merge(cov, left_on="node", right_on="cnode")
cov["walk"] = cov.d + cov.snapd
cov = cov[cov.walk <= WALK][["cell", "tnode", "walk"]]
cand = sorted(cov.tnode.unique())
p = U["pop"]
N_i = cov.groupby("cell").tnode.apply(set)
C_j = cov.groupby("tnode").cell.apply(set)
print(f"Unserved residents: {p.sum():,.0f} in {len(U):,} cells | candidate sites: {len(cand):,} | "
      f"residents coverable by any candidate: {p[N_i.index].sum():,.0f}")

def covered(sites, cover=C_j):
    cs_ = set().union(*[cover.get(s, set()) for s in sites]) if len(sites) else set()
    return p[list(cs_)].sum()

def greedy(k):
    chosen, done = [], set()
    for _ in range(k):
        best = max(cand, key=lambda s: p[list(C_j[s] - done)].sum())
        chosen.append(best); done |= C_j[best]
    return chosen

def mclp(k):
    prob = pulp.LpProblem("MCLP", pulp.LpMaximize)
    x = {j: prob.add_variable(f"x_{j}", cat="Binary") for j in cand}
    y = {i: prob.add_variable(f"y_{i}", cat="Binary") for i in N_i.index}
    prob += pulp.lpSum(p[i] * y[i] for i in N_i.index)
    for i, Ni in N_i.items():
        prob += y[i] <= pulp.lpSum(x[j] for j in Ni)
    prob += pulp.lpSum(x.values()) == k
    status = prob.solve(pulp.HiGHS(msg=False, timeLimit=120))
    m_ = re.search(r"status: (\w+)", str(status))
    return [j for j in cand if (x[j].value() or 0) > .5], (m_.group(1) if m_ else str(status))

rng = np.random.default_rng(42)
rows = []
for k in [1, 2, 3, 5, 8, 10, 15, 20]:
    t0 = time.time(); opt, status = mclp(k); t_ilp = time.time() - t0
    g = covered(greedy(k))
    rnd = np.mean([covered(list(rng.choice(cand, k, replace=False))) for _ in range(200)])
    rows.append({"k": k, "random": rnd, "greedy": g, "ILP (optimal)": covered(opt), "ILP status": status, "ILP time (s)": round(t_ilp, 2)})
res = pd.DataFrame(rows).set_index("k")
res["greedy gap to optimum"] = (1 - res.greedy / res["ILP (optimal)"]).map(lambda v: pct(v, 2))
res["share of unserved covered (ILP)"] = (res["ILP (optimal)"] / p.sum()).map(pct)
display(res.round(0))
print("Reading: random placement is a weak baseline (it wastes stops where nobody lacks one). Greedy reaches the optimum for "
      f"{(res.greedy >= res['ILP (optimal)'] - .5).sum()} of {len(res)} values of k: the pockets are small and far apart, so their "
      "catchments rarely overlap. The ILP is still needed to *prove* the plan is optimal; on overlapping demand, greedy can fall short.")
Unserved residents: 13,483 in 1,075 cells | candidate sites: 2,618 | residents coverable by any candidate: 10,915
random greedy ILP (optimal) ILP status ILP time (s) greedy gap to optimum share of unserved covered (ILP)
k
1 66.0 625.0 625.0 Optimal 1.0 0.00% 4.6%
2 146.0 1233.0 1233.0 Optimal 0.0 0.00% 9.1%
3 228.0 1820.0 1820.0 Optimal 0.0 0.00% 13.5%
5 371.0 2651.0 2651.0 Optimal 0.0 0.00% 19.7%
8 565.0 3514.0 3514.0 Optimal 0.0 0.00% 26.1%
10 741.0 3976.0 3976.0 Optimal 0.0 0.00% 29.5%
15 1057.0 5000.0 5000.0 Optimal 0.0 0.00% 37.1%
20 1339.0 5878.0 5878.0 Optimal 0.0 0.00% 43.6%
Reading: random placement is a weak baseline (it wastes stops where nobody lacks one). Greedy reaches the optimum for 8 of 8 values of k: the pockets are small and far apart, so their catchments rarely overlap. The ILP is still needed to *prove* the plan is optimal; on overlapping demand, greedy can fall short.
In [24]:
K = 10
sites, _ = mclp(K)
sol = nodes.loc[sites].copy()
sol["covers"] = [p[list(C_j[s])].sum() for s in sites]
# Marginal (non-overlapping) contribution, in greedy order of the optimal set
done = set(); marg = {}
for s in sorted(sites, key=lambda s: -p[list(C_j[s])].sum()):
    marg[s] = p[list(C_j[s] - done)].sum(); done |= C_j[s]
sol["new_residents"] = sol.index.map(marg)
sol["parish"] = gpd.sjoin_nearest(sol[["geometry"]], parishes, how="left").groupby(level=0).name.first()
# Is the site on an existing line? (distance to the nearest route shape)
shp = feed.shapes.sort_values(["shape_id", "shape_pt_sequence"])
shp_g = gpd.GeoDataFrame(geometry=gpd.points_from_xy(shp.shape_pt_lon, shp.shape_pt_lat), crs=4326).to_crs(CRS)
shp["x"], shp["y"] = shp_g.geometry.x.values, shp_g.geometry.y.values
from shapely.geometry import LineString
sl = shp.groupby("shape_id")[["x", "y"]].apply(lambda d: LineString(d.values) if len(d) > 1 else None).dropna()
sl = gpd.GeoDataFrame({"shape_id": sl.index}, geometry=list(sl.values), crs=CRS)
sl = sl.merge(feed.trips[["shape_id", "route_id"]].drop_duplicates("shape_id"), on="shape_id").merge(routes[["route_id", "route_short_name", "mode"]], on="route_id")
sl = sl[sl["mode"].isin(["Bus", "Tram"])]          # a new street stop can only be served by a bus or tram line
nn = gpd.sjoin_nearest(sol[["geometry"]], sl[["route_short_name", "mode", "geometry"]], how="left", distance_col="d_line").groupby(level=0).first()
sol["nearest_line"] = nn["mode"] + " " + nn.route_short_name.astype(str)
sol["d_line_m"] = nn.d_line.round(0)
sol["action"] = np.select([sol.d_line_m <= 30, sol.d_line_m <= 300],
                          ["add a stop on an existing line", "short diversion of a nearby line (< 300 m)"], "new or extended route")
sol = sol.sort_values("new_residents", ascending=False)
KEY.update(k=K, covered_k=round(sol.new_residents.sum()), unserved_total=round(p.sum()),
           covered_share=round(sol.new_residents.sum() / p.sum(), 3),
           on_existing_line=int((sol.action == "add a stop on an existing line").sum()),
           short_diversion=int(sol.action.str.startswith("short").sum()),
           proposals=sol[["parish", "new_residents", "nearest_line", "d_line_m", "action"]].round(0).to_dict("records"),
           greedy_k=round(res.loc[K, "greedy"]), random_k=round(res.loc[K, "random"]))

# Validation: robustness of the k = 10 plan if people only walk 400 m (steep streets, older residents)
cov400 = cov[cov.walk <= 400].groupby("tnode").cell.apply(set)
v400 = covered(sites, cov400)
KEY["covered_k_at_400m"] = round(v400)
print(f"Plan with k={K}: {sol.new_residents.sum():,.0f} of {p.sum():,.0f} unserved residents gain a stop "
      f"({pct(sol.new_residents.sum() / p.sum())}). If people walk only 400 m, the same plan still serves {v400:,.0f}.")
display(sol[["parish", "new_residents", "nearest_line", "d_line_m", "action"]].round(0))
Plan with k=10: 3,976 of 13,483 unserved residents gain a stop (29.5%). If people walk only 400 m, the same plan still serves 2,968.
parish new_residents nearest_line d_line_m action
osmid
5673552858 Santa Clara 625.0 Bus 2714 297.0 short diversion of a nearby line (< 300 m)
6863638786 Alcântara 609.0 Tram 18E 269.0 short diversion of a nearby line (< 300 m)
4659350688 Marvila 587.0 Bus 794 252.0 short diversion of a nearby line (< 300 m)
14157415807 Alvalade 430.0 Bus 701 217.0 short diversion of a nearby line (< 300 m)
1852999616 Parque das Nações 401.0 Bus 708 255.0 short diversion of a nearby line (< 300 m)
416014369 Olivais 316.0 Bus 29B 191.0 short diversion of a nearby line (< 300 m)
2453530383 São Vicente 296.0 Bus 206 130.0 short diversion of a nearby line (< 300 m)
6382163442 Marvila 251.0 Bus 794 12.0 add a stop on an existing line
10801845646 São Domingos de Benfica 238.0 Bus 58B 55.0 short diversion of a nearby line (< 300 m)
7167940713 São Domingos de Benfica 225.0 Bus 749 243.0 short diversion of a nearby line (< 300 m)
In [25]:
fig, ax = plt.subplots(figsize=(10, 5))
ks = res.index
ax.plot(ks, res["ILP (optimal)"], color=TEAL, lw=2.8, marker="o", label="Optimisation (ILP, PuLP)")
ax.plot(ks, res.greedy, color=GREY, lw=2, marker="s", ls="--", label="Greedy heuristic (reaches the optimum here)")
ax.set_xticks(list(ks))
ax.plot(ks, res.random, color=GREY, lw=1.5, marker="^", ls=":", label="Random sites (mean of 200)")
ax.axhline(p.sum(), color=ORANGE, lw=1, ls="--")
ax.text(1, p.sum() * 1.02, f"all {p.sum():,.0f} residents without a stop", color=ORANGE, fontsize=9.5)
ax.annotate(f"{K} stops → {res.loc[K, 'ILP (optimal)']:,.0f} residents\n({pct(res.loc[K, 'ILP (optimal)'] / p.sum(), 0)} of the gap), "
            f"{res.loc[K, 'ILP (optimal)'] / max(res.loc[K, 'random'], 1):.0f}× random placement",
            xy=(K, res.loc[K, "ILP (optimal)"]), xytext=(K + 1.5, res.loc[K, "ILP (optimal)"] * .55), fontsize=10, color=TEAL,
            fontweight="bold", arrowprops=dict(arrowstyle="->", color=TEAL))
ax.set_ylim(0, p.sum() * 1.12); ax.set_xlabel("Number of new stops (k)"); ax.set_ylabel("Unserved residents brought within 500 m")
ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda v, _: f"{v:,.0f}")); ax.legend(frameon=False, loc="center right")
finish(fig, f"{K} well-placed stops would give {pct(res.loc[K, 'ILP (optimal)'] / p.sum(), 0)} of residents who lack one a stop within a 500 m walk",
       "Residents covered by k new stops: exact optimisation vs greedy and random baselines",
       source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}", name="09_optimisation_models")
No description has been provided for this image
In [26]:
fig, ax = plt.subplots(figsize=(10, 8.2))
covered_cells = set().union(*[C_j[s] for s in sites])
cells.plot(ax=ax, color="#ECE9E2", lw=0)
parishes.boundary.plot(ax=ax, color="#999", lw=.6)
cells[(cells.cls == "No stop") & ~cells.index.isin(covered_cells)].plot(ax=ax, color=ORANGE, lw=0)
cells.loc[list(covered_cells)].plot(ax=ax, color=TEAL, lw=0)
sol.plot(ax=ax, color=TEAL, edgecolor="white", markersize=120, marker="*", zorder=5)
for i, (_, s) in enumerate(sol.head(5).iterrows()):
    ax.annotate(f"{s.parish}: +{s.new_residents:,.0f}", xy=(s.geometry.x, s.geometry.y), xytext=(s.geometry.x + 700, s.geometry.y - 250 - 120 * i),
                fontsize=9, fontweight="bold", color=INK, arrowprops=dict(arrowstyle="-", color="#555", lw=.8),
                bbox=dict(facecolor="white", edgecolor="none", alpha=.85, pad=1.5))
ax.set_axis_off()
n_cheap = KEY["on_existing_line"] + KEY["short_diversion"]
lead = "All" if n_cheap == K else f"{n_cheap} of the"
finish(fig, f"{lead} {K} proposed stops lie within 300 m of an existing bus or tram line: small diversions, not new routes",
       "Stars: optimal sites (k = 10) · teal: residents the new stops would reach · orange: residents still without a stop",
       source=f"{SRC_GTFS}; {SRC_POP}; {SRC_OSM}", name="10_proposed_stops")
No description has been provided for this image
In [27]:
m = folium.Map(location=[38.735, -9.15], zoom_start=12, tiles="CartoDB positron")
folium.GeoJson(cells[cells.cls == "No stop"][["pop", "parish", "geometry"]].round(0).to_crs(4326), name="Residents with no stop ≤ 500 m",
               style_function=lambda f: {"weight": 0, "fillColor": ORANGE, "fillOpacity": .6},
               tooltip=folium.GeoJsonTooltip(["parish", "pop"], aliases=["Parish", "Residents"])).add_to(m)
folium.GeoJson(cells.loc[list(covered_cells)][["geometry"]].to_crs(4326), name="Reached by the proposed stops",
               style_function=lambda f: {"weight": 0, "fillColor": TEAL, "fillOpacity": .5}).add_to(m)
for _, s in sol.to_crs(4326).iterrows():
    folium.Marker([s.geometry.y, s.geometry.x], icon=folium.Icon(color="cadetblue", icon="star"),
                  tooltip=f"{s.parish}: +{s.new_residents:,.0f} residents · {s.action} (nearest: {s.nearest_line}, {s.d_line_m:.0f} m)").add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
m.save(MAPS / "map5_proposed_stops.html")
m
Out[27]:
Make this Notebook Trusted to load map: File -> Trust Notebook

8 · Data story & ethics¶

The climax chart¶

Every chart before this one leads to it and every chart after it explains it. It answers the research question in one picture: who is left behind, and where?

In [28]:
pp = ps.sort_values("share_poor").copy()
city_rate = KEY["share_poor"]
top_n = pp.sort_values("poor", ascending=False)
cum = top_n.poor.cumsum() / top_n.poor.sum()
n_half = int((cum < .5).sum() + 1)
half_set = set(top_n.index[:n_half])
KEY.update(n_parishes_half_poor=n_half, parishes_half_poor=list(top_n.index[:n_half]),
           worst_parish=pp.index[-1], worst_parish_share=round(float(pp.share_poor.iloc[-1]), 3),
           best_parish=pp.index[0], best_parish_share=round(float(pp.share_poor.iloc[0]), 3))
fig, ax = plt.subplots(figsize=(10, 8.4))
colors = [ORANGE if n in half_set else GREY for n in pp.index]
ax.barh(pp.index, pp.share_poor, color=colors, height=.72)
for i, (n, r_) in enumerate(pp.iterrows()):
    ax.text(r_.share_poor + .004, i, f"{pct(r_.share_poor, 0)}  ({r_.poor:,.0f})", va="center", fontsize=8.8,
            color=INK if n in half_set else "#666", fontweight="bold" if n in half_set else "normal",
            bbox=dict(facecolor="white", edgecolor="none", pad=.6), zorder=3)
ax.axvline(city_rate, color=INK, lw=1.2, ls="--", zorder=2)
ax.text(city_rate + .004, -1.1, f"Lisbon: {pct(city_rate, 0)}", fontsize=9.5, color=INK)
ax.set_xlim(0, pp.share_poor.max() * 1.3); ax.set_ylim(-1.6, len(pp) - .4)
ax.xaxis.set_major_formatter(mtick.PercentFormatter(1, 0)); ax.set_xlabel("Share of residents poorly served (number of residents in brackets)")
ax.tick_params(axis="y", labelsize=9.5)
finish(fig, f"Half of Lisbon's {top_n.poor.sum():,.0f} poorly served residents live in just {n_half} of its 24 parishes",
       f"Orange: the {n_half} parishes that together hold 50% of poorly served residents · morning peak, 500 m walk, < 10 departures/hour",
       source=f"{SRC_GTFS}; {SRC_POP}; parishes {SRC_OSM}", name="00_CLIMAX_parishes")
No description has been provided for this image

The story on Freytag's pyramid¶

Stage Job Our chart(s) Message
1 · Exposition context, audience, question network map (map 1), departures by hour (fig 02) Lisbon looks well served: 6 operators and a dense network; the median resident can catch dozens of departures per hour on foot.
2 · Rising action tension builds network vs straight line (fig 03), residents by class (fig 04), by hour (fig 05) Averages hide people. Measured along real streets, about 1 in 9 residents (≈61,000 people) is poorly served at the peak, and more than half at 23:00.
3 · Climax the key insight parishes ranked (fig 00) + choropleth (fig 06) The disadvantage is concentrated: half of the poorly served live in 5 of 24 parishes, four on the northern and eastern edge (Lumiar, Parque das Nações, São Domingos de Benfica, Olivais) plus a central pocket (Bairro do Rego, Avenidas Novas).
4 · Falling action explain, nuance, limits Gi* hotspots (fig 07), network hubs (fig 08), validation tables Gi* hotspots covering 12% of the city hold 70% of the poorly served. They are not far from the interchanges: railways, motorways and hills cut them off over the last few hundred metres. The ranking holds at 400 m and 600 m.
5 · Resolution what to do optimisation (figs 09–10, map 5) Ten optimally placed stops would give about 4,000 people (30% of the coverage gap) a stop within 500 m, most of them close to an existing line. Low-frequency areas need more buses, not more stops. Planners and residents decide.

Responsible AI problem solver: is AI needed?¶

Dimension Question Our answer
Problem What real problem? Some residents cannot reach frequent public transport on foot. This limits access to jobs, health care and school.
Stakeholders Who is affected? Residents of the hotspots (older people and people without a car in particular), Carris/Metro planners, the City Council, TML.
Data Reliable, representative? Official timetables (GTFS) and a modelled population grid validated against the 2021 census (within 1%). Not observed ridership.
AI Is AI necessary? No black-box AI is needed. A transparent index plus an exact optimisation model is more explainable and more auditable than a predictive model. Machine learning would add risk without adding information.
Performance How is it evaluated? Residents covered; ILP compared with greedy and random baselines; sensitivity to 400/500/600 m; straight-line vs network distance.
Explainability Can we explain it? Every number traces back to a stop, a timetable and a walking distance. A planner can recompute it by hand.
Responsibility Who could be harmed? Residents of areas labelled "poorly served" (stigma); areas the model cannot see (informal housing, new buildings missing from the grid).
Impact Does it really help? Only if planners check the sites on the ground (slopes, road width, safety) and residents are consulted. The model proposes, people decide.
In [29]:
ethics = pd.DataFrame([
    ["Representativeness", "WorldPop is a *model* (census + buildings), validated: total within 1% of the 2021 census. It counts residents only, not workers, students or tourists. GTFS is the *timetable*, not real punctuality or crowding."],
    ["Bias", "Areas with recent housing may be under-counted. Walking 500 m is not equal for everyone: slopes, stairs and disabilities make it harder. We test 400 m to reflect this. Carris Metropolitana and rail services stopping just outside the city are included (1 km buffer)."],
    ["Privacy / anonymisation", "No personal data is used: population is aggregated to ~100 m cells (median about 40 people per cell). No individual can be identified. This is in line with GDPR and the principles of Algerian Law 18-07 (amended by 25-11) on personal data."],
    ["Licence & consent", "GTFS (TML open data), WorldPop CC BY 4.0, OpenStreetMap ODbL (© OpenStreetMap contributors). All are open licences that allow reuse with attribution. No consent is needed because there is no personal data."],
    ["Explainability", "Rule-based index + exact optimisation: every result can be traced back to a stop, a timetable and a walking distance."],
    ["No harm / dignity", "We name *places that are under-served*, never *people* or communities as a problem. No chart stigmatises a group (spirit of Algerian Law 20-05 against discrimination)."],
    ["Human oversight", "Proposed sites are suggestions for planners. Field checks (slope, road width, safety) and consultation with residents are required before any decision."],
    ["Limits stated", "One weekday; schedule ≠ reliability; walking network from OSM may miss some paths; no elevation; no destinations (jobs, hospitals); 'poorly served' threshold (10 dep/h) is a choice, tested in the sensitivity table."],
], columns=["Principle", "How this project handles it"])
pd.set_option("display.max_colwidth", 300)
display(ethics)
Principle How this project handles it
0 Representativeness WorldPop is a *model* (census + buildings), validated: total within 1% of the 2021 census. It counts residents only, not workers, students or tourists. GTFS is the *timetable*, not real punctuality or crowding.
1 Bias Areas with recent housing may be under-counted. Walking 500 m is not equal for everyone: slopes, stairs and disabilities make it harder. We test 400 m to reflect this. Carris Metropolitana and rail services stopping just outside the city are included (1 km buffer).
2 Privacy / anonymisation No personal data is used: population is aggregated to ~100 m cells (median about 40 people per cell). No individual can be identified. This is in line with GDPR and the principles of Algerian Law 18-07 (amended by 25-11) on personal data.
3 Licence & consent GTFS (TML open data), WorldPop CC BY 4.0, OpenStreetMap ODbL (© OpenStreetMap contributors). All are open licences that allow reuse with attribution. No consent is needed because there is no personal data.
4 Explainability Rule-based index + exact optimisation: every result can be traced back to a stop, a timetable and a walking distance.
5 No harm / dignity We name *places that are under-served*, never *people* or communities as a problem. No chart stigmatises a group (spirit of Algerian Law 20-05 against discrimination).
6 Human oversight Proposed sites are suggestions for planners. Field checks (slope, road width, safety) and consultation with residents are required before any decision.
7 Limits stated One weekday; schedule ≠ reliability; walking network from OSM may miss some paths; no elevation; no destinations (jobs, hospitals); 'poorly served' threshold (10 dep/h) is a choice, tested in the sensitivity table.

Responsible AI checklist (course, §3.4) and ethical checklist (§2.5)¶

  • ✓ The data source is reliable and documented (official GTFS, WorldPop, OSM; versions and dates above).
  • ✓ Privacy and personal data protection are considered (aggregated grid only).
  • ✓ The visualisations communicate findings honestly (bars start at zero, sources and dates on every chart, the comparison groups are always shown).
  • ✓ Human oversight is kept for important decisions (sites are proposals only).
  • ✓ The dataset is representative enough (population within 1% of the census; all 6 operators).
  • ✓ Potential bias is investigated (straight line vs network, 400/500/600 m sensitivity, hour of day).
  • ✓ The model's limits and uncertainty are acknowledged (see the table above).
  • ✓ The solution has a clear benefit: thousands of residents gain a stop within a 500 m walk.
  • ✓ We write "associated with", never "caused by"; examples are aggregated, no invented people.
In [30]:
KEY["generated"] = time.strftime("%Y-%m-%d %H:%M")
(OUT / "key_numbers.json").write_text(json.dumps(KEY, indent=2, ensure_ascii=False, default=float), encoding="utf-8")
ps.round(4).to_csv(OUT / "parish_accessibility.csv")
sol.drop(columns="geometry").assign(lon=sol.to_crs(4326).geometry.x, lat=sol.to_crs(4326).geometry.y).round(5).to_csv(OUT / "proposed_stops.csv")
res.to_csv(OUT / "optimisation_comparison.csv")
cells.drop(columns=["centroid"]).to_crs(4326).to_file(OUT / "cells_accessibility.gpkg", driver="GPKG")
print(json.dumps({k: v for k, v in KEY.items() if not isinstance(v, (list, dict))}, indent=1, default=float))
{
 "population": 549517,
 "pop_moved_nonresidential": 65190,
 "departures_day": 345063,
 "peak_hour": 9,
 "evening_ratio_22h": 0.32,
 "pop_no_stop": 13483,
 "pop_low": 47311,
 "share_no_stop": 0.0245,
 "share_poor": 0.1106,
 "median_resident_ai": 31.0,
 "cov_euclid": 0.9997,
 "cov_network": 0.9755,
 "hotspot_cells": 1585,
 "hotspot_share_of_poor": 0.701,
 "hotspot_area_share": 0.122,
 "hotspot_clusters": 36,
 "dist_hub_hotspot_km": 1.14,
 "dist_hub_other_km": 1.01,
 "k": 10,
 "covered_k": 3976,
 "unserved_total": 13483,
 "covered_share": 0.295,
 "on_existing_line": 1,
 "short_diversion": 9,
 "greedy_k": 3976,
 "random_k": 741,
 "covered_k_at_400m": 2968,
 "n_parishes_half_poor": 5,
 "worst_parish": "Parque das Na\u00e7\u00f5es",
 "worst_parish_share": 0.318,
 "best_parish": "Miseric\u00f3rdia",
 "best_parish_share": 0.004,
 "generated": "2026-12-01 18:39"
}

9 · Export for the results interface¶

interface/ is an interactive explorer of these results (map, hour slider, new-stop plan). This cell writes the data it reads, so the interface always shows exactly what this notebook computed.

In [31]:
from shapely.geometry import mapping
UI = ROOT / "interface"; UI.mkdir(exist_ok=True)
r5 = lambda v: round(float(v), 5)

# Cells: grid position, residents, parish, Gi*, peak index and the index for every hour 05–23
c4 = gpd.GeoSeries(cells.centroid, crs=CRS).to_crs(4326)
dx, dy = tr.a, -tr.e
col = np.floor((c4.x - tr.c) / dx).astype(int); row = np.floor((tr.f - c4.y) / dy).astype(int)
ai_hours = np.column_stack([access_index(dph_h[dph_h.h == h][["stop_id", "route_id", "dep"]]).values for h in hours])
par_names = sorted(parishes.name)
pidx = {n: i for i, n in enumerate(par_names)}
cell_rows = [[int(a_), int(b_), round(float(p_), 1), pidx[pa], int(hs), int(ht), round(float(ai), 1),
              (None if pd.isna(ns) else int(ns)), [int(v) for v in ah]]
             for a_, b_, p_, pa, hs, ht, ai, ns, ah in zip(col, row, cells["pop"], cells.parish, cells.has_stop, cells.hot,
                                                           cells.ai, cells.nearest_stop_m, ai_hours)]

# New-stop plan: greedy order up to 20 sites (it matches the ILP optimum at every k tested above)
order = greedy(20); done = set(); plan = []
for s in order:
    new = C_j[s] - done; done |= C_j[s]
    g = gpd.GeoDataFrame(geometry=[nodes.loc[s].geometry], crs=CRS)
    nl = gpd.sjoin_nearest(g, sl[["route_short_name", "mode", "geometry"]], distance_col="d").iloc[0]
    pt = g.to_crs(4326).geometry.iloc[0]
    plan.append({"lon": r5(pt.x), "lat": r5(pt.y), "gain": round(float(p[list(new)].sum())),
                 "parish": gpd.sjoin_nearest(g, parishes).iloc[0]["name"],
                 "line": f"{nl['mode']} {nl.route_short_name}", "d_line": round(float(nl.d)),
                 "cells": [int(cells.index.get_loc(i)) for i in new]})

sens_num = []
for rad in (400, 500, 600):
    hs = cells.index.isin(pairs.loc[pairs.walk <= rad, "cell"])
    ai_r = access_index(peak_dph, rad)
    poor_r = pd.Series(classify(ai_r, hs), index=cells.index).isin(["No stop", "Low"])
    sens_num.append({"m": rad, "no_stop": round(float(cells.loc[~hs, "pop"].sum() / POP), 4),
                     "poor": round(float(cells.loc[poor_r, "pop"].sum() / POP), 4)})

st4 = stops.to_crs(4326)
data = {
    "grid": {"lon0": tr.c, "lat0": tr.f, "dx": dx, "dy": dy},
    "hours": hours, "low": LOW, "walk": WALK, "date": "2026-12-03",
    "key": {k: v for k, v in KEY.items() if not isinstance(v, (list, dict))},
    "parishes": [{"name": n, **{k: (round(float(v), 4) if isinstance(v, (float, np.floating)) else v)
                                for k, v in ps.loc[n, ["residents", "no_stop", "poor", "share_poor", "share_no_stop", "mean_ai", "mean_walk_m", "stops"]].items()},
                  "geom": json.loads(json.dumps(mapping(parishes.set_index("name").loc[[n]].to_crs(4326).simplify(0.00015).iloc[0]),
                                                default=list), parse_float=lambda x: round(float(x), 5))} for n in par_names],
    "stops": [[r5(g.x), r5(g.y), m_, nm] for g, m_, nm in zip(st4.geometry, st4["mode"], st4.stop_name)],
    "hubs": [{"name": h["name"], "bc": round(float(h.betweenness), 3), "lines": int(h.lines), "modes": h.modes,
              "lon": r5(g.x), "lat": r5(g.y)} for (_, h), g in zip(top_hubs.iterrows(), top_hubs.to_crs(4326).geometry)],
    "plan": plan,
    "by_hour": [int(v) for v in by_hour.values],
    "by_mode": {k: int(v) for k, v in by_mode.items()},
    "poor_by_hour": [round(float(v), 4) for v in pbh.values],
    "models": [{"k": int(k), "random": round(float(r_["random"])), "greedy": round(float(r_.greedy)), "ilp": round(float(r_["ILP (optimal)"]))}
               for k, r_ in res.iterrows()],
    "sensitivity": sens_num,
    "moved": {k: round(float(v)) for k, v in moved.items()},
    "classes": {k: round(float(v)) for k, v in cls_pop.items()},
}
(UI / "results.json").write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
(UI / "cells.json").write_text("[\n" + ",\n".join(json.dumps(r_, separators=(",", ":")) for r_ in cell_rows) + "\n]", encoding="utf-8")
print(f"interface data: {len(cell_rows):,} cells, {len(data['stops']):,} stops, {len(plan)} plan sites; "
      f"results.json {(UI / 'results.json').stat().st_size / 1e3:.0f} kB, cells.json {(UI / 'cells.json').stat().st_size / 1e3:.0f} kB")
interface data: 10,485 cells, 3,154 stops, 20 plan sites; results.json 189 kB, cells.json 885 kB

Extra layers for the 3D dashboard (dashboard/)¶

Route geometry (one representative shape per route, clipped to Lisbon + 1.5 km and simplified) and departures per stop, used for the 3D route lines and stop towers.

In [32]:
from shapely.geometry import LineString as _LS
DASH = ROOT / "dashboard" / "data"; DASH.mkdir(parents=True, exist_ok=True)
clip = city.buffer(1500).to_crs(4326).iloc[0]
trips_per_route = feed.trips.groupby("route_id").size()
route_rows = []
for _, r_ in routes.iterrows():
    sid = first_shape.get(r_.route_id)
    if sid not in lines.index or len(lines[sid]) < 2:
        continue
    g = _LS([(lo, la) for la, lo in lines[sid]]).intersection(clip)
    if g.is_empty:
        continue
    parts = list(g.geoms) if hasattr(g, "geoms") else [g]
    for part in parts:
        if part.geom_type != "LineString" or part.length < 0.002:
            continue
        part = part.simplify(0.00008)
        route_rows.append({"m": r_["mode"], "n": str(r_.route_short_name), "a": r_.agency_name,
                           "t": int(trips_per_route.get(r_.route_id, 0)),
                           "p": [[round(x, 5), round(y, 5)] for x, y in part.coords]})
dep_day = st.groupby("stop_id").size()
dep_peak = st[(st.hour >= PEAK[0]) & (st.hour < PEAK[1])].groupby("stop_id").size() / (PEAK[1] - PEAK[0])
lines_at_stop = st.groupby("stop_id").route_short_name.nunique()
stop_rows = [[r5(g.x), r5(g.y), m_, nm, int(dep_day.get(sid, 0)), round(float(dep_peak.get(sid, 0)), 1), int(lines_at_stop.get(sid, 0))]
             for g, m_, nm, sid in zip(st4.geometry, st4["mode"], st4.stop_name, st4.stop_id)]
(DASH / "routes.json").write_text(json.dumps(route_rows, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
(DASH / "stops.json").write_text(json.dumps(stop_rows, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
import shutil
for f in ("results.json", "cells.json"):
    shutil.copy(UI / f, DASH / f)
print(f"dashboard data: {len(route_rows)} route lines, {len(stop_rows)} stops; "
      f"routes.json {(DASH / 'routes.json').stat().st_size / 1e3:.0f} kB, stops.json {(DASH / 'stops.json').stat().st_size / 1e3:.0f} kB")
dashboard data: 1641 route lines, 3154 stops; routes.json 638 kB, stops.json 185 kB