Street Tessellation#

In this notebook we show how the street tesselation is working and some of the process how we got there. See Implementation for a usage example and the function stubs. How the population is distributed is explained in the next notebook Street Population Density.

Hide code cell source

import geopandas as gpd
import matplotlib.pyplot as plt
import osmnx as ox
import shapely as shp

import superblockify as sb
from superblockify.config import logger, Config
2026-11-24 13:24:51,012 |     INFO | __init__.py:11 | superblockify version 1.0.3

First we will get a partitioned city, namely Scheveningen. We can do this easily with a superblockify partitioner.

Hide code cell source

CITY_NAME, SEARCH_STR = Config.PLACES_SMALL[2]
logger.info(
    "Running partitioner for %s with search string %s.", CITY_NAME, SEARCH_STR
)
part = sb.ResidentialPartitioner(
    name=CITY_NAME + "_main", city_name=CITY_NAME, search_str=SEARCH_STR
)
part.run(calculate_metrics=False, make_plots=True)

Hide code cell output

2026-11-24 13:24:51,017 |     INFO | 351138818.py:2 | Running partitioner for Scheveningen with search string Scheveningen, The Hague, Netherlands.
---------------------------------------------------------------------------
ConnectionRefusedError                    Traceback (most recent call last)
File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connection.py:239, in HTTPConnection._new_conn(self)
    238 try:
--> 239     sock = connection.create_connection(
    240         (self._dns_host, self.port),
    241         self.timeout,
    242         source_address=self.source_address,
    243         socket_options=self.socket_options,
    244     )
    245 except socket.gaierror as e:

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/util/connection.py:85, in create_connection(address, timeout, source_address, socket_options)
     84 try:
---> 85     raise err
     86 finally:
     87     # Break explicitly a reference cycle

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/util/connection.py:73, in create_connection(address, timeout, source_address, socket_options)
     72     sock.bind(source_address)
---> 73 sock.connect(sa)
     74 # Break explicitly a reference cycle

ConnectionRefusedError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

NewConnectionError                        Traceback (most recent call last)
File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connectionpool.py:793, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
    792 # Make the request on the HTTPConnection object
--> 793 response = self._make_request(
    794     conn,
    795     method,
    796     url,
    797     timeout=timeout_obj,
    798     body=body,
    799     headers=headers,
    800     chunked=chunked,
    801     retries=retries,
    802     response_conn=response_conn,
    803     preload_content=preload_content,
    804     decode_content=decode_content,
    805     **response_kw,
    806 )
    808 # Everything went great!

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connectionpool.py:494, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
    493         new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
--> 494     raise new_e
    496 # conn.request() calls http.client.*.request, not the method in
    497 # urllib3.request. It also calls makefile (recv) on the socket.

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connectionpool.py:470, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
    469 try:
--> 470     self._validate_conn(conn)
    471 except (SocketTimeout, BaseSSLError) as e:

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connectionpool.py:1125, in HTTPSConnectionPool._validate_conn(self, conn)
   1124 if conn.is_closed:
-> 1125     conn.connect()
   1127 # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connection.py:827, in HTTPSConnection.connect(self)
    826 sock: socket.socket | ssl.SSLSocket
--> 827 self.sock = sock = self._new_conn()
    828 server_hostname: str = self.host

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connection.py:254, in HTTPConnection._new_conn(self)
    253 except OSError as e:
--> 254     raise NewConnectionError(
    255         self, f"Failed to establish a new connection: {e}"
    256     ) from e
    258 sys.audit("http.client.connect", self, self.host, self.port)

NewConnectionError: HTTPSConnection(host='overpass-api.de', port=443): Failed to establish a new connection: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

MaxRetryError                             Traceback (most recent call last)
File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/adapters.py:696, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    695 try:
--> 696     resp = conn.urlopen(
    697         method=request.method,
    698         url=url,
    699         body=request.body,  # type: ignore[arg-type]  # urllib3 stubs don't accept Iterable[bytes | str]
    700         headers=request.headers,  # type: ignore[arg-type]  # urllib3#3072
    701         redirect=False,
    702         assert_same_host=False,
    703         preload_content=False,
    704         decode_content=False,
    705         retries=self.max_retries,
    706         timeout=resolved_timeout,
    707         chunked=chunked,
    708     )
    710 except (ProtocolError, OSError) as err:

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/connectionpool.py:847, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
    845     new_e = ProtocolError("Connection aborted.", new_e)
