Usage#

The superblockify package works out of the box, meaning no further downloads are necessary. Maps are downloaded from the OpenStreetMap API and population data is downloaded from the GHSL-POP 2023 dataset. Only those map tiles that are needed are cached in the data/ghsl folder.

The following example uses superblockify to partition the street network of Scheveningen, a district of The Hague, using the ResidentialPartitioner class. After partitioning, the results will be saved to a GeoPackage file (.gpkg) that can be opened and edited with a GIS software like QGIS.

Import#

First, import the package. By convention, superblockify is shortened as sb:

import superblockify as sb
2026-11-24 13:27:14,666 |     INFO | __init__.py:11 | superblockify version 1.0.3

Configuration#

There are several options to configure superblockify, see the API Reference.

Common ones are, for example, to log at the “debug” level:

sb.config.set_log_level("DEBUG")

If you already have the GHSL raster file, you can skip its download. In this case, if you already have the file GHS_POP_E2025_GLOBE_R2023A_54009_100_V1_0.tif inside the data/ghsl folder, you could set the FULL_RASTER parameter to NONE:

sb.config.Config.FULL_RASTER = None

Initialization#

For this example we will use the ResidentialPartitioner class. It is a class that partitions a city into superblocks based on the residential street tags in OpenStreetMap. First, initialize the partitioner with the city name and a search string.

