Skip to main content

9  Street network analysis

A road network has a form: its junctions, its dead ends, the directions of its streets and its connected parts. Street network analysis describes this form with numbers. This chapter gives the numbers of OSMnx on a duckOSM network, and shows that OSMnx itself works on it.

You learn

  • the two views of the statistics
  • junctions
  • street bearings and their entropy
  • connected components
  • the nearest node and edge of a point
  • a smaller area
  • random points
  • heights and grades
  • OSMnx on a duckOSM network
  • street centrality with cityseer
  • city blocks with momepy

Extras duckosm[analysis,viz]

Run this chapter in Colab

Install duckOSM (for Colab)
# Install duckOSM when it is not installed (for example in Colab). It takes approximately 1 minute.
# Until duckOSM 0.9.0 is on PyPI, the SDK of these notebooks is in the nightly wheel of main (the GitHub pre-release "nightly").
# roadstyle (the maps) also comes from its nightly wheel, so the newest roadstyle parts work with no roadstyle release.
import importlib.util, json, os, urllib.request
def nightly_wheel(repo="Khoshkhah/duckOSM", name=".whl"):        # the address of the newest nightly wheel of a repository
    release = json.load(urllib.request.urlopen(f"https://api.github.com/repos/{repo}/releases/tags/nightly"))
    return next(a["browser_download_url"] for a in release["assets"] if name in a["name"] and a["name"].endswith(".whl"))
if importlib.util.find_spec("duckosm") is None:      # not installed: install it with the extras of this notebook
    %pip install -q "duckosm[analysis,viz] @ {nightly_wheel()}"
    %pip install -q osmnx momepy mapclassify cityseer
    %pip install -q --force-reinstall --no-deps "roadstyle @ {nightly_wheel('Khoshkhah/roadstyle', 'manylinux')}"
import duckosm             # the SDK
if not hasattr(duckosm, "network"):                    # an old duckOSM (0.8.0 or older), without the SDK
    %pip install -q --force-reinstall --no-deps "duckosm @ {nightly_wheel()}"
    raise SystemExit("duckOSM is updated: restart the session (in Colab: Runtime > Restart session), then run this cell again")
print("duckosm", duckosm.__version__)    # the version
# The network of chapter 1 (monaco.duckdb). The chapter opens it. When you run this chapter alone (in Colab), the file
# is not there, so this cell makes it one time.
if not os.path.exists("monaco.duckdb") or not duckosm.open("monaco.duckdb").has_mode("driving", "walking", "cycling"):
    duckosm.network(osm_id=2220322, modes=["driving", "walking", "cycling"], path="monaco.duckdb")

9.1 What street network analysis measures

Street network analysis describes the form of a road network with numbers. How many junctions does a city have? How long is a street on average? Do the streets make a grid? Can you drive from each place to each other place? Urban planners and researchers ask these questions, and the Python library OSMnx answers them for OpenStreetMap data.

The module duckosm.analysis gives the functions of OSMnx 2 on a duckOSM network. The counts, the bearings, the components and the nearest searches run in Rust, on the tables of the file. Each function takes a mode view (net.driving), a network with one mode, or a path with mode=.

Question duckOSM OSMnx
How large is the network? stats basic_stats
How many streets meet at each node? streets_per_node count_streets_per_node
In which direction does each street go? bearings, orientation_entropy, plot_orientation add_edge_bearings, orientation_entropy, plot_orientation
Which parts are connected? components, largest_component networkx, largest_component
Which node or edge is nearest to a point? nearest_nodes, nearest_edges nearest_nodes, nearest_edges
What is in a smaller area? clip truncate_graph_bbox, truncate_graph_polygon
How steep is each street? add_elevation, grades add_node_elevations_raster, add_edge_grades
Where are random points on the streets? sample_points sample_points
Can OSMnx itself work on it? to_osmnx the OSMnx graph

The guide duckOSM for OSMnx users gives the duckOSM call for each OSMnx call.

9.1.1 Two views of one network

duckOSM and OSMnx cut the roads at different places. OSMnx keeps a node only where the streets meet or end (simplify_graph). duckOSM also cuts a road where another mode joins it, where its tags change and where an OSM way ends, because your data joins to each of these edges by edge_id. So a duckOSM network has more nodes and edges than the OSMnx graph of the same area.

The duckosm view keeps every node, and the osmnx view removes the nodes where only two roads meet

The duckosm view keeps every node, and the osmnx view removes the nodes where only two roads meet

stats gives each number in two views:

View Nodes and edges Use it
osmnx a node where a road only passes through (it has exactly 2 neighbor nodes) is removed, and its two edges become one edge to compare with OSMnx and with published OSMnx numbers
duckosm every row of <mode>.nodes and <mode>.edges to count the rows that your data joins to
ImportantKey idea

The osmnx view gives the numbers that OSMnx gives for the same roads. The duckosm view counts the rows of the file. Use the osmnx view to compare cities, and the duckosm view to plan your own data.

9.2 Open the network of chapter 1

Chapter 1 builds Monaco with three modes (driving, walking and cycling) and saves it as monaco.duckdb. This chapter opens that file with duckosm.open: it builds nothing. The analysis uses the driving network, net.driving. an is the short name of the module.

from duckosm import analysis as an
net = duckosm.open("monaco.duckdb")
net.driving
driving of monaco.duckdb
mode edges nodes km oneway_km
driving 2840 1768 96.2 35.5

