Developer reference

This is the complete developer reference for the LinkBikeNet package. If you are looking for an introduction to LinkBikeNet, read the Getting started guide.

linkbikenet.linkbikenet

linkbikenet.linkbikenet.linkbikenet(city_query, connection_strategy='largest_to_closest', export_data=True, city_id=None, export_file_format='geojson', import_files={})[source]

Create links between components of bicycle networks in cities. How components are connected depends on the chosen connection strategy.

Parameters:
city_querystr

Search string for the city that the analysis should be performed on. This is the query used to fetch the data from nominatim.

connection_strategystr, default=”largest

Strategy to use for connecting between components. Default is “largest_to_second”, other options are “largest_to_closest” and “closest_components”.

export_databool, optional, default True

If set to True, data will be saved to a file. The filename is [slug].gpkg, where slug is a string id made out of city_query.

city_idNone or str, default None

If set, the slugified city_id is used in the filename of the data export. For example, a city_id “Athens” will slugify into “athens” in filenames. If set to None, the slugified city_query is used in the filename of the data export. It is useful to set a city_id for cities where the city_query is not the city name, for example to set for a city_query “Municipality of Athens” the city_id to “Athens”.

export_file_formatstr, default “geojson”

File format for the data export, relevant if export_data set to True. Default “geojson”, also possible “gpkg”. If exporting as geojson, generates extra files for street network and city boundary. If exporting as gkpg, these are added all in one file as extra layers.

import_files: dict, default {}

The following key:value entries can be set:

  • ‘city_boundary’None or str, default None

    If not set to None, the study area is selected from the (Multi)Polygon provided in the city_boundary shape or gpkg file, ideally in unprojected latitude-longitude degrees (EPSG:4326), but EPSG:3857 also works.

  • ‘street_network’None or str, default None

    If not set to None, the street network is loaded from this file. Must be a gpkg file in unprojected crs EPSG:4326 with layers nodes and edges, with the structure that an undirected osmnx street network g has after saved via ox.io.save_graph_geopackage(). For example:

    >>> ox.settings.useful_tags_way = ["highway", "cycleway", "cycleway:right", "cycleway:left", "cycleway:both", "cyclestreet"]
    >>> g = ox.graph_from_place("Barcelona", network_type='all_public', simplify=False, retain_all=True)
    >>> g = nx.MultiGraph(ox.convert.to_digraph(g))
    >>> ox.io.save_graph_geopackage(g, "Barcelona_streets.gpkg")
    
  • ‘bike_network’None or str, default None

    If not set to None, the existing bike network is loaded from this file. Must be a gpkg file in unprojected crs EPSG:4326 with layers nodes and edges, with the structure that an undirected osmnx bike network has after saved via ox.io.save_graph_geopackage().

Returns:
linked_componentsgeopandas.GeoDataFrame

Geodataframe with the proposed links, ordered after strategy chosen.

linkbikenet.functions

Print footer.

linkbikenet.functions._print_header(city_query, connection_strategy)[source]

Print header.

linkbikenet.functions.calculate_network_statistics(H)[source]

Return total network length and largest component length.

Parameters:
H: networkx.Graph

undirected simple graph representing the street network with weighted edges

Returns:
total_length: float

total length of the network

largest_length: float

length of the largest connected component

linkbikenet.functions.create_gdf_with_geoms(df, edges)[source]
Parameters:
df: pandas.DataFrame

Dataframe with path nodes and path edges

edges: geopandas.GeoDataFrame

The street network, in a projected coordinate reference system

Returns:
gdf: geopandas.GeoDataFrame

projected GeoDataFrame with path nodes and path edges and merged geometries

linkbikenet.functions.find_edges_to_drop(g)[source]

find parallel edges that have different pbi values, list the ones with pbi=0

Parameters:
gnetworkx.MultiDiGraph

simplified graph representing the street network, with added binary edge attribute “pbi”

Returns:
edges_to_drop: list

unique list of edges to drop-> edges where pbi values differ and pbi value=0 gets dropped

linkbikenet.functions.get_correct_edgetuples(edge_gdf, nodelist)[source]

helper function that maps a node list (output of nx.shortest_paths) to the correct set of edge tuples that can be used for INDEXING THE EDGE GDF