--> 847 retries = retries.increment(
    848     method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
    849 )
    850 retries.sleep()

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/urllib3/util/retry.py:555, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
    554     reason = error or ResponseError(cause)
--> 555     raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
    557 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)

MaxRetryError: HTTPSConnectionPool(host='overpass-api.de', port=443): Max retries exceeded with url: /api/interpreter (Caused by NewConnectionError("HTTPSConnection(host='overpass-api.de', port=443): Failed to establish a new connection: [Errno 111] Connection refused"))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
Cell In[3], line 5
      1 CITY_NAME, SEARCH_STR = Config.PLACES_SMALL[2]
      2 logger.info(
      3     "Running partitioner for %s with search string %s.", CITY_NAME, SEARCH_STR
      4 )
----> 5 part = sb.ResidentialPartitioner(
      6     name=CITY_NAME + "_main", city_name=CITY_NAME, search_str=SEARCH_STR
      7 )
      8 part.run(calculate_metrics=False, make_plots=True)

File ~/work/superblockify/superblockify/superblockify/partitioning/base.py:155, in BasePartitioner.__init__(self, name, city_name, search_str, unit, graph, reload_graph, max_nodes)
    153     self.graph = self.load_or_find_graph(city_name, search_str, reload_graph)
    154 elif search_str is not None:
--> 155     self.graph = self.load_or_find_graph(city_name, search_str)
    156 elif graph is not None:
    157     self.graph = graph

File ~/work/superblockify/superblockify/superblockify/partitioning/base.py:808, in BasePartitioner.load_or_find_graph(self, city_name, search_str, reload_graph)
    806 else:
    807     logger.debug("Finding graph with search string %s", search_str)
--> 808     graph = load_graph_from_place(
    809         save_as=graph_path,
    810         search_string=search_str,
    811         add_population=True,
    812         custom_filter=Config.NETWORK_FILTER,
    813         simplify=True,
    814     )
    815     logger.debug("Saving graph to %s", graph_path)
    816     ox.save_graphml(graph, graph_path)

File ~/work/superblockify/superblockify/superblockify/utils.py:234, in load_graph_from_place(save_as, search_string, add_population, only_cache, max_nodes, **gfp_kwargs)
    232 ox.settings.cache_only_mode = only_cache
    233 try:
--> 234     graph = ox.graph_from_polygon(mult_polygon.geometry.union_all(), **gfp_kwargs)
    235 except CacheOnlyInterruptError:  # pragma: no cover
    236     logger.debug("Only loaded graph from cache")

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/osmnx/graph.py:497, in graph_from_polygon(polygon, network_type, simplify, retain_all, truncate_by_edge, custom_filter)
    495 # create buffered graph from the downloaded data
    496 bidirectional = network_type in settings.bidirectional_network_types
--> 497 G_buff = _create_graph(response_jsons, bidirectional)
    499 # truncate buffered graph to the buffered polygon and retain_all for
    500 # now. needed because overpass returns entire ways that also include
    501 # nodes outside the poly if the way (that is, a way with a single OSM
    502 # ID) has a node inside the poly at some point.
    503 G_buff = truncate.truncate_graph_polygon(G_buff, poly_buff, truncate_by_edge=truncate_by_edge)

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/osmnx/graph.py:678, in _create_graph(response_jsons, bidirectional)
    674 # consume response_jsons generator to download data from server. if
    675 # cache_only_mode, just consume response_jsons then continue next loop.
    676 # otherwise, extract nodes and paths from the downloaded OSM data.
    677 response_count = 0
--> 678 for response_json in response_jsons:
    679     response_count += 1
    680     if not settings.cache_only_mode:

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/osmnx/_overpass.py:443, in _download_overpass_network(polygon, network_type, custom_filter)
    441 for way_filter in way_filters:
    442     query_str = f"{overpass_settings};(way{way_filter}(poly:{polygon_coord_str!r});>;);out;"