9.3 Statistics: stats

stats(view) gives the numbers of OSMnx basic_stats as a DataFrame: one row for each key, one column for each view. net.driving.stats() gives the same table.

Key What it is
n, m the number of nodes and of edges (a two-way road is two edges)
k_avg the average degree: 2 × m / n
edge_length_total, edge_length_avg the sum and the average of the edge lengths, in metres
streets_per_node_avg the average number of streets at a node
intersection_count the nodes with 2 or more streets (OSMnx’s rule)
street_length_total, street_segment_count, street_length_avg the same as the edge keys, with a two-way road counted once
circuity_avg the length of the streets divided by the straight distance between their ends
self_loop_proportion the share of edges that start and end at the same node
s = an.stats(net.driving)
s.drop(["streets_per_node_counts", "streets_per_node_proportions"])
osmnx duckosm
n 843 1768
m 1484 2840
k_avg 3.520759 3.21267
edge_length_total 96058.971143 96207.398536
edge_length_avg 64.729765 33.875845
streets_per_node_avg 2.537367 2.256787
intersection_count 636 1561
street_length_total 65778.865675 65866.686087
street_segment_count 1070 1997
street_length_avg 61.475575 32.982817
circuity_avg 1.173462 1.075075
self_loop_proportion 0.004673 0.0
NoteWhat the output shows

The duckosm view counts 1,768 nodes and 2,840 edges: the rows of the file. The osmnx view counts 843 nodes and 1,484 edges, about half. The lengths are almost the same (65.8 km and 65.9 km of streets), because the same roads are in both views. So the average street is 61 m in the osmnx view and 33 m in the duckosm view. The 2-road nodes count as intersections in the duckosm view: 1,561, not 636. The circuity is 1.17 in the osmnx view: the streets of Monaco follow the hills and the coast.

9.3.1 The densities: area_m2

OSMnx gives the densities only when you give the area. area_m2= is the area in square metres. Here it is the area of the boundary of the network (net.boundary), measured in its UTM zone. The node and intersection densities are counts per km². The edge and street densities are metres per km².

b = net.boundary
utm = b.estimate_utm_crs()
area_m2 = b.to_crs(utm).area.sum()
print(f"area: {area_m2 / 1e6:.2f} km2")
area: 2.39 km2
dens = an.stats(net.driving, area_m2=area_m2)
dens.loc[["node_density_km", "intersection_density_km", "edge_density_km", "street_density_km"]].round(1)
osmnx duckosm
node_density_km 352.644024 739.590314
intersection_density_km 266.051719 652.998009
edge_density_km 40183.418903 40245.509096
street_density_km 27516.635697 27553.372759

The boundary of the city has 2.39 km². In the osmnx view Monaco has 353 nodes and 266 intersections per km², and 27,517 m of streets per km². The street density is almost the same in the two views. The node density of the duckosm view is twice as large.

9.3.2 The streets at the nodes

The keys streets_per_node_counts and streets_per_node_proportions are dicts: the number of nodes (or their share) for each count of streets.

import pandas as pd

counts = pd.DataFrame(s.loc["streets_per_node_counts"].to_dict())
counts.sort_index()
osmnx duckosm
0 0 0
1 207 207
2 24 948
3 566 567
4 44 44
5 2 2
NoteWhat the output shows

Both views have 207 dead ends, about 566 T junctions, 44 crossings and 2 nodes with five streets. They differ only in the nodes with two streets: 948 in the duckosm view, 24 in the osmnx view. OSMnx keeps a 2-street node only where it must, for example where a loop starts and ends at the same node.

9.4 Junctions: streets_per_node

streets_per_node(view) gives the number of streets at each node of the duckosm view, as a Series with the node_id as its index. A two-way road counts once.

Streets The node is
1 a dead end
2 a road passing through (or a place where the tags change)
3 a T junction
4 a crossing

The map shows the dead ends, the T junctions and the crossings.

spn = an.streets_per_node(net.driving)
spn.value_counts().sort_index()
streets
1    207
2    948
3    567
4     44
5      2
Name: count, dtype: int64
import matplotlib.pyplot as plt

nodes = net.driving.nodes().set_index("node_id")
nodes["streets"] = spn
fig, ax = plt.subplots(figsize=(7, 7))
net.driving.edges().plot(ax=ax, color="lightgray", linewidth=0.6)
classes = [(1, "#d1242f", "dead end"), (3, "#bf8700", "T junction"), (4, "#2ea043", "crossing")]
for k, color, label in classes:
    nodes[nodes.streets == k].plot(ax=ax, color=color, markersize=6, label=label)
ax.legend(title="node", loc="lower right")
ax.set_axis_off()
plt.show()

NoteWhat the output shows

The counts are the classes of the duckosm view: 948 nodes with two streets, 567 T junctions, 207 dead ends and 44 crossings. Monaco has few crossings: its streets meet mostly at T junctions, on the slopes. Many dead ends are at the edge of the city, where the boundary cuts the streets, and at the entries of garages.

9.5 Street directions

9.5.1 The bearing of each edge: bearings

bearings(view) gives the compass bearing of each edge, from its source node to its target node: 0 is north, 90 is east, 180 is south and 270 is west. The result is a Series with the edge_id as its index. A self-loop has NaN.

brg = an.bearings(net.driving)
brg.describe().round(1)
count    2840.0
mean      169.0
std       102.6
min         0.2
25%        73.3
50%       174.1
75%       246.7
max       359.3
Name: bearing, dtype: float64