Parameters:
edge_gdf: geopandas.geodataframe.GeoDataFrame

The street network, in a projected coordinate reference system

nodelist: list

A list of nodes that make up source and targets of edges

Returns:
edgelist_final: list

List of edge tuples that can be used for INDEXING THE EDGE GDF

linkbikenet.functions.get_underway_connections(H, pairinfo, components_sorted)[source]

Taking a path between two components, get other components on the way that also become connected.

Parameters:
Hnetworkx.Graph

Graph of bicycle network components, connected up to a stage.

pairinfopandas.DataFrame

Data containing the closest node pair and more information: ‘lcc_nodeid’, ‘comp_nodeid’, ‘distance_nw’, ‘path’, ‘lcc’, ‘comp’

components_sortedlist of nx.Graph

Connected components sorted with the largest first.

Returns:
components_connected_underwaylist

List of components that were connected underway. Can be empty.

connection_pointslist

List of connection point nodes. Can be empty.

linkbikenet.functions.graph_edges_to_gdf(G)[source]

Create a geodataframe with edges attributes from a simple nx graph.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

Returns:
edges_gdfgeopandas.GeoDataFrame

Geodataframe with edges from G, including edge attributes.

linkbikenet.functions.import_bike_network(bike_network, import_path='./')[source]

Import and project a street network from gpkg file

For all edges between a pair of nodes u and v there must be one edge with key 0.

Parameters:
bike_networkstr

The street network will be loaded from this file. Must be a gpkg file in unprojected crs EPSG:4326 with layers nodes and edges, with the structure that a osmnx street network g has after saving its undirected version via ox.io.save_graph_geopackage(). For example: >>> g = ox.graph_from_place(“Barcelona”, network_type=’all_public’, simplify=False, retain_all=True) >>> g = nx.MultiGraph(ox.convert.to_digraph(g)) >>> ox.io.save_graph_geopackage(g, “Barcelona_streets.gpkg”)

import_pathstr, default settings.import_path

Path to import files.

Returns:
h: networkx.Graph

graph of the bike network

linkbikenet.functions.import_network(street_network)[source]

Import and project a street network from gpkg file

For all edges between a pair of nodes u and v there must be one edge with key 0.

Parameters:
street_networkstr

The street network will be loaded from this file. Must be a gpkg file in unprojected crs EPSG:4326 with layers nodes and edges, with the structure that a osmnx street network g has after saving its undirected version via ox.io.save_graph_geopackage(). For example: >>> g = ox.graph_from_place(“Barcelona”, network_type=’all_public’, simplify=False, retain_all=True) >>> ox.io.save_graph_geopackage(g, “Barcelona_streets.gpkg”)

Returns:
nodesgeopandas.geodataframe.GeoDataFrame

Extracted OSM nodes, projected

edgesgeopandas.geodataframe.GeoDataFrame

Extracted OSM edges, projected

g_undirnetworkx.classes.multigraph.MultiGraph

Extracted networkX graph, undirected

city_boundary_gdfgeopandas.geodataframe.GeoDataFrame

Convex hull of the street network

linkbikenet.functions.initialize_progress_bar(desc_string, total=1, unit='step')[source]

Initialize tqdm progress bar.

Link components with the given strategy.

Parameters:
connection_strategystring

Strategy to use for connecting between components.

Hnetworkx.Graph

Graph of bicycle network components.

Gnetworkx.Graph

Graph of the street network.

Returns:
Hnetworkx.Graph

Graph of bicycle network components, with added link paths.

paths_alllist

List of nodes of all added link paths.

path_edges_allset

Set of edges of all added link paths.

num_comps_addedlist

List of how many components were added in each step.

linkbikenet.functions.map_edges_to_bike_infrastructure(g)[source]

map if edges in graph have bike infrastructure as specified in config.py

Parameters:
g :networkx.MultiDiGraph

simplified graph representing the street network

Returns:
gnetworkx.MultiDiGraph

simplified graph representing the street network, with added binary edge attribute “pbi”

linkbikenet.functions.mark_joined_component(H, component, step)[source]

Mark components when they join the largest connected component.

Parameters:
Hnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

componentnetworkx.Graph

Undirected simple graph representing a component of the existing bike network.

stepint

The step at which the component is connected to the largest connected component.

linkbikenet.functions.pair_between_closest_components(wcc)[source]