--> 443     yield _overpass_request(OrderedDict(data=query_str))

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/osmnx/_overpass.py:510, in _overpass_request(data)
    508 msg = f"Post {prepared_url} with timeout={settings.requests_timeout}"
    509 utils.log(msg, level=lg.INFO)
--> 510 response = requests.post(
    511     url,
    512     data=data,
    513     timeout=settings.requests_timeout,
    514     headers=_http._get_http_headers(),
    515     **settings.requests_kwargs,
    516 )
    518 # handle 429, 502, and 504 errors by pausing then recursively re-trying request
    519 if response.status_code in {429, 502, 504}:  # pragma: no cover

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/api.py:134, in post(url, data, json, **kwargs)
    117 def post(
    118     url: _t.UriType,
    119     data: _t.DataType = None,
    120     json: _t.JsonType = None,
    121     **kwargs: Unpack[_t.PostKwargs],
    122 ) -> Response:
    123     r"""Sends a POST request.
    124 
    125     :param url: URL for the new :class:`Request` object.
   (...)    131     :rtype: requests.Response
    132     """
--> 134     return request("post", url, data=data, json=json, **kwargs)

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/api.py:71, in request(method, url, **kwargs)
     67 # By using the 'with' statement we are sure the session is closed, thus we
     68 # avoid leaving sockets open which can trigger a ResourceWarning in some
     69 # cases, and look like a memory leak in others.
     70 with sessions.Session() as session:
---> 71     return session.request(method=method, url=url, **kwargs)

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/sessions.py:651, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    646 send_kwargs = {
    647     "timeout": timeout,
    648     "allow_redirects": allow_redirects,
    649 }
    650 send_kwargs.update(settings)
--> 651 resp = self.send(prep, **send_kwargs)
    653 return resp

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/sessions.py:784, in Session.send(self, request, **kwargs)
    781 start = preferred_clock()
    783 # Send the request
--> 784 r = adapter.send(request, **kwargs)
    786 # Total elapsed time of the request (approximately)
    787 elapsed = preferred_clock() - start

File ~/micromamba/envs/sb_env/lib/python3.12/site-packages/requests/adapters.py:729, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    725     if isinstance(e.reason, _SSLError):
    726         # This branch is for urllib3 v1.22 and later.
    727         raise SSLError(e, request=request)
--> 729     raise ConnectionError(e, request=request)
    731 except ClosedPoolError as e:
    732     raise ConnectionError(e, request=request)

ConnectionError: HTTPSConnectionPool(host='overpass-api.de', port=443): Max retries exceeded with url: /api/interpreter (Caused by NewConnectionError("HTTPSConnection(host='overpass-api.de', port=443): Failed to establish a new connection: [Errno 111] Connection refused"))

The partitioner has been run and for each Superblock it produces a partition, inclusing a subgraph object, which includes the nodes and edges of the Superblock. One of them looks like this:

subgraph = part.partitions[6]["subgraph"]
subgraph_edges = ox.graph_to_gdfs(subgraph, nodes=False, edges=True)
subgraph_edges.explore(style_kwds={"weight": 4})

As edges are represented by linestrings, the area is not clearly defined. The first idea that might come to one’s mind is the convex hull of the linestrings.

# From subgraph_edges we want to get a hull that encloses all edges
convex_hull = subgraph_edges.union_all().convex_hull
# Make gdf from convex hull with the same crs as the subgraph
convex_hull_gdf = gpd.GeoDataFrame(
    geometry=[convex_hull], crs=subgraph_edges.crs
)
# plot both gdfs together
ax = subgraph_edges.plot()
convex_hull_gdf.plot(ax=ax, color="lightgray")
plt.axis("off")
plt.show()