9.5.2 Grid or not: orientation_entropy

orientation_entropy(view) puts the bearings into num_bins bins (default 36 bins of 10 degrees) and gives the entropy of the bins. The entropy is large when the streets go in all directions, and small when they go in few.

Network Entropy
the streets go in all directions equally ln(36) = 3.58
a perfect grid (four directions) ln(4) = 1.39

weight="length" lets a long street count more than a short street.

print("orientation entropy:", round(an.orientation_entropy(net.driving), 3))
print("weighted by length:", round(an.orientation_entropy(net.driving, weight="length"), 3))
orientation entropy: 3.528
weighted by length: 3.48

The entropy of Monaco is 3.528, near the largest value of 3.58: the streets go in almost all directions. With weight="length" it is 3.48: the long streets have a few more common directions, along the coast from southwest to northeast.

9.5.3 The polar histogram: plot_orientation

plot_orientation(view) draws the bearings as a polar histogram, as OSMnx does. The area of each bar shows its share. It gives (fig, ax), so you can put it into your own figure with ax= and give it a title=.

fig, ax = an.plot_orientation(net.driving, title="Monaco, driving")
plt.show()

The bars are of almost equal size in all directions. The longest bars point to the northeast and to the southwest, along the coast. A city with a grid shows four long bars at right angles.

9.6 Connected parts

9.6.1 The component of each node: components

A strongly connected component is a set of nodes in which you can go from each node to each other node, along the directions of the edges. components(view) gives the component of each node, as a Series with the node_id as its index. Component 0 is the largest, 1 is the next, and so on. strong=False gives the weakly connected components: the directions of the edges do not count.

comp = an.components(net.driving)
print(f"{comp.nunique()} parts; the largest has {(comp == 0).sum():,} of {len(comp):,} nodes")
weak = an.components(net.driving, strong=False)
print(f"weakly connected: {weak.nunique()} parts; the largest has {(weak == 0).sum():,} nodes")
122 parts; the largest has 1,600 of 1,768 nodes
weakly connected: 16 parts; the largest has 1,718 nodes
NoteWhat the output shows

The driving network has 122 strongly connected parts. The largest has 1,600 of the 1,768 nodes. The other 121 parts are small: most are one node, for example the end of a one-way garage ramp that only leaves the network. When the directions do not count, the network has only 16 parts, and the largest has 1,718 nodes.

9.6.2 The largest part: largest_component

largest_component(view, out=...) writes a new network file with only the largest component of the mode. The mode keeps the nodes, the edges and the turn tables of that component. The other modes of the file do not change. Use it before an analysis that needs a connected graph, for example a matrix of all pairs. The map shows the edges outside the largest part in orange.

big = an.largest_component(net.driving, out="data/monaco_largest.duckdb")
edges = net.driving.edges()
inside = edges.edge_id.isin(big.driving.edges().edge_id)
print(inside.sum(), "of", len(edges), "edges are in the largest part")
2622 of 2840 edges are in the largest part
net.driving.plot(highlight=edges.edge_id[~inside])

The largest part has 2,622 of the 2,840 edges. The 218 orange edges are outside it: garage ramps, private service roads, and short roads at the boundary of the city that you can enter but not leave (or leave but not enter).

9.7 From points to the network

nearest_nodes(view, x, y) and nearest_edges(view, x, y) join points to the network: addresses, sensors, GPS points or bus stops. x is the longitudes and y the latitudes, as numbers or arrays. The result has the same shape: an array for arrays, a number for a number. return_dist=True also gives the distances in metres.

nearest_edges measures the distance to the line of the edge. The two edges of a two-way road are at the same distance, so the edge with the lower edge_id comes.

Here the points are ten random points in the box of the network (black). The edge of each point is orange.

import numpy as np

rng = np.random.default_rng(1)
west, south, east, north = edges.total_bounds
xs = rng.uniform(west, east, 10)
ys = rng.uniform(south, north, 10)
ids, dist = an.nearest_edges(net.driving, xs, ys, return_dist=True)
node_ids = an.nearest_nodes(net.driving, xs, ys)
pd.DataFrame({"edge_id": ids, "distance_m": dist.round(1), "node_id": node_ids}).head(3)
edge_id distance_m node_id
0 1754122589688343229 374.9 25212793
1 2179780264819535765 618.3 12136114443
2 3363728794791538739 12.1 1784107000
fig, ax = plt.subplots(figsize=(7, 7))
net.driving.plot(highlight=ids, ax=ax)
ax.scatter(xs, ys, color="black", s=20, zorder=3)
plt.show()

The table has the edge_id and the node_id of each point, and the distance to the edge in metres. The first two points are 375 m and 618 m from a road: they are in the sea, in the box of the network but outside the city. The third point is 12 m from its road. The map shows each point and its edge.

TipTip

To put your own data on the network, join the edge_id of nearest_edges to your rows. Chapter 4. Join your data by edge_id shows the join.

9.8 A smaller area: clip

clip(net, ...) writes a new network file with the edges inside an area. Give one area:

Argument The area
bbox=(west, south, east, north) a box in degrees
polygon= a shapely polygon or a GeoDataFrame
point=(lon, lat) with dist_m= the circle of dist_m metres around the point

An edge that crosses the border stays whole, as in a build (chapter 1. Get and build an area). Here the area is 500 m around the casino square.

