Developer reference

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

fixbikenet.fixbikenet

Main procedure for running fixbikenet.

fixbikenet.fixbikenet.fixbikenet(city_query, min_gap_length=20, max_gap_length=800, num_gaps=50, export_data=True, city_id=None, export_plot=False, import_files={})[source]

Find gaps in bicycle networks and return the num_gaps that are the most important to fill.

Parameters:
city_querystr

Name of the city that the analysis should be performed on.

min_gap_lengthint, default 20

Minimum distance between node pairs to be considered as a potential gap, in meters.

max_gap_lengthint, default 800

Maximum distance between node pairs to be considered as a potential gap, in meters.

num_gapsint, default 50

Number of gaps to find.

export_databool, default True

If set to True, data will be saved to a file. The filename is [slug].[settings.export_file_format], where slug is a string id made out of city_query (or city_id if set).

city_idstr | None, 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_plotbool, optional, default False

If set to True, plot will be saved to a file.

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’str | None, default None

    If not set to None, the street network is loaded from this file. For best results, this network should encompass both car and protected bicycle infrastructure. 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: >>> import fixbikenet as fbn >>> g = ox.graph_from_place(“Barcelona”, simplify=False, retain_all=True, custom_filter = fbn.osm.CARPBI_NETWORK_CUSTOM_FILTER) >>> g = nx.MultiGraph(ox.convert.to_digraph(g)) >>> ox.io.save_graph_geopackage(g, “Barcelona_carpbi_network.gpkg”).

  • ‘point_data’None or str, default None

    If not set to None, an additional data set of points will be loaded from this file, representing point events like traffic crashes or citizen feedback to improve bike infrastructure. Must be a gpkg or geojson file in unprojected CRS EPSG:4326 containing only point objects, optionally with an int num column that encodes the number of point events. The data set is used to re-prioritize the ordering of the network gaps, controlled with settings.import_data_impact.

Returns:
gaps_orderedgeopandas.geodataframe.GeoDataFrame

Ordered geodataframe with the num_gaps most important gaps to fill.

References

[1] Vybornova, A., Cunha, T., Gühnemann, A. and Szell, M. (2023), Automated Detection of Missing Links in Bicycle Networks. Geogr Anal, 55: 239-267. https://doi.org/10.1111/gean.12324

fixbikenet.osm

Global constants for fixbikenet related to OpenStreetMap (OSM). These are meant for advanced users only who have a good understanding of OSM tags.

CARPBI_NETWORK_CUSTOM_FILTERlist[str] or None

Custom filter for all infrastructure elements that are the combined drive and pbi (protected bicycle infrastructure) network. By default, CARPBI_NETWORK_CUSTOM_FILTER is a superset of PBI_CUSTOM_FILTER, so it is best to keep them in sync.

PBI_CUSTOM_FILTERlist[str]

Custom filter for protected bicycle infrastructure (pbi). Always keep in sync with PBI_DICT and PBI_DICT_SUB. By default, PBI_CUSTOM_FILTER is a subset of CARPBI_NETWORK_CUSTOM_FILTER, so it is best to keep them in sync.

PBI_DICTdict

Dictionary for protected bicycle infrastructure (pbi), for single criteria. Always keep in sync with PBI_CUSTOM_FILTER.

PBI_DICT_SUBdict

Dictionary for protected bicycle infrastructure (pbi), with one sub-criterion. For example, highway~path AND bicycle~designated. Always adds a second criterion access!~private. Always keep in sync with PBI_CUSTOM_FILTER.

fixbikenet.utils

Utility utils for fixbikenet.

fixbikenet.utils._get_weighted_distances(B, num_types, inverted=False)[source]

Get weighted distances by edge attribute num_types.

Parameters:
Bnetworkx.classes.multigraph.MultiGraph

The routed, grown bicycle network graph, where edges have the attribute num_types. The numerical attribute “distance” must exist for all edges.

num_typesstr

Name of the attribute to weight the distances.

Returns:
dist_weighted_by_types_dictdict

Dictionary where keys are the edges (tuples of node ids), and values are the weighted distances following [1].

Notes

The calculation follows [1], only without +1 in the numerator and with a small epsilon to prevent division by zero.

References

[1] (1,2)
  1. Folco, L. Gauvin, M. Tizzoni, M. Szell, Data-driven micromobility network planning for demand and safety, Environment and planning B: Urban analytics and city science 50(8), 2087-2102 (2023)

fixbikenet.utils._import_data_files(import_files)[source]

Import data files.

Print footer.

fixbikenet.utils._print_header(city_query)[source]