This approach is quick and easy, but it has some drawbacks. It might be larger than we are looking for. For example, a star shaped neighborhood would result in a hull spanning around all areas between the streets, even if it might include areas that belong to another Superblock. Also, it might be smaller than we are looking for. For example, a neighborhood that is linear, one long street with houses on both sides, would result in a hull that is just a line, which is not what we are looking for. The latter problem can be solved by buffering the edges before taking the convex hull. The former problem has multiple solutions summarized under the term concave hull. shapely provides the function concave_hull for this purpose. It takes a ratio parameter, which determines how concave the hull is. A ratio of 1 results in the convex hull, a ratio of 0 results in only a line between the nearest points in the geometry.

Hide code cell source

from numpy import linspace

def plot_concave_hull(ax, subgraph_edges, ratio=0.4, allow_holes=False,
                      color="crimson"):
    concave_hull = shp.concave_hull(
        subgraph_edges.union_all(),
        ratio=ratio,
        allow_holes=allow_holes,
    )
    # Make gdf from convex hull with the same crs as the subgraph
    convex_hull_gdf = gpd.GeoDataFrame(
        geometry=[concave_hull], crs=subgraph_edges.crs
    )
    # plot both gdfs together
    convex_hull_gdf.plot(ax=ax, color=color)

# Figure different ratios
fig = plt.figure(layout="constrained", figsize=(10, 8))
subfigs = fig.subfigures(2, 1, hspace=0.07, height_ratios=[2., 1.])
# Overlaying
axs0 = subfigs[0].subplots(1, 1)
for ratio in linspace(1, 1/10, 10):
    color = plt.cm.coolwarm(ratio)
    plot_concave_hull(axs0, subgraph_edges, ratio=ratio, color=color)
subgraph_edges.plot(ax=axs0, color="black", linewidth=3)
axs0.set_axis_off()
colorbar = plt.cm.ScalarMappable(cmap=plt.cm.coolwarm,
                           norm=plt.Normalize(vmin=1, vmax=0.1))
# vertically oriented colorbar with title Ratio of Alpha Shape
cbar = fig.colorbar(colorbar, ax=axs0, orientation="vertical", shrink=0.8)
cbar.set_label("Ratio of Alpha Shape", rotation=270, labelpad=20)
cbar.ax.get_yaxis().labelpad = 20

# Side by side
axs1 = subfigs[1].subplots(1, 7)
for i, ratio in enumerate(linspace(1, 1/10, 7)):
    color = plt.cm.coolwarm(ratio)
    plot_concave_hull(axs1[i], subgraph_edges, ratio=ratio, color=color)
    subgraph_edges.plot(ax=axs1[i], color="black", linewidth=3)
    axs1[i].set_axis_off()

plt.show()

The function works with the points in the linestrings, so it is highly dependent on the point density. The ratio determines the maximum edge length, rescaled between the greatest and smallest distance between al pairs of points. This results in the fact, that a shape with lower ratio is not necessarily fully included in a shape with a higher ratio, see the two lowest ratios on the bottom right. This solution still does not satisfy us.

Optimally all Superblock cells would not overlap each other and form a tiling, also called tesselation, of the city.

Morphological Tessellation#

There is a solution satisfying our requirements. Okabe and Sugihara define the line Network Voronoi Diagram (line N-VD) [Equation 4.7]. It is basically a Voronoi diagram (also called Thiessen polygons in some fields) where lines are made up of multiple points[1]. Araldi and Fusco use this idea to do geostatistical analysis[2]. Fleischmann et al. implement the same idea in the momepy package for building footprints [3]. With list of footprint geometries, the Tessellation class returns a GeoDataFrame with a cell corresponding to each input geometry that was given.

momepy tessellation