small = an.clip(net, point=(7.4280, 43.7393), dist_m=500, out="data/monaco_casino.duckdb")
print(len(small.driving.edges()), "of", len(net.driving.edges()), "edges")
small.driving.plot()
702 of 2840 edges

The circle of 500 m around the casino square holds 702 of the 2,840 edges. The new file is a full network, with its own nodes and turn tables, so every call of this chapter and of the routing chapters works on it.

9.9 Random points on the roads: sample_points

sample_points(view, n, seed=...) gives n random points on the streets, as a GeoDataFrame with the edge_id of each point. A street is chosen with a chance that follows its length, so a longer street gets more points. The two edges of a two-way road count as one street. The same seed gives the same points. Use the points as random trip starts or to test a sensor plan.

pts = an.sample_points(net.driving, 200, seed=1)
print(len(pts), "points on", pts.edge_id.nunique(), "edges")
pts.head(3)
200 points on 168 edges
edge_id geometry
0 3573362122345682814 POINT (7.41198 43.72807)
1 8503051478251022153 POINT (7.41666 43.732)
2 1061984460650555701 POINT (7.42884 43.74604)

The 200 points are on 168 edges: a long edge can get more than one point.

9.10 Heights and grades

9.10.1 Add the ground height: add_elevation

add_elevation(net) adds the ground height to the nodes (ele) and to the edges (z_from, z_to, z_vertices). It changes the file in place. dem= takes a DEM file (GeoTIFF) of your own. Without it, the call finds a source for the area (source="auto") and downloads its tiles into the cache. For Monaco the source is Copernicus. Add elevation gives the sources and the options.

an.add_elevation(net.driving)
net.driving.nodes()["ele"].describe().round(1)
  source=auto → copernicus (bbox 7.41, 43.73, 7.44, 43.75)
  [driving] 1768 nodes sampled (0 nodata/fill) -> ele
  1 Copernicus tiles downloaded, 12.6 MB
count    1768.0
mean       42.6
std        33.4
min        -0.5
25%        15.3
50%        33.9
75%        65.7
max       336.4
Name: ele, dtype: float64

The progress lines show the source (Copernicus, one tile of 12.6 MB) and the 1,768 nodes that got a height. The heights go from -0.5 m at the sea to 336 m, and the median is 34 m. Monaco rises fast from the coast.

9.10.2 The grade of each edge: grades

grades(view) gives (z_to - z_from) / length_m for each edge, as a Series with the edge_id as its index. 0.05 is 5 % up, and -0.05 is 5 % down. It needs add_elevation first.

g = an.grades(net.driving)
print(f"the steepest of all edges: {g.abs().max():.0%}")
the steepest of all edges: 880%
e = net.driving.edges().set_index("edge_id")
long = e.length_m >= 50
ground = e.tunnel.isna() & e.bridge.isna()
ok = g[long & ground]
ok.abs().describe(percentiles=[0.5, 0.9]).round(3)
count    471.000
mean       0.071
std        0.065
min        0.000
50%        0.051
90%        0.158
max        0.351
Name: grade, dtype: float64

Over all edges the steepest grade is 880 %: a wrong value on a tunnel or a short edge. The second cell keeps only the edges of 50 m or more that are on the ground. For these 471 edges of 50 m or more that are not tunnels or bridges, the steepest is 35 %, the median is 5.1 % and 90 % of the edges are below 15.8 %. Monaco is a steep city.

WarningWarning

A DEM gives the height of the ground. A tunnel or a bridge is not on the ground, so its grade from the DEM is wrong. A short edge on a slope can also get a large grade from the cells of the DEM. Remove these edges before you use the grades.

9.11 OSMnx on the network: to_osmnx

to_osmnx(view) gives the mode as the networkx.MultiDiGraph of OSMnx. Each OSMnx function works on it: the graph passes ox.convert.validate_graph. The node keys are the node_id. Each edge keeps its edge_id and has the OSMnx names: osmid, length, geometry, highway, name, oneway, lanes, speed_kph and travel_time.

Here OSMnx finds a route on the largest part (big, above) with its own shortest_path.

import osmnx as ox

G = an.to_osmnx(big.driving)
print(G)
MultiDiGraph named 'monaco_largest' with 1600 nodes and 2622 edges
orig, dest = an.nearest_nodes(big.driving, [7.4155, 7.4370], [43.7310, 43.7480])
route = ox.routing.shortest_path(G, orig, dest, weight="travel_time")
route_edges = ox.routing.route_to_gdf(G, route)
len(route_edges), round(route_edges["length"].sum()), round(route_edges["travel_time"].sum())
(67, 2889, 202)

The graph of the largest part has 1,600 nodes and 2,622 edges, the same as big. OSMnx found a route on it with its own shortest_path: 67 edges, 2,889 m and 202 s.

9.11.1 Check: the osmnx view gives the numbers of OSMnx

Section “Statistics: stats” says that the osmnx view of stats gives the numbers of OSMnx. This check proves it: it computes the same numbers in two ways, on the same driving network of Monaco, and compares them.

Way What it does
duckOSM an.stats(net.driving)["osmnx"]: the osmnx view of duckOSM’s own statistics
OSMnx to_osmnx gives the network to OSMnx, OSMnx simplifies it (it removes the nodes where only two roads meet), and ox.basic_stats counts it

