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.
# 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.requestdef 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"))returnnext(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") isNone: # 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 SDKifnothasattr(duckosm, "network"): # an old duckOSM (0.8.0 or older), without the SDK%pip install -q --force-reinstall --no-deps "duckosm @ {nightly_wheel()}"raiseSystemExit("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.ifnot os.path.exists("monaco.duckdb") ornot 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=.
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
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 annet = 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
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.boundaryutm = 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 pdcounts = 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.
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.
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=.
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")
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 nprng = np.random.default_rng(1)west, south, east, north = edges.total_boundsxs = rng.uniform(west, east, 10)ys = rng.uniform(south, north, 10)
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.
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.
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%}")
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 oxG = an.to_osmnx(big.driving)print(G)
MultiDiGraph named 'monaco_largest' with 1600 nodes and 2622 edges
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"] =Falsetheirs = 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:
Give cityseer the walking network as lines in metres, one line for each street.
cityseer makes its own graph and its network structure (io.nx_from_generic_geopandas, io.network_structure_from_nx).
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.
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, Normalizejunctions["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 boundary of the area (net.boundary) less the water
momepy makes the blocks in three steps:
Enclosures: it cuts the land along the streets. Each enclosure is an area with streets around it.
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.
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.
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).
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.
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.
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.
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.
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 ioimport geopandas as gpdimport mapclassifyfrom IPython.display import SVGfrom matplotlib.colors import ListedColormapfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patchsix = 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 isnotNone: 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
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:
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.
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).
Take the outline of the street space: the two edges of each street.
Take the street space out of the extra areas (the parks and the sea), so that they do not fill the streets.
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.
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.
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.