In our case the input geometries can be the smaller neighborhood boundaries, and the tesselation fills up the gaps. For the Superblocks we will use an union of the edges of the subgraphs and buffer them a small bit. As we do not want the polygons to overlap wich each other, we’ll buffer using a flat cap style.

 def border_from_subgraph_shrinked(subgraph, buffer=1):
    """Shrinked subgraph borders, to avoid overlap between partitions.
    Does work well with small buffer values."""
    edges = ox.graph_to_gdfs(subgraph, nodes=False, edges=True)
    # First buffer with flat cap style to avoid self-intersections
    polygon = shp.Polygon(edges.union_all().buffer(2 * buffer, cap_style='flat')
                          .exterior)
    # Simplify the polygon to remove small artifacts of flat cap style at curved edges
    # polygon = polygon.simplify(buffer*2, preserve_topology=True)
    # geos::simplify::PolygonHullSimplifier would do the job. No bindings yet.
    # https://libgeos.org/doxygen/classgeos_1_1simplify_1_1PolygonHullSimplifier.html
    # http://lin-ear-th-inking.blogspot.com/2022/04/outer-and-inner-concave-polygon-hulls.html
    # http://lin-ear-th-inking.blogspot.com/2022/05/using-outer-hulls-for-smoothing.html
    # Secondly, erode the polygon to avoid overlap between partitions
    return polygon.buffer(-buffer, cap_style='round')

border_from_subgraph_shrinked(part.partitions[6]["subgraph"], buffer=1)

We would like to simplify the polygon before buffering down, but as we use a flat cap style, the line connection have small artifacts when choosing larger buffers. The Ramer–Douglas–Peucker algorithm does not suffice our needs, because the result can split the polygon up and does not inherently enclose the original polygon. The geos::simplify::PolygonHullSimplifier would do the job, but it got added in GEOS 3.11, and no python package has any bindings, yet.

Now, when using the momepy.Tessellation class, we get:

from momepy import Tessellation

borders = gpd.GeoDataFrame(
    geometry=[border_from_subgraph_shrinked(p["subgraph"], buffer=1) for p in part
    .partitions],
    crs=part.partitions[0]["subgraph"].graph["crs"],
    data=[p["name"] for p in part.partitions],
    columns=["partition_id"]
)
# Morphological tessellation around given buildings ``gdf`` within set ``limit``.
tessellation = Tessellation(borders, unique_id="partition_id",
                               limit=part.graph.graph["boundary"],
                               shrink=0.0)
# Plot on our map
tessellation_gdf = tessellation.tessellation
fig, axe = plt.subplots(figsize=(10, 10))
tessellation_gdf.plot(ax=axe, edgecolor="white", column="partition_id", legend=True,
                      cmap="tab20")
borders.plot(ax=axe, color="white", alpha=0.5, facecolor="white")
ox.plot_graph(part.sparsified, ax=axe, node_size=0, edge_color="black",
              edge_linewidth=1)
axe.set_axis_off()
plt.show()

This is much more what we want. Another way to make it even better it so take the sparsified network at cell borders, but at the same time, the sparsified network should also have a volume as there might be people living on it. Finally, we will implement our own method, inspired by this technique, a solution sewed to our needs.

Independent Tessellation#

When looking into the code, momepy uses scipy.spatial.Voronoi to generate the tessellation for every enclosure. This is done with a dense point array for the geometry boundaries (borders in our case).

As we want to calculate area and population for each Partition, we can save time by calculating the Voronoi diagram once for the whole graph/city, and save area and population for each edge. Later we can use this data to calculate the area and population for each Partition.

Hide code cell source

import pandas as pd
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d

Now, we will create Voronoi cells for each edge, so we can later dissolve them to Superblock cells. As we are working in a MultiDiGraph two way streets are represented by two directed edges with the same geometry, both should share the same cell, so grouping the edges is a crucial part. First we will group the edges connecting the same nodes u and v and then we will merge the edges with the same or reverse geometry.

edges = ox.graph_to_gdfs(part.graph,
                         nodes=False,
                         edges=True,
                         node_geometry=False,
                         fill_edge_geometry=True)
# `edges` is a pandas dataframe with the multiindex (u, v, key)
# Merge two columns, when the geometry of one is equal or the reverse of the other
# 1. Group if u==u and v==v or u==v and v==u (match for hashed index (u, v) where u<v)
# get flat index of the first match
edges["edge_id"] = edges.index.to_flat_index()
# sort the edge_id tuples
edges["node_pair"] = edges["edge_id"].apply(lambda x: tuple(sorted(x[:2])))
# 2. Aggregate if the geometry is equal or the reverse of the other
# Merge columns if geometry_1 == geometry_2 or geometry_1 == geometry_2.reverse()
# reverse geometry if x_start >= x_end
edges["geometry"] = edges["geometry"].apply(
    lambda x: x if x.coords[0] < x.coords[-1] else x.reverse())