One detail: to_osmnx marks the graph as simplified, because each edge already has its full line. OSMnx does not simplify a graph with that mark. So the cell sets H.graph["simplified"] = False first, and then OSMnx simplifies it as it does with its own graphs.

H = an.to_osmnx(net.driving)
H.graph["simplified"] = False
theirs = ox.basic_stats(ox.simplify_graph(H))
ours = an.stats(net.driving)["osmnx"]
keys = ["n", "m", "intersection_count", "street_segment_count"]
pd.DataFrame({"duckOSM": [ours[k] for k in keys], "OSMnx": [theirs[k] for k in keys]}, index=keys)
duckOSM OSMnx
n 843 843
m 1484 1484
intersection_count 636 636
street_segment_count 1070 1070

The two columns are the same: 843 nodes (n), 1,484 edges (m), 636 intersections and 1,070 street segments. So you can use an.stats and compare its osmnx view with any number that OSMnx gives for another city. The tests of duckOSM run this check for each key.

9.12 Street centrality with cityseer

cityseer measures how central each street junction is, for people who walk. It computes two measures within a walking distance:

Measure Column The question it answers
closeness (harmonic) cc_harmonic_<distance> How easy is it to reach the other junctions from here? The sum of 1 / distance to each junction within the distance
betweenness cc_betweenness_<distance> How many shortest walks between two junctions within the distance pass through here?

The steps:

  1. Give cityseer the walking network as lines in metres, one line for each street.
  2. cityseer makes its own graph and its network structure (io.nx_from_generic_geopandas, io.network_structure_from_nx).
  3. Compute the two measures within 400 m and 800 m (about 5 and 10 minutes on foot).

The first lines of the cell stop cityseer’s progress bars and information lines.

import logging

from cityseer import config
from cityseer.metrics import networks
from cityseer.tools import io

config.QUIET_MODE = True
logging.getLogger("cityseer").setLevel(logging.WARNING)
walk = net.walking.edges()
walk = walk[~walk.is_reverse].to_crs(walk.estimate_utm_crs())[["edge_id", "geometry"]]
graph = io.nx_from_generic_geopandas(walk)
junctions, segments, structure = io.network_structure_from_nx(graph)
len(junctions), len(segments)
(4589, 11874)

cityseer’s network has 4,589 junctions (the walking nodes of duckOSM) and 11,874 segments: each street in both directions.

junctions = networks.centrality_shortest(structure, junctions, distances=[400, 800])
columns = ["cc_harmonic_400", "cc_harmonic_800", "cc_betweenness_400", "cc_betweenness_800"]
junctions[columns].describe().loc[["mean", "50%", "max"]].round(1)
cc_harmonic_400 cc_harmonic_800 cc_betweenness_400 cc_betweenness_800
mean 2.5 3.8 2434.9 13338.4
50% 2.4 3.8 1367.0 6060.0
max 8.5 9.5 18878.0 163846.0

Within 400 m the middle junction has a closeness of 2.4, and within 800 m 3.8. Betweenness is very uneven: the middle junction is on 6,060 shortest walks within 800 m, and the busiest junction on 163,846.

from matplotlib.colors import LogNorm, Normalize

junctions["betweenness_800"] = junctions.cc_betweenness_800.clip(lower=1)
fig, axes = plt.subplots(1, 2, figsize=(14, 7))
for ax, column, norm, title in [(axes[0], "cc_harmonic_800", Normalize(), "closeness within 800 m"),
                                (axes[1], "betweenness_800", LogNorm(), "betweenness within 800 m (log scale)")]:
    walk.plot(ax=ax, color="lightgray", linewidth=0.4)
    order = junctions.sort_values(column)
    order.plot(ax=ax, column=column, cmap="viridis", norm=norm, markersize=4, legend=True,
               legend_kwds={"label": title, "shrink": 0.6})
    ax.set_axis_off()
plt.show()

Closeness (left) is highest in the dense centers near the port and in Monte Carlo, where many footways and steps meet. Betweenness (right, on a log scale) shows lines: the few streets and steps that join the parts of Monaco, so many walks pass through them. The dark junctions at the edges are on few or no shortest walks.

9.13 City blocks with momepy

A city block is the land between streets, with its buildings. Planners use blocks to compare parts of a city: small blocks make a city easy to walk, and large blocks make long detours. momepy is a Python library that measures the shape of a city. It makes the blocks from three layers. duckOSM gives all three from the same OSM file:

Layer From duckOSM
The streets the edges of the network (net.driving.edges(), net.walking.edges())
The buildings duckosm.gis.features(net, tags={"building": True}) (chapter 10)
The land the boundary of the area (net.boundary) less the water

momepy makes the blocks in three steps:

  1. Enclosures: it cuts the land along the streets. Each enclosure is an area with streets around it.
  2. Cells: it divides each enclosure into one cell for each building (a tessellation). A cell is the land that is nearer to its building than to other buildings.
  3. Blocks: it joins the cells of the buildings that are between the same streets. A cell with no building goes into no block.

9.13.1 The streets

momepy needs one line for each street, in metres. The network has one edge for each direction of a two-way street, so the cell keeps the edges with is_reverse false. It takes the walking edges too: in Monaco many streets join only by steps and footways. It removes the tunnels, because a tunnel does not cut the land above it.

import momepy