Print header.

fixbikenet.utils._reset_auto_settings(setting_was_auto)[source]

Reset settings and constants to auto.

fixbikenet.utils._resolve_crs_calculations(gdf)[source]

Resolve constants._CRS_CALCULATIONS = ‘auto’

Parameters:
gdfgeopandas.geodataframe.GeoDataFrame

A geodataframe from which to estimate the UTM CRS

fixbikenet.utils._validate_parameters(city_query, min_gap_length, max_gap_length, export_data, import_files)[source]

Check if user parameter input is valid. If not, raise an exception or warning.

Parameters:
Same as `growbikenet.growbikenet()`
Additionally:
constants._PRESET_TAGSdict

Dictionary of preset seed point tags.

Returns:
import_filesdefaultdict

Defaultdict of file names to import.

fixbikenet.utils._validate_settings()[source]

Check if user settings input is valid. If not, raise an exception or warning.

Returns:
setting_was_autodict

Dictionary remembering which setting or constant was set to auto, so it can be reset to auto in the end.

fixbikenet.utils.add_point_data_to_net(points, edges)[source]

Match point data to network edges.

Parameters:
pointsgeopandas.geodataframe.GeoDataFrame

A geodataframe of unprojected point geometries, optional having a column num containing an integer. This could be (number of) point events like crashes or citizen feedback to improve bike infrastructure. If a num column is not provided, assumes 1 per point.

edgesgeopandas.geodataframe.GeoDataFrame

A geodataframe of projected spatial network edges. This is the routed network of seed points.

matching_distanceint, default settings.import_point_data_snap_distance

Matching distance in meters. Set via settings.import_point_data_snap_distance.

Returns:
edges_with_datageopandas.geodataframe.GeoDataFrame

The same spatial network edges, but with a new int column num_points populated with the summed up num values of all points, matched to the closest links if within matching_distance.

fixbikenet.utils.assign_pbi_to_edges(g)[source]

Assign a boolean pbi attribute to all edges in a graph depending if they are considered protected bike infrastructure (pbi).

Parameters:
gnetworkx.MultiDiGraph

Simplified graph representing the street network.

Returns:
gnetworkx.MultiDiGraph

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

fixbikenet.utils.bike_infra_mapping_gdf(g, edges_gdf)[source]

Add binary edge attribute pbi to edges_gdf.

Parameters:
gnetworkx.MultiDiGraph

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

edges_gdfgeopandas.GeoDataFrame

Edges representing the street network.

Returns:
edges_gdfgeopandas.GeoDataFrame

Edges representing the street network with added binary attribute “pbi”.

fixbikenet.utils.compute_benefit_metric(comp, node_path, ebc)[source]

Compute benefit metric B for edge in connected component of edges.

Parameters:
compnetworkx.Graph

Connected component of edges.

node_pathlist

list of nodes on path.

ebcdict

Local betweenness centrality values for all edges in network.

Returns:
Bfloat

Benefit metric B for edge.

fixbikenet.utils.compute_local_betweenness_centrality(G, nodes_gdf)[source]

Compute weighted betweenness centrality for paths within settings.radius.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

nodes_gdfgeopandas.GeoDataFrame

All nodes in street network.

Returns:
ebcdict

Local betweenness centrality values for all edges in network.

fixbikenet.utils.create_gdf_with_geoms(df, edges)[source]
Parameters:
dfpandas.DataFrame

Dataframe with path nodes and path edges.

edgesgeopandas.GeoDataFrame

The street network, in a projected coordinate reference system.

Returns:
gdfgeopandas.GeoDataFrame

Projected GeoDataFrame with path nodes and path edges and merged geometries.

fixbikenet.utils.download_network(city_query, network_type='drive', custom_filter=None, retain_all=True, city_boundary_geometry=None)[source]

Download and prepare a street network from OSM via OSMnx.

Downloads a network with a given network_type and custom_filter using ox.graph_from_place(). Then, stores the undirected OSM data in geodataframes and projects using constants._CRS_CALCULATIONS.

Parameters:
city_querystr

Name of the city that the analysis should be performed on. Overruled (for data fetching) if city_boundary_geometry is set.

network_type{‘drive’, ‘all’, ‘all_public’, ‘bike’, ‘drive_service’, ‘walk’}, default ‘drive’

What type of street network to retrieve if custom_filter is None.

custom_filterNone or str or list[str], default None

A custom ways filter to be used instead of the network_type presets.

retain_allbool, default True