Find the constants.TOP_CLOSEST_COMPONENTS closest pairs of nodes belonging to two different connected components.

Parameters:
wcclist of nx.Graph

Connected components sorted with the largest first.

Returns:
closest_pairspandas.DataFrame

The constants.TOP_CLOSEST_COMPONENTS candidates of node pairs, with the following info: ‘lcc_nodeid’, ‘comp_nodeid’, ‘distance_eucl’, ‘lcc’, ‘comp’

linkbikenet.functions.pair_between_largest_and_closest_components(wcc)[source]

Find the top constants.TOP_CLOSEST_COMPONENTS pairs of nodes connecting the largest component to the geographically nearest remaining components.

Parameters:
wcclist of nx.Graph

Connected components sorted with the largest first.

Returns:
closest_pairspandas.DataFrame

The constants.TOP_CLOSEST_COMPONENTS candidates of node pairs, with the following info: ‘lcc_nodeid’, ‘comp_nodeid’, ‘distance_eucl’, ‘lcc’, ‘comp’

linkbikenet.functions.pair_between_largest_components(G, wcc)[source]

Find the top constants.TOP_CLOSEST_COMPONENTS pairs of nodes connecting the largest component to the second largest.

Parameters:
componentslist of networkx.Graph

Components sorted with the largest first.

Returns:
closest_pairspandas.DataFrame

The constants.TOP_CLOSEST_COMPONENTS candidates of node pairs, with the following info: ‘lcc_nodeid’, ‘comp_nodeid’, ‘distance_eucl’, ‘lcc’, ‘comp’

linkbikenet.functions.path_to_edges(nodelist)[source]

Turn a list of nodes along a path into a list of edges along the path.

Parameters:
nodelistlist

List of node ids, ordered along a path.

Returns:
edgelist_finallist

List of edge ids (=tuples of node ids), ordered along a path.

linkbikenet.functions.resolve_crs_calculations(gdf, crs_projected='auto')[source]

Resolve settings.crs_projected = ‘auto’

Parameters:
gdfgeopandas.geodataframe.GeoDataFrame

A geodataframe from which to estimate the UTM CRS

crs_projectedstr

A given CRS, or ‘auto’. If ‘auto’, it is resolved to an estimated UTM. In this case, it also sets settings.crs_projected to the UTM.

Returns:
crs_projectedstr

If it was set to ‘auto’, the estimated UTM, otherwise identical to the input crs_calculations.

linkbikenet.functions.shortest_path_components(G, pair_components, path)[source]

Starting from an initial shortest path between a pair of nodes in two different components, identify the two nodes and their shortest path which is truly the shortest path between the two components.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

pair_componentslist

Pair of networkx graph components.

pathlist

List of node ids making up the shortest path of two nodes from the two components.

Returns:
pathlist

List of node ids making up the shortest path between the two components.

linkbikenet.functions.shortest_path_components_from_candidates(G, pair_candidates)[source]

Given a set of node pair candidates between pairs of components, find the two components and their nodes that are closest.

Parameters:
Gnetworkx.Graph

Graph for calculating shortest paths, with edges weighted via ‘length’.

pair_candidatespandas.DataFrame

Data set of node pair candidates between one lcc component and other components. Fields: ‘lcc_nodeid’, ‘comp_nodeid’

Returns:
closest_pairspandas.DataSeries

Data containing the closest node pair and more information: ‘lcc_nodeid’, ‘comp_nodeid’, ‘distance_nw’, ‘path’, ‘lcc’, ‘comp’

linkbikenet.functions.slugify(s)[source]

Slugify a string

Source: https://github.com/Chalarangelo/30-seconds-of-code/blob/master/content/snippets/python/s/slugify.md Note: A clean global solution would be using unidecode, but we do not want extra dependencies for this. We assume European city names in latin alphabet, some special letters like Hungarian long ö already mapped.

Parameters:
sstr

String to slufigy

Returns:
sstr

Slugified string

linkbikenet.settings

Global settings for linkbikenet that can be configured by the user.

export_pathdict(str)

Paths to results and plots folders to save data and plots.

import_pathstr

Path to import files (as defined in growbikenet’s import_files parameter).

silentbool, default False

If set to True, suppresses all user feedback. Useful for batch exports.