lines = pd.concat([net.driving.edges(), net.walking.edges()])
lines = lines.drop_duplicates("edge_id")
lines = lines[~lines.is_reverse & lines.tunnel.isna()]
crs = lines.estimate_utm_crs()
streets = lines.to_crs(crs)[["edge_id", "highway", "lanes", "oneway", "geometry"]]
len(streets)
6115

9.13.2 The buildings and the land

The buildings are the OSM areas with a building tag. The land is the boundary less the water: the lakes (natural=water) and the two ports of Monaco (leisure=marina).

buildings = duckosm.gis.features(net, tags={"building": True}).to_crs(crs)
buildings = buildings[buildings.geom_type.isin(["Polygon", "MultiPolygon"])]
buildings = buildings.explode(index_parts=False).reset_index(drop=True)[["geometry"]]
water = duckosm.gis.features(net, tags={"natural": ["water"], "leisure": ["marina"]}).to_crs(crs)
area = net.boundary.to_crs(crs).union_all()
land = area.difference(water.union_all())
len(buildings), round(land.area / 1e6, 2)
(1258, 2.08)

9.13.3 Land with no building

momepy puts a cell into a block only when the cell has a building. A park, a beach or a quay at the sea has no building, so its land goes into no block, and the roads on that land are outside all blocks. To keep this land, the next cell gives momepy two more kinds of area as if they were buildings:

Area Why
The OSM land areas: parks, gardens, sports grounds, grass, forest, beaches, parking their land then goes into a block
The sea, the ports and the land outside the area, as one polygon around the land the land along the coast and along the edge of the area then goes into a block

After momepy, the sea, the ports and the land outside the area are cut out of the result again. This changes only what momepy gets as input, not what momepy does.

import geopandas as gpd
import shapely

tags = {"leisure": ["park", "garden", "pitch", "playground", "sports_centre", "track", "stadium"],
        "landuse": ["grass", "forest", "recreation_ground", "cemetery", "meadow", "village_green", "flowerbed"],
        "natural": ["wood", "beach", "scrub", "grassland", "bare_rock", "heath"],
        "amenity": ["parking"]}
open_land = duckosm.gis.features(net, tags=tags).to_crs(crs)
open_land = open_land.geometry.intersection(land).difference(buildings.union_all())
frame = shapely.box(*area.buffer(300).bounds)
sea = frame.difference(land)
extra = gpd.GeoSeries(pd.concat([open_land, gpd.GeoSeries([sea], crs=crs)]), crs=crs).explode(index_parts=False)
extra = extra[extra.geom_type.eq("Polygon") & (extra.area > 20)]
things = gpd.GeoDataFrame(geometry=pd.concat([buildings.geometry, extra]), crs=crs).reset_index(drop=True)
len(buildings), len(extra), len(things)
(1258, 246, 1504)

momepy gets 1,504 areas: the 1,258 buildings and 246 extra areas (the OSM land areas, and the pieces of the polygon of the sea, the ports and the land outside the area).

9.13.4 The three steps

momepy works on the frame (the rectangle around the area), with the buildings and the extra areas. Then the fourth line cuts the sea, the ports and the land outside the area out of the blocks. momepy.generate_blocks gives two results: the blocks, and the block of each building. This chapter uses only the blocks.

enc = momepy.enclosures(streets, limit=gpd.GeoSeries([frame], crs=crs))
cells = momepy.enclosed_tessellation(things, enc)
blocks, _ = momepy.generate_blocks(cells, streets, things)
blocks = gpd.GeoDataFrame(geometry=blocks.intersection(land), crs=crs).explode(index_parts=False)
blocks = blocks[blocks.area > 1].reset_index(drop=True)
len(enc), len(cells), len(blocks)
(1635, 2870, 404)

momepy cuts the frame into 1,635 enclosures and 2,870 cells, and joins the cells into blocks. After the cut, 404 blocks are on the land.

The next cell measures the share of the road length on the land that is in no block and on no block border.

on_land = streets.intersection(land).length.sum()
in_blocks = streets.intersection(blocks.buffer(0.5).union_all()).length.sum()
round(1 - in_blocks / on_land, 2)
np.float64(0.15)

15 % of the road length on the land is still outside all blocks. These roads run on land with no building and no OSM land area: small pieces of land with roads all around them, such as traffic islands, corners at junctions and the middle strip of a divided road. These pieces are street land, not blocks, so they stay empty on the maps.

9.13.5 The size of the blocks

The cell gives each block its area in hectares (1 ha = 10,000 m², about a football field and a half) and puts it in a size class.

blocks["ha"] = blocks.area / 10_000
classes = ["< 0.1 ha", "0.1-0.5 ha", "0.5-1 ha", "1-5 ha", "> 5 ha"]
blocks["size"] = pd.cut(blocks.ha, [0, 0.1, 0.5, 1, 5, 1000], labels=classes)
blocks["size"].value_counts().sort_index()
size
< 0.1 ha      169
0.1-0.5 ha    152
0.5-1 ha       46
1-5 ha         34
> 5 ha          3
Name: count, dtype: int64

Most blocks are small: 169 blocks have less than 0.1 ha, and 152 have 0.1 to 0.5 ha. Only 3 blocks have more than 5 ha. They are on the coast and on the slopes, where few streets cut the land.

The blocks change with the streets that you give to momepy. With the driving streets only, many steps and footways do not cut the land, and the blocks become larger.

9.13.6 The map of momepy’s blocks