If True, return the entire graph even if it is not connected, useful for disconnected bicycle networks. If False, retain only the largest weakly connected component, useful for road networks.

city_boundary_geometryNone or shapely.Polygon or shapely.MultiPolygon,
default None

If not set to None, the study area is selected from this geometry.

Returns:
nodesgeopandas.geodataframe.GeoDataFrame

Extracted OSM nodes, projected.

edgesgeopandas.geodataframe.GeoDataFrame

Extracted OSM edges, projected.

g_undirnetworkx.classes.multigraph.MultiGraph

Extracted networkX graph, undirected.

fixbikenet.utils.find_actual_gaps(G, potential_gaps, min_gap_length)[source]

Determine which potential gaps are actual gaps by finding paths between all contact nodes and only keeping the gaps that have no protected bike infrastructure.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

potential_gapslist

All unique potential gaps in protected bicycle network.

min_gap_lengthint

Minimum distance between node pairs to be considered as a potential gap, in meters.

Returns:
found_gapslist

List of all gaps in protected bicycle network.

found_gaps_nsplist

List of paths in network for all gaps in protected bicycle network.

fixbikenet.utils.find_contact_nodes(G)[source]

Find nodes that have both edges with protected and without protected bike infrastructure incident on them.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

fixbikenet.utils.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_droplist

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

fixbikenet.utils.find_potential_gaps(contact_nodes, nodes_gdf, max_gap_length)[source]

Find potential gaps in protected bicycle network, corresponding to two contact nodes that are within max_gap_length euclidean distance of each other.

Parameters:
contact_nodeslist

list of all nodes that fulfill criteria to be a contact node.

nodes_gdfgeopandas.GeoDataFrame

All nodes in street network.

max_gap_lengthint

User defined maximal euclidean distance between two contact nodes.

Returns:
potential_gapslist

All unique potential gaps in protected bicycle network.

fixbikenet.utils.gap_declustering(gaps_df, G, ebc, contact_nodes, min_gap_length)[source]
Parameters:
gaps_dfpd.DataFrame

Dataframe containing gaps in protected bicycle network.

Gnetworkx.Graph

undirected simple graph representing the street network with weighted edges.

ebcdict

local betweenness centrality values for all edges in network.

contact_nodeslist

List of contact nodes.

min_gap_lengthint

Minimum distance between node pairs to be considered as a potential gap, in meters.

Returns:
resultpd.DataFrame

Dataframe with node path for gaps and the newly calculated benefit metric.

fixbikenet.utils.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_gdfgeopandas.geodataframe.GeoDataFrame

The street network, in a projected coordinate reference system.

nodelistlist

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

Returns:
edgelist_finallist

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

fixbikenet.utils.graph_edges_to_gdf(G)[source]
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.

fixbikenet.utils.graph_nodes_to_gdf(G)[source]
Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

Returns:
nodes_gdfgeopandas.GeoDataFrame

geodataframe with nodes from G.

fixbikenet.utils.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’) >>> 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:
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.

fixbikenet.utils.initialize_progress_bar(desc_string, total=1, unit='step')[source]

Initialize tqdm progress bar.

fixbikenet.utils.rank_gaps_by_b(found_gaps_nsp, G, ebc)[source]

Calculate b for all gaps.

Parameters:
found_gaps_nsplist

List of paths in network for all gaps in protected bicycle network.

Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

ebcdict

Local betweenness centrality values for all edges in network.

Returns:
Bs: list

list of values of b for all gaps in protected bicycle network.

fixbikenet.utils.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.

fixbikenet.utils.weigh_edges(G)[source]

Add weight parameter to all edges in G, calculated by multiplying the length of the edge with the corresponding penalty value.

Parameters:
Gnetworkx.Graph

Undirected simple graph representing the street network.

Returns:
Gnetworkx.Graph

Undirected simple graph representing the street network with weighted edges.

fixbikenet.settings

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

export_file_format{‘gpkg’, ‘geojson’}, default ‘gpkg’

File format for the data export, relevant if export_data is set to True. If exporting as geojson, generates extra files for seed points, city boundary, and existing bicycle network (if relevant). If exporting as gkpg, these are added all in one file as extra layers.

export_pathdict(str)

Paths to results folder to save data.

import_data_impactfloat, default 10000

Impact of imported trip or point data on results. Must be non-negative.

import_point_data_snap_distanceint, default 100

Maximum distance between point data and network links for snapping, in meters.

import_pathstr

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

radiusint, default 2500

Cut-off length for computation of local betweenness centrality, in meters.

random_seedint, default 43

Random number generator seed for reproducibility

silentbool, default False

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