# 3. Group by node_pair and geometry
edges = edges.groupby(["node_pair", "geometry"]).agg({
    "edge_id": tuple,
    "component_name": "first",
}).reset_index()
edges.set_index("edge_id", inplace=True)

edges = gpd.GeoDataFrame(edges, geometry="geometry", crs=part.graph.graph["crs"])
edges.explore()

For each geometry we will interpolate the lines into points of equal distance of 10m.

# get multiindex of first row
distance = 10
# The maximum distance between points after discretization.
edge_points = []
edge_indices = []
# iterate over street_id, geometry
for idx, geometry in edges["geometry"].items():
    if geometry.length < 2 * distance:
        # for edges that would result in no point, take the middle
        pts = [shp.line_interpolate_point(geometry, 0.5, normalized=True)]
    else:
        # interpolate points along the line with at least distance between them
        # start and end 0.1 from the ends to avoid edge effects
        pts = shp.line_interpolate_point(
                geometry,
                np.linspace(
                    0.1,
                    geometry.length - 0.1,
                    num=int((geometry.length - 0.1) // distance),
                ),
            )  # offset to keep nodes out
    edge_points.append(shp.get_coordinates(pts))
    # Append multiindices for this geometry
    edge_indices += [idx] * len(pts)

points = np.vstack(edge_points)

Now we know for each point, which edge it belongs to. We can use this to calculate the Voronoi diagram.

Before we continue, let’s also introduce a hull around the points, so that the outer edge cells are not infinite or too large. As a hull we can use the boundary polygon of the graph from OSM, as used in the node approach, or a buffered union of the edge geometries. Then we can also split up the hull into points and add them to the points array.

hull = shp.Polygon(edges.union_all().buffer(100).exterior)
# interpolate points along the hull - double the distance
hull_points = shp.line_interpolate_point(
    hull.boundary,
    np.linspace(0.1, hull.length - 0.1, num=int(hull.length // (2 * distance))),
)
# add hull points to the points array
points = np.vstack([points, shp.get_coordinates(hull_points)])
# add edge indices to the edge_indices array
edge_indices += [-1] * len(hull_points)

For the points array we can now calculate the Voronoi diagram.

edge_voronoi_diagram = Voronoi(points)

Hide code cell source

from matplotlib.patches import Rectangle, ConnectionPatch

# Plot with inset axes
fig, axe = plt.subplots(figsize=(10, 10))
zoom_window = (587000, 587500, 5772000, 5772500)

edges.plot(ax=axe, color="black", linewidth=0.5)
voronoi_plot_2d(edge_voronoi_diagram, ax=axe, show_vertices=False, line_colors='orange',
                line_width=1, line_alpha=0.6, point_size=2)
axe.set_title("Voronoi diagram of dense edge points")
# Create inset axes
axins = axe.inset_axes([0.6, 0.01, 0.45, 0.45])
edges.plot(ax=axins, color="black", linewidth=2)
voronoi_plot_2d(edge_voronoi_diagram, ax=axins, show_vertices=False,
                line_colors='orange',
                line_width=2, line_alpha=0.6, point_size=4)
axins.set_xlim(*zoom_window[:2])
axins.set_ylim(*zoom_window[2:])
axins.set_xticks([])
axins.set_yticks([])
# Indicate zoom window
rect = Rectangle((zoom_window[0], zoom_window[2]), zoom_window[1] - zoom_window[0],
                 zoom_window[3] - zoom_window[2], linewidth=1, edgecolor='r',
                 facecolor='none', zorder=10)
axe.add_patch(rect)
# Connect zoom window to inset
axe.add_artist(
    ConnectionPatch(xyA=(zoom_window[0], zoom_window[2]),
                    xyB=(zoom_window[0], zoom_window[2]),
                    coordsA="data", coordsB="data", axesA=axe, axesB=axins,
                    linewidth=1, zorder=10))
axe.add_artist(
    ConnectionPatch(xyA=(zoom_window[1], zoom_window[3]),
                    xyB=(zoom_window[1], zoom_window[3]),
                    coordsA="data", coordsB="data", axesA=axe, axesB=axins,
                    linewidth=1, zorder=10))
plt.show()

Let’s see how the cells look like for the Partitioner part.

# Construct cell polygons for each of the dense points
point_vertices = pd.Series(edge_voronoi_diagram.regions).take(
    edge_voronoi_diagram.point_region)
point_polygons = []
for region in point_vertices:
    if -1 not in region:
        point_polygons.append(
            shp.polygons(edge_voronoi_diagram.vertices[region]))
    else:
        point_polygons.append(None)

# Create GeoDataFrame with cells and index
edge_poly_gdf = gpd.GeoDataFrame(
    geometry=point_polygons,
    index=edge_indices,
    crs=part.graph.graph["boundary_crs"],
)
# Drop cells that are outside the boundary
edge_poly_gdf = edge_poly_gdf.loc[edge_poly_gdf.index != -1]
# Dissolve cells by index
edge_poly_gdf = edge_poly_gdf.dissolve(by=edge_poly_gdf.index)
# delete index_str
edge_poly_gdf

The GeoDataFrame now includes the cell geometries for each edge tuple.

edge_poly_gdf["component_name"] = edges.loc[edge_poly_gdf.index, "component_name"]
# Set NaNs to "sparse"
edge_poly_gdf["component_name"] = edge_poly_gdf["component_name"].fillna("sparse")
# Plot with color by edge label
fig, axe = plt.subplots(figsize=(10, 10))
edge_poly_gdf.plot(column="component_name", ax=axe, legend=True, cmap="tab20")
ox.plot_graph(part.graph, ax=axe, node_size=8, edge_color="black", edge_linewidth=0.5,
              node_color="black")

When dissolving the cells grouped by the component_name we get the wanted regions.

# Interactive explore map with unions of partitions
edge_poly_gdf.dissolve(by="component_name", as_index=False).explore(
    column="component_name", cmap="tab20")

Implementation#

We implemented a function that does this and more for us in one function call. add_edge_cells accepts a graph and adds a cell attribute with the cell geometry to every edge.

ky_graph = ox.graph_from_place("Kyiv, Ukraine", network_type="drive")
ky_graph = ox.project_graph(ky_graph)

For a graph as big as Kyiv, 7th largest European city as of 1st of January 2021, this takes about a minute. This graph has more than 23k edges, resulting in about 300k points for the Voronoi diagram (10m interpolation) ans 13k edge cells.

sb.add_edge_cells(ky_graph)

Hide code cell source

# Get polygons from edges and plot
edge_poly_gdf = gpd.GeoDataFrame(
    geometry=[data["cell"] for _, _, data in ky_graph.edges(data=True)],
    crs=ky_graph.graph["crs"],
    index=ky_graph.edges(),
    columns=["geometry"],
)
fig, axe = plt.subplots(figsize=(10, 10))
edge_poly_gdf.plot(ax=axe, color="orange", alpha=0.5, edgecolor="black", linewidth=0.5)
ox.plot_graph(ky_graph, ax=axe, node_size=0, edge_color="black", edge_linewidth=0.5,
              node_color="black")
superblockify.population.tessellation.add_edge_cells(graph, **tess_kwargs)[source]

Add edge tessellation cells to edge attributes in the graph.

Tessellates the graph into plane using a Voronoi cell approach. Function writes to edge attribute cells of the graph in-place. Furthermore, cell_id is added to the edge attributes, for easier summary of statistics later.

The approach was developed inspired by the momepy.Tessellation class and tessellates with scipy.spatial.Voronoi.

Parameters:
graphnetworkx.MultiDiGraph

The graph to tessellate.

**tess_kwargs

Keyword arguments for the superblockify.population.tessellation.get_edge_cells() function.

Raises:
ValueError

If the graph is not in a projected coordinate system.

ValueError

If the limit and the edge points are disjoint.

Notes

The graph must be in a projected coordinate system.