This map shows the blocks as momepy gives them, with only the water cut out. Each block reaches the center line of its streets, so two blocks on the two sides of a street touch at that line.

The first cell sorts the roads into three kinds, for the maps: main roads, streets, and footways and steps.

main = ["motorway", "trunk", "primary", "secondary", "tertiary"]
paths = ["footway", "steps", "pedestrian", "path", "cycleway", "corridor"]
kind = pd.Series("street", index=streets.index)
kind[streets.highway.str.replace("_link", "").isin(main)] = "main road"
kind[streets.highway.isin(paths)] = "footway, steps"
kind.value_counts()
footway, steps    4184
street            1210
main road          721
Name: count, dtype: int64

Monaco has 4,184 footways and steps, 1,210 streets and 721 main roads. Most lines are footways and steps: Monaco has many of them between its streets, on the slopes.

The second cell makes a function, block_map, that draws blocks. The two maps below use it. The maps draw the footways, but not the roads for cars: block_map(blocks, roads=True) also draws the center lines of the main roads and the streets. Each block is a half-transparent polygon with a border inside it, on top of the buildings. The border is a band of 1 m inside the polygon, so it does not make the block larger. Two blocks that touch never have the same color: mapclassify.greedy gives each block one of six colors in this way. The map is an SVG, a vector picture: click it and zoom in to one block, and it stays sharp. The plain gray areas in the middle are the two ports.

Layer, from the bottom to the top Style
The street space (only on the second map) white
The footways and the steps brown dashed lines
The buildings gray
The blocks half-transparent, with a border of 1 m inside the polygon, in the same color
import io

import geopandas as gpd
import mapclassify
from IPython.display import SVG
from matplotlib.colors import ListedColormap
from matplotlib.lines import Line2D
from matplotlib.patches import Patch

six = ListedColormap(["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e", "#e6ab02"])


def block_map(blks, space=None, roads=False):
    """The map of the blocks blks as an SVG: with the street space space (a polygon) if you give it, and with the
    center lines of the main roads and the streets if roads is True."""
    color = mapclassify.greedy(blks, min_colors=6)
    fig, ax = plt.subplots(figsize=(12, 13))
    ax.set_facecolor("#e8e8e8")
    legend = []
    if space is not None:
        gpd.GeoSeries([space], crs=blks.crs).plot(ax=ax, color="white")
        legend.append(Patch(facecolor="white", edgecolor="#bbbbbb", label="street space"))
    streets[kind == "footway, steps"].plot(ax=ax, color="#8b4513", linewidth=0.25, linestyle=(0, (4, 3)))
    if roads:
        streets[kind != "footway, steps"].plot(ax=ax, color="#666666", linewidth=0.4)
        legend.append(Line2D([], [], color="#666666", linewidth=0.8, label="road (center line)"))
    buildings.plot(ax=ax, color="#9e9e9e", edgecolor="#6e6e6e", linewidth=0.2)
    blks.plot(ax=ax, color=[six(c) for c in color], alpha=0.45)
    border = blks.difference(blks.buffer(-1))
    border.plot(ax=ax, color=[six(c) for c in color])
    legend += [Patch(facecolor=(0.11, 0.62, 0.47, 0.45), edgecolor="#1b9e77", linewidth=1.5, label="block (six colors)"),
               Patch(facecolor="#9e9e9e", edgecolor="#6e6e6e", label="building"),
               Line2D([], [], color="#8b4513", linewidth=0.5, linestyle=(0, (4, 3)), label="footway, steps")]
    ax.legend(handles=legend, title="Blocks of Monaco", loc="lower right", facecolor="#e8e8e8")
    ax.set_xticks([])
    ax.set_yticks([])
    svg = io.StringIO()
    fig.savefig(svg, format="svg", bbox_inches="tight")
    plt.close(fig)
    return SVG(svg.getvalue())


block_map(blocks)

Each polygon is one block of momepy. Where a street separates two blocks, the two borders touch at the center line of the street.

9.13.7 The street space

On the first map the streets have no space of their own: two blocks on the two sides of a street touch at its center line. A real street has a width. This section gives momepy the two edges of each street, not only its center line, so that momepy itself makes blocks that stop at the street edge.

The width of each street

OSM gives the width of few streets: in Monaco, 32 of 3,502 road ways have a width tag. So the next cell gives each road a width in one of three ways. The map reads only the column streets["width"]:

Way How Change it
By kind one width for each kind: main road 12 m, street 8 m, footway or steps 2 m the dict widths
From the lanes (used here) lanes × 3.25 m for each lane, on both sides of a two-way road, plus 2 m for the sidewalks. Footways and steps, and roads with no lanes, take the width of their kind the lane width and the sidewalk width in the cell
Your own any width that you have, for example measured widths put them into streets["width"]
widths = {"main road": 12.0, "street": 8.0, "footway, steps": 2.0}
by_kind = kind.map(widths)
sides = streets.oneway.map({True: 1, False: 2}).fillna(2)
by_lanes = streets.lanes * sides * 3.25 + 2.0
streets["width"] = by_lanes.where(kind != "footway, steps").fillna(by_kind)
streets.groupby(kind).width.describe()[["count", "min", "50%", "max"]].round(1)
count min 50% max
footway, steps 4184.0 2.0 2.0 2.0
main road 721.0 5.2 8.5 15.0
street 1210.0 5.2 8.5 8.5