part = sb.ResidentialPartitioner(
    name="Scheveningen_test",
    city_name="Scheveningen",
    search_str="Scheveningen, NL",
    unit="time",  # "time", "distance", any other edge attribute, or None to count edges
)
---------------------------------------------------------------------------
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[4], line 1
----> 1 part = sb.ResidentialPartitioner(
      2     name="Scheveningen_test",
      3     city_name="Scheveningen",
      4     search_str="Scheveningen, NL",

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"))

This will download the map of Scheveningen, preprocess it, output some statistics and store it in the data/graphs folder for later use. Any other partitioner for Scheveningen, given the same city_name, will use the same preprocessed, locally stored map. Population tiles are cached in the data/ghsl folder (if not using the full raster).

If you want to select a different city, find the corresponding search string (search_str) at https://nominatim.openstreetmap.org/. The smaller the place, the quicker the partitioning. For large places sufficient memory is required.

Partitioning#

Next, we will show the quickest way to partition the city and calculate the metrics all in one go.

part.run(
    calculate_metrics=True,  # set to False if you are not interested in metrics
    make_plots=True,  # set to False if you are not interested in plots
    replace_max_speeds=False,  # set to true to overwrite the OSM speed limits
    # -> with 15 km/h inside Superblocks and 50 km/h outside
    # If the approach has specific parameters, you can set them here
)
Street network of Scheveningen

Simple street network of Scheveningen.#

First, you want to see the street network of the city you are working with. This should look like the street network of the place you want to analyze, if it does not, check the search_str or the OSM relation ID. Some streets at the outer edges might be cut off, this is due to the requirement that the street network needs to be strongly connected, in other words, you should be able to reach every street from every other street. For in- and outgoing highways, this might not be the case, so they are cut off. Furthermore, the network filter decides which streets are included in the start.

Component rank size plot for street length of Superblocks

Superblock street length rank size plot.#

Generally, a rank-size plot shows the distribution of a quantity in descending order. In this case, the street length of the generated Superblocks is shown on a logaritmic scale. If you are more interested in the tesselated Superblock areas, instead of the street length, you can find this information in the geopackage file saved later.

Superblocks of Scheveningen

Generated Superblocks for Scheveningen. Each Superblock is colored differently with one representative point for visual aid.#

A central feature of this package is the distance calculation between every point on the map before \(d_S(i,j)\) and after introducing the Superblocks \(d_N(i,j)\). This is done to evaluate the generated Superblock configuration. The way the distance calculation works is explained in the Restricted Distance Calculation section. The restriction imposed by the Superblocks is that after implementing them, one is not allowed to travel through a Superblock that does not contain the starting or ending point. Another visualization of this restriction is shown on the Betweenness Centrality explainer page.

Relative increase of the distance metric on the graph

Relative increase of the distance metric on the graph.#

The fraction of the two distances \(d_N(i,j)/d_S(i,j)\) is shown on the street network. If this is close to \(1\), the Superblocks do not restrict the travel distance much. A value of \(1.1\) means that the travel distance is increased by \(10\%\). As we specified the unit as “time” in the initialization (unit="time"), the distance metric is in minutes and one can talk about a \(10\%\) increase in travel time.

Component-wise travel increase

Travel increase for each Superblock.#

Finally, the travel increase is shown as arithmetic mean for each Superblock.

All shown plots are saved as pdf to the data/results/Scheveningen_test folder. Here, is possible to save and load a partitioner object to continue the work later.

part.save()
part.load("Scheveningen_test")

The most illustrative and interactive way to view the results is to save them to a geopackage file. This file can be opened in QGIS and edited further.

sb.save_to_gpkg(part, save_path=None)

This will save the partitioning results to data/results/Scheveningen_test/{city_name}.gpkg. If you calculated the metrics before, they will be available in the layers, for each Superblock. This includes more metrics than shown in the plots earlier. The name of the components is saved into a classification edge attribute. The sparse graph is saved with the value “SPARSE” into the classification edge attribute.

To learn more about the inner workings and background of the package, please see the next Reference section. Otherwise, you can also check out the API documentation.

FAQ#

Can I export the plots to another format?#

Yes, you can export the plots to any format supported by matplotlib. Just change the PLOT_SUFFIX attribute in the Config class to the desired format.

sb.config.Config.PLOT_SUFFIX = "png"  # or "svg", "pdf", etc.

The downloaded city is too big/small/not the right city, can I change this?#

The deciding string for the area to download is the search_str. Finding a fitting OSM area is via the Nominatim API. If you want to see your area before downloading, use the Nominatim Search. It helps to be more specific, e.g. “Scheveningen, The Hague, Netherlands” instead of just “Scheveningen”. Otherwise, OSM relations IDs, e.g. R13751467, can be used.

To re-download the map, pass reload_graph=True when initializing the partitioner.

part = sb.ResidentialPartitioner(
    name="Scheveningen_test",
    ...,
    reload_graph=True,
)

The Superblocks look too big/small/random when using the ResidentialPartitioner, why is that?#

The ResidentialPartitioner uses the residential street tags to find the Superblocks. The variation in OSM data quality and street tagging practices can be reflected when using this approach. The BetweennessPartitioner instead does not rely on OSM tags but uses the betweenness centrality - a topological property of the street network. Try this approach if the Superblocks from the ResidentialPartitioner are not satisfactory .

superblockify.partitioning.approaches.betweenness.BetweennessPartitioner(name='unnamed', city_name=None, search_str=None, unit='time', graph=None, reload_graph=False, max_nodes=20000)[source]

Partitioner using betweenness centrality of nodes and edges.

Set sparsified graph from edges or nodes with high betweenness centrality.

superblockify.partitioning.approaches.betweenness.BetweennessPartitioner.write_attribute()

Determine edges with high betweenness centrality for sparsified graph.

Edges with high betweenness centrality are used to construct the sparsified graph.

The high percentile is determined through ranking all edges by their betweenness centrality and taking the top percentile. The percentile is determined by the percentile parameter.

Parameters:
percentilefloat, optional

The percentile to use for determining the high betweenness centrality edges, by default 90.0

scalingstr, optional

The type of betweenness to use, can be normal, length, or linear, by default normal

max_rangeint, optional

The range to use for calculating the betweenness centrality, by default None, which uses the whole graph. Its unit is meters.

**kwargs

Additional keyword arguments. calculate_metrics_before takes the make_plots parameter.

Raises:
ValueError

If scaling is not normal, length, or linear.

ValueError

If percentile is not between, 0.0 and 100.0.

Pass the kwargs from the write_attribute() method (as seen above or in the API documentation) to the BetweennessPartitioner.run(...) method to set the parameters for the partitioning. After initializing a BetweennessPartitioner, part = BetweennessPartitioner(...), run the partitioning with the optional parameters, e.g. part.run(percentile=85.0, scaling="normal", max_range=None).

My country has another maximum speed limit, can I change this?#

When calculating the metrics and using replace_max_speeds=True, the maximum speed limits are set to 15 km/h inside the Superblocks and 50 km/h outside of them. If you want to change these values, you can do so by setting the V_MAX_LTN and V_MAX_SPARSE attributes in the Config class.

sb.config.Config.V_MAX_LTN = 30  # km/h
sb.config.Config.V_MAX_SPARSE = 60  # km/h

Some streets I know are not being used in the partitioning, why is that?#

When downloading the map from OpenStreetMap, we use a specific network filter, which should include the car network.

sb.config.Config.NETWORK_FILTER

If you want to include more streets, you can change the network filter to include more or less streets. When changing the network filter, you might want to remove the cached graphs, or set reload_graph=True when initializing the partitioner.

Some process is taking too long or suddenly stops, what can I do?#

If there are warnings or logs that indicate a problem, they might point to the issue. Be aware that, when analyzing a large city, superblockify needs sufficient resources. If it runs out of memory, some processes might stop abruptly without warning. To combat this, you can either try to find a search_str with a smaller area or set the MAX_NODES attribute in the Config class to a lower value. When initializing a partitioner, the street network is cut off at this number of nodes, including the most central nodes. By default, this is set to 20,000.

For further settings, see the other attributes in the Config class.

superblockify.config.Config()[source]

Configuration class for superblockify.

Attributes:
WORK_DIR

The working directory of the package. This is used to store the graphs and results in subdirectories of this directory. By default, this is the current working directory when the package is imported. This is only used to define the following directories.

GRAPH_DIR

The directory where the graphs are stored.

RESULTS_DIR

The directory where the results are stored.

GHSL_DIR

The directory where the GHSL population data is stored when downloaded.

V_MAX_LTN

The maximum speed in km/h for the restricted calculation of travel times.

V_MAX_SPARSE

The maximum speed in km/h for the restricted calculation of travel times for the sparsified graph.

NETWORK_FILTER

The filter used to filter the OSM data for the graph. This is a string that is passed to the osmnx.graph_from_place() function.

CLUSTERING_PERCENTILE

The percentile used to determine the betweenness centrality threshold for the spatial clustering and anisotropy nodes.

NUM_BINS

The number of bins used for the histograms in the entropy calculation.

FULL_RASTER

The path and filename of the full GHSL raster. If None, tiles of the needed area are downloaded from the JRC FTP server and stored in the GHSL_DIR directory. <https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/GHSL/GHS_POP_GLOBE_R2023A/GHS_POP_E2025_GLOBE_R2023A_54009_100/V1-0/GHS_POP_E2025_GLOBE_R2023A_54009_100_V1_0.zip>

DOWNLOAD_TIMEOUT

The timeout in seconds for downloading the GHSL raster tiles.

logger

The logger for this module. This is used to log information, warnings and errors throughout the package.

TEST_DATA_PATH

The path to the test data directory.

HIDE_PLOTS

Whether to hide the plots in the tests.

PLACES_GENERAL

A list of tuples of the form (name, place) where name is the name of the place and place is the place string that is passed to the superblockify.utils.load_graph_from_place() function.

PLACES_SMALL

Same as PLACES_GENERAL but for places of which the graph is small enough to be used in the tests.

PLACES_100_CITIES

100 cities from Boeing et al. (2019) <https://doi.org/10.1007/s41109-019-0189-1> A dictionary of the form {name: place} where name is the name of the place, and place is a dictionary of various attributes. One of them is the query attribute which is the place string or a list of place strings. Find the extensive list in the ./cities.yml file.

PLACES_GERMANY

List of cities in Germany by population. All cities with more than 100,000 inhabitants are included. Data from the German Federal Statistical Office.

PLOT_SUFFIX

The format of the plots. Can be "png", "jpg", "pdf", "svg", etc. Matplotlib uses the Pillow library to save the plots, so all formats supported by Pillow are supported by Matplotlib. <https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html>

MAX_NODES

The maximum number of nodes in the graph. If the graph has more nodes, it is reduced. See superblockify.partitioning.utils.reduce_graph().

If you run into any other issues, feel free to look into the API documentation, Source Code, activate debug logs sb.config.set_log_level("DEBUG") or finally open a new issue.