The footways and the steps are 2 m wide. Most streets and main roads are 8.5 m: one lane in each direction (2 × 3.25 m) plus 2 m of sidewalks. A one-way road with one lane is 5.25 m, and the widest main roads, with four lanes, are 15 m.

Momepy with the street edges

The steps of the first cell:

  1. Find the roads that stop inside a block on the first map: a garden path, steps or a driveway. They are a part of their block, so they get no street space.
  2. Make the street space: each other road with its width, less the buildings. A street never goes through a building. ends gives the shape of the end of a road: "flat" (cut square, used here) or "round" (a half circle).
  3. Take the outline of the street space: the two edges of each street.
  4. Take the street space out of the extra areas (the parks and the sea), so that they do not fill the streets.
  5. Give momepy each building and area 10 cm smaller. Where a building touches a street edge, momepy otherwise puts the street strip into the block of that building. This changes only the input: the blocks are made of momepy’s cells, so their shapes do not change.
ends = "flat"
half = streets["width"] / 2
inside = streets.sjoin(blocks[["geometry"]], predicate="within").index.unique()
between = streets.drop(inside)
space = between.buffer(half.drop(inside), cap_style=ends).union_all().difference(buildings.union_all())
edges = gpd.GeoSeries([space], crs=crs).explode(index_parts=False).boundary.explode(index_parts=False)
cut = pd.concat([streets.geometry, edges])
cut = gpd.GeoDataFrame(geometry=cut, crs=crs).reset_index(drop=True)
extra2 = extra.difference(space).explode(index_parts=False)
extra2 = extra2[extra2.geom_type.eq("Polygon") & (extra2.area > 20)]
things2 = gpd.GeoDataFrame(geometry=pd.concat([buildings.geometry, extra2]), crs=crs).reset_index(drop=True)
things2 = gpd.GeoDataFrame(geometry=things2.buffer(-0.1), crs=crs)
things2 = things2[~things2.is_empty].reset_index(drop=True)
len(inside), round(space.intersection(land).area / 1e6, 2)
(1871, 0.29)

1,871 roads stop inside a block on the first map, so they get no street space. The street space of the other roads covers 0.29 km² of the land of Monaco.

The second cell runs the same three steps of momepy as before, with the new lines, and cuts out the water again.

enc2 = momepy.enclosures(cut, limit=gpd.GeoSeries([frame], crs=crs))
cells2 = momepy.enclosed_tessellation(things2, enc2)
blocks2, _ = momepy.generate_blocks(cells2, cut, things2)
blocks2 = gpd.GeoDataFrame(geometry=blocks2.intersection(land), crs=crs).explode(index_parts=False)
blocks2 = blocks2[blocks2.area > 1].reset_index(drop=True)
len(blocks2), round(blocks2.area.sum() / 1e6, 2)
(448, np.float64(1.71))

momepy makes 448 blocks on the land, and they cover 1.71 km². No block covers the street space. There are more blocks than on the first map, because the street edges cut the land into more pieces.

block_map(blocks2, space)

The street space is white between the blocks. Each block is a block of momepy: momepy made it with the street edges as input, so it stops at the edge of its streets. A building is never cut by the street space.

9.14 Try it yourself

1. Give the statistics of the walking network of Monaco, and compare streets_per_node_avg with driving.

an.stats(net.walking).loc[["n", "m", "streets_per_node_avg"]]

2. Count the dead ends of the network of 500 m around the casino square (small, above).

(an.streets_per_node(small.driving) == 1).sum()

3. Clip the network to a box around the port, and give its orientation entropy.

port = an.clip(net, bbox=(7.418, 43.730, 7.430, 43.738), out="data/port.duckdb")
an.orientation_entropy(port.driving)

4. Draw the edges whose grade is more than 10 % (on the ground, 50 m or more).

steep = ok[ok.abs() > 0.10].index
net.plot(highlight=list(steep))

9.15 Words in this chapter

Word Meaning
street network analysis the description of the form of a road network with numbers
view a way to count the nodes and edges: osmnx (2-road nodes removed) or duckosm (every row)
intersection a node where 2 or more streets meet (OSMnx’s rule)
dead end a node with one street
circuity the length of a street divided by the straight distance between its ends
bearing the compass direction of an edge, from 0 (north) to 360 degrees
orientation entropy a number for the spread of the street directions: 1.39 for a grid, 3.58 for all directions
strongly connected component a set of nodes where you can go from each node to each other node along the edge directions
DEM a digital elevation model: a raster of ground heights
grade the change of height of an edge divided by its length

9.16 Summary

Call Does
an.stats(view, area_m2=...) the numbers of OSMnx basic_stats, in two views
an.streets_per_node(view) the streets at each node
an.bearings(view) the compass bearing of each edge
an.orientation_entropy(view, weight=...) the entropy of the street directions
an.plot_orientation(view, title=...) the polar histogram of the bearings
an.components(view, strong=...) the connected component of each node
an.largest_component(view, out=...) a new file with the largest component
an.nearest_nodes(view, x, y), an.nearest_edges(view, x, y) the nearest node and edge of each point
an.clip(net, point=..., dist_m=...) a new file with the edges inside an area
an.sample_points(view, n, seed=...) random points on the streets
an.add_elevation(net, dem=...), an.grades(view) the heights, and the grade of each edge
an.to_osmnx(view) the network as an OSMnx graph

The reference: duckosm.analysis. Next: 10. OSM data for GIS, OSM features, OSM XML and administrative areas.