fixbikenet 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fixbikenet/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ import contextlib
2
+ from importlib.metadata import PackageNotFoundError, version
3
+
4
+ from . import functions
5
+ from fixbikenet.fixbikenet import fixbikenet
6
+
7
+ __author__ = "MS, AV, MK"
8
+ __author_email__ = "email@domain.com"
9
+
10
+ with contextlib.suppress(PackageNotFoundError):
11
+ __version__ = version("fixbikenet")
fixbikenet/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """fixbikenet package version."""
2
+
3
+ __version__ = "0.5.0" # x-release-please-version
@@ -0,0 +1,183 @@
1
+ # import packages
2
+ import pandas as pd
3
+ import osmnx as ox
4
+ import os
5
+ import matplotlib.pyplot as plt
6
+
7
+ # import functions
8
+ from fixbikenet.functions import *
9
+
10
+ def fixbikenet(
11
+ city_name,
12
+ proj_crs = "3857",
13
+ radius = 2500,
14
+ maxgap = 200,
15
+ penalty = {0: 5, 1: 1},
16
+ export_data = True,
17
+ export_file_format="geojson",
18
+ export_plot=False,
19
+ ):
20
+ """
21
+ Finds gaps in bicycle networks and returns the 100 that are the most important to fill.
22
+ Parameters
23
+ ----------
24
+ city_name : str
25
+ name of the city that the analysis should be performed on
26
+ proj_crs : str, default '3857'
27
+ coordinate reference system that is used to project osm data. Default is '3857' (WGS 84 / Pseudo-Mercator)
28
+ radius : int, default 2500
29
+ cut-off length for computation of local betweenness centrality, in meters
30
+ maxgap : int, default 50
31
+ maximum distance between node pairs to be considered as a potential gap
32
+ penalty : dict, default {0:5, 1: 1}
33
+ weighing for shortest path calculations, where streets without protected bike infrastructure (pbi) get penalized
34
+ export_data : bool, optional, default True
35
+ 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_name
36
+ export_file_format : str, optional, default "geojson"
37
+ 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.
38
+ export_plot : bool, optional, default False
39
+ If set to True, plot will be saved to a file
40
+ Returns
41
+ -------
42
+ gdf : geopandas.geodataframe.GeoDataFrame
43
+ ordered geodataframe with the 100 most important gaps to fill
44
+
45
+ References
46
+ ----------
47
+ [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
48
+ """
49
+ # check if user input is valid
50
+ if type(city_name) != str:
51
+ raise TypeError("city_name must be a string")
52
+ if type(proj_crs) != str:
53
+ raise TypeError("proj_crs must be a string")
54
+ if type(radius) != int:
55
+ raise TypeError("radius must be an integer")
56
+ if type(maxgap) != int:
57
+ raise TypeError("maxgap must be an integer")
58
+ if type(export_data) is not bool:
59
+ raise TypeError("export_data must be a boolean")
60
+ if export_file_format != "geojson" and export_file_format != "gpkg":
61
+ raise ValueError("export_file_format must be 'geojson' or 'gpkg'")
62
+
63
+ ### downloading and preprocessing data from OSM
64
+ print("Downloading OSM data..")
65
+
66
+ # fetch street network data from osmnx
67
+ g = ox.graph_from_place(
68
+ city_name, network_type='all', simplify=False
69
+ )
70
+ g = ox.simplify_graph(
71
+ g,
72
+ edge_attrs_differ=['highway']
73
+ )
74
+
75
+ # export osmnx data to gdfs
76
+ nodes_gdf, edges_gdf = ox.graph_to_gdfs(
77
+ g,
78
+ nodes=True,
79
+ edges=True,
80
+ node_geometry=True,
81
+ fill_edge_geometry=True
82
+ )
83
+
84
+ # project to proj_crs
85
+ nodes_gdf = nodes_gdf.to_crs(proj_crs)
86
+ edges_gdf = edges_gdf.to_crs(proj_crs)
87
+
88
+
89
+ # check which edges have existing bike infrastructure as defined in config/config_osm.yml and assign boolean value to edges
90
+ g = map_edges_to_bike_infrastructure(g)
91
+ edges_gdf = bike_infra_mapping_gdf(g, edges_gdf)
92
+
93
+ print("Checking for parallel edges to drop...")
94
+ edges_to_drop = find_edges_to_drop(g)
95
+ g.remove_edges_from(edges_to_drop)
96
+ print("Edges dropped")
97
+
98
+ # Capital-G: the Graph() object we will be working with from now on
99
+ G = nx.Graph(g)
100
+
101
+ # add weight to edges for path calculation, using penalty
102
+ G = weigh_edges(G, penalty)
103
+
104
+ # finding contact nodes in network
105
+ contact_nodes = find_contact_nodes(G)
106
+
107
+ # finding potential gaps in network
108
+ potential_gaps = find_potential_gaps(contact_nodes, nodes_gdf, maxgap)
109
+
110
+ # add routing for gaps in network
111
+ found_gaps, found_gaps_nsp = find_actual_gaps(G, potential_gaps)
112
+
113
+ # calculating local betweenness score dependent on radius
114
+ print("Calculating local betweenness centrality..")
115
+ ebc = compute_local_betweenness_centrality(G, nodes_gdf, radius)
116
+
117
+ # calculate parameter B for all gaps, used for deciding which gaps are most important
118
+ Bs = rank_gaps_by_b(found_gaps_nsp, G, ebc)
119
+
120
+ df = pd.DataFrame(
121
+ {
122
+ "gap": found_gaps,
123
+ "B": Bs,
124
+ "nodelist": found_gaps_nsp
125
+ }
126
+ )
127
+ df = df.sort_values(by="B", ascending=False).reset_index(drop=True)
128
+
129
+ # only keep the 100 most important gaps. If there are fewer than 100 gaps keep only those
130
+ if df.shape[0] > 100:
131
+ df = df.iloc[:100]
132
+
133
+ # assign source and target nodes for each gap
134
+ df["source"] = [t[0] for t in df.gap]
135
+ df["target"] = [t[1] for t in df.gap]
136
+
137
+ # compute list of all edges that are part of each gap, where each edge is u,v
138
+ df["edge_list"] = df.nodelist.apply(lambda x: get_correct_edgetuples(edges_gdf, x))
139
+
140
+ # drop keys for edges
141
+ edges_gdf = edges_gdf.loc[:, :, 0].copy()
142
+
143
+ # add actual geometries in network to each gap
144
+ gdf = create_gdf_with_geoms(df, edges_gdf)
145
+
146
+ # Generate export data filename
147
+ if export_data:
148
+ os.makedirs("./results/", exist_ok=True)
149
+ export_data_filename = (
150
+ city_name + "-" + export_file_format
151
+ )
152
+
153
+ if export_data:
154
+ ### save data
155
+ print("Saving data..")
156
+ edges_gdf.drop(["osmid"], axis=1, inplace=True)
157
+ city_boundary = ox.geocoder.geocode_to_gdf(city_name)
158
+ city_boundary.to_crs(epsg=proj_crs, inplace=True)
159
+ # We have meter precision, so rounding to integers is fine. Better would be to
160
+ # change dtypes to int, but this does not seem possible without manual looping.
161
+ city_boundary.geometry = city_boundary.geometry.set_precision(grid_size=1)
162
+ edges_gdf.geometry = edges_gdf.geometry.set_precision(grid_size=1)
163
+ gdf.geometry = gdf.geometry.set_precision(grid_size=1)
164
+ if export_file_format == "geojson":
165
+ gdf.to_file("./results/"+export_data_filename, driver="GeoJSON")
166
+ edges_gdf.to_file("./results/"+city_name+"-street_network.geojson", driver="GeoJSON")
167
+ city_boundary.to_file("./results/"+city_name+"-city_boundary.geojson", driver="GeoJSON")
168
+ elif export_file_format == "gpkg":
169
+ gdf.to_file("./results/"+export_data_filename, driver="GPKG", layer="Identified gaps")
170
+ edges_gdf.to_file("./results/"+export_data_filename, driver="GPKG", layer="Street network", append=True)
171
+ city_boundary.to_file("./results/"+export_data_filename, driver="GPKG", layer="City boundary", append=True)
172
+
173
+ if export_plot:
174
+ print("Saving plot..")
175
+ os.makedirs("./results/plots/", exist_ok=True)
176
+ fig, ax = plt.subplots(1, 1, figsize=(10, 10))
177
+ edges_gdf.plot(ax=ax, color="grey")
178
+ gdf.plot(ax=ax, color="red")
179
+ ax.set_axis_off()
180
+ fig.savefig(f"./results/plots/"+export_data_filename+".png", dpi=150, bbox_inches='tight')
181
+ plt.close()
182
+
183
+ return gdf
@@ -0,0 +1,344 @@
1
+ import yaml
2
+ import networkx as nx
3
+ import random
4
+ import numpy as np
5
+ import geopandas as gpd
6
+
7
+ def map_edges_to_bike_infrastructure(g):
8
+ """
9
+ map if edges in graph have bike infrastructure as specified in config_osm.yml
10
+
11
+ Parameters
12
+ ----------
13
+ g :networkx.MultiDiGraph
14
+ simplified graph representing the street network
15
+
16
+ Returns
17
+ -------
18
+ g : networkx.MultiDiGraph
19
+ simplified graph representing the street network, with added binary edge attribute "pbi"
20
+ """
21
+ # first step: map all highway attributes
22
+ protected_bike_infra = yaml.load(
23
+ open("./config/config_osm.yml"),
24
+ Loader=yaml.FullLoader)["protected_bike_infra"]
25
+
26
+ # add binary edge attribute "pbi" (protected bike infra: True/False)
27
+ for edge in g.edges(keys=True):
28
+ g.edges[edge]["pbi"] = protected_bike_infra[
29
+ g.edges[edge]["highway"]
30
+ ]
31
+ return g
32
+
33
+ def bike_infra_mapping_gdf(g, edges_gdf):
34
+ """
35
+ add binary edge attribute pbi to edges_gdf
36
+
37
+ Parameters
38
+ ----------
39
+ g : networkx.MultiDiGraph
40
+ simplified graph representing the street network, with added binary edge attribute "pbi"
41
+ edges_gdf: geopandas.GeoDataFrame
42
+ edges representing the street network
43
+
44
+ Returns
45
+ -------
46
+ edges_gdf: geopandas.GeoDataFrame
47
+ edges representing the street network with added binary attribute "pbi"
48
+ """
49
+ # Build dict of edge attribute
50
+ attr_dict = {
51
+ (u, v, k): data['pbi']
52
+ for u, v, k, data in g.edges(keys=True, data=True)
53
+ }
54
+
55
+ # Map to GeoDataFrame
56
+ edges_gdf['pbi'] = edges_gdf.index.map(attr_dict)
57
+ return edges_gdf
58
+
59
+ def find_edges_to_drop(g):
60
+ """
61
+ find parallel edges that have different pbi values, list the ones with pbi=0
62
+
63
+ Parameters
64
+ ----------
65
+ g : networkx.MultiDiGraph
66
+ simplified graph representing the street network, with added binary edge attribute "pbi"
67
+
68
+ Returns
69
+ -------
70
+ edges_to_drop: list
71
+ unique list of edges to drop-> edges where pbi values differ and pbi value=0 gets dropped
72
+ """
73
+ # to find parallel edges, get all u,v tuples for which u,v,w>0 exists:
74
+ uvs = [edge[:2] for edge in list(g.edges) if edge[2] > 0] # >0 includes key=1, key=2, ...
75
+ uvs = list(set(uvs))
76
+ edges_to_drop = []
77
+
78
+ for uv in uvs:
79
+ # collect all parallel edges for u-v node pair;
80
+ # account for the fact that edges are directed! uv[::-1]==vu might also be on the list
81
+ parallel_edges = [edge for edge in list(g.edges) if (edge[:2] == uv) or (edge[:2] == uv[::-1])]
82
+
83
+ # get set of PBIs for this u-v parallel edge list
84
+ pbis = set([g.edges[e]["pbi"] for e in parallel_edges])
85
+
86
+ # if we have both pbi==0 and pbi==1,
87
+ if len(pbis) == 2:
88
+ # add edges with pbi==0 to edges_to_drop list
89
+ to_drop = [e for e in parallel_edges if g.edges[e]["pbi"] == 0]
90
+ edges_to_drop += to_drop
91
+
92
+ edges_to_drop = list(set(edges_to_drop))
93
+ return edges_to_drop
94
+
95
+ def weigh_edges(G, penalty):
96
+ """
97
+ adds weight parameter to all edges in G, which is calculated by multiplying the length of the edge with the corresponding penalty value
98
+
99
+ Parameters
100
+ ----------
101
+ G: networkx.Graph
102
+ undirected simple graph representing the street network
103
+ penalty: dictionary
104
+ dictionary of penalty values, dependent on if edge has bike infrastructure or not
105
+
106
+ Returns
107
+ -------
108
+ G: networkx.Graph
109
+ undirected simple graph representing the street network with weighted edges
110
+ """
111
+ for edge in G.edges:
112
+ # compute edge weight
113
+ edge_pbi = G.edges[edge]["pbi"]
114
+ edge_length = G.edges[edge]["length"]
115
+ edge_weight = edge_length * penalty[edge_pbi]
116
+ # add as attribute
117
+ G.edges[edge]["weight"] = edge_weight
118
+ return G
119
+
120
+ def find_contact_nodes(G):
121
+ """
122
+ find nodes that have both edges with protected and without protected bike infrastructure incident on them
123
+
124
+ Parameters
125
+ ----------
126
+ G:networkx.Graph
127
+ undirected simple graph representing the street network with weighted edges
128
+
129
+ Return
130
+ ------
131
+ contact_nodes: list
132
+ list of all nodes that fulfill criteria to be a contact node
133
+ """
134
+ contact_nodes = []
135
+ for node in G.nodes:
136
+ pbis = set([G.edges[edge]["pbi"] for edge in G.edges(node)])
137
+ if len(pbis) == 2:
138
+ contact_nodes.append(node)
139
+ return contact_nodes
140
+
141
+ def find_potential_gaps(contact_nodes, nodes_gdf, maxgap):
142
+ """
143
+ finds potential gaps in protected bicycle network, corresponding to two contact nodes that are within maxgap euclidean distance of each other
144
+
145
+ Parameters
146
+ ----------
147
+ contact_nodes: list
148
+ list of all nodes that fulfill criteria to be a contact node
149
+ nodes_gdf: geopandas.GeoDataFrame
150
+ all nodes in street network
151
+ maxgap: int
152
+ user defined maximal euclidean distance between two contact nodes
153
+
154
+ Returns
155
+ -------
156
+ potential_gaps: list
157
+ all unique potential gaps in protected bicycle network
158
+ """
159
+ potential_gaps = []
160
+
161
+ for node in contact_nodes:
162
+ node_buffer = nodes_gdf.loc[node, "geometry"].buffer(maxgap)
163
+ q = nodes_gdf.sindex.query(node_buffer, predicate="intersects")
164
+ neighbours = list(nodes_gdf.iloc[q].index)
165
+ neighbours.remove(node)
166
+ # convention: sort by ascending OSMID...
167
+ node_pairs = [tuple(sorted(z)) for z in zip([node] * len(neighbours), neighbours)]
168
+ potential_gaps += node_pairs
169
+
170
+ # ... so that we can easily deduplicate
171
+ potential_gaps = list(set(potential_gaps))
172
+ return potential_gaps
173
+
174
+ def find_actual_gaps(G, potential_gaps):
175
+ """
176
+ determines which potential gaps are actual gaps by finding paths between all contact nodes and only keeping the gaps that have no protected bike infrastructure
177
+
178
+ Parameters
179
+ ----------
180
+ G: networkx.Graph
181
+ undirected simple graph representing the street network with weighted edges
182
+ potential_gaps: list
183
+ all unique potential gaps in protected bicycle network
184
+
185
+ Returns
186
+ -------
187
+ found_gaps: list
188
+ list of all gaps in protected bicycle network
189
+ found_gaps_nsp: list
190
+ list of paths in network for all gaps in protected bicycle network
191
+ """
192
+ pbi_dict = nx.get_edge_attributes(G, "pbi")
193
+
194
+ found_gaps = []
195
+ found_gaps_nsp = []
196
+
197
+ for u, v in potential_gaps:
198
+
199
+ try:
200
+ nodelist = nx.shortest_path(G, u, v, weight="length")
201
+ except nx.NetworkXNoPath:
202
+ continue
203
+
204
+ # assume valid until proven otherwise
205
+ valid = True
206
+
207
+ for i in range(len(nodelist) - 1):
208
+ a, b = nodelist[i], nodelist[i + 1]
209
+
210
+ # undirected edge normalization (ONLY once per lookup)
211
+ key = (a, b) if (a, b) in pbi_dict else (b, a)
212
+
213
+ if pbi_dict.get(key, 1) != 0:
214
+ valid = False
215
+ break
216
+
217
+ if valid:
218
+ found_gaps.append((u, v))
219
+ found_gaps_nsp.append(nodelist)
220
+
221
+ return found_gaps, found_gaps_nsp
222
+
223
+ def compute_local_betweenness_centrality(G, nodes_gdf, radius):
224
+ """
225
+ computes weighted betweenness centrality for paths within radius
226
+
227
+ Parameters
228
+ ----------
229
+ G: networkx.Graph
230
+ undirected simple graph representing the street network with weighted edges
231
+ nodes_gdf: geopandas.GeoDataFrame
232
+ all nodes in street network
233
+ radius: int
234
+ maximum length of path for betweennessn centrality calculation, set by user
235
+
236
+ Returns
237
+ -------
238
+ ebc: dict
239
+ local betweenness centrality values for all edges in network
240
+ """
241
+ # set current ebc value of all G edges to 0
242
+ for edge in G.edges:
243
+ G.edges[edge]["ebc"] = 0
244
+
245
+ # create dict that will be updated at each step
246
+ ebc = nx.get_edge_attributes(G, "ebc")
247
+
248
+ # for each node, compute "local" ebc (buffered with radius!)
249
+ # for comp feas, now only subset of randomly drawn 300 nodes
250
+ random.seed(1312)
251
+ random_nodes = random.choices(list(G.nodes), k=300)
252
+ for node in random_nodes:
253
+ node_buffer = nodes_gdf.loc[node, "geometry"].buffer(radius)
254
+ q = nodes_gdf.sindex.query(node_buffer, predicate="intersects")
255
+ neighbours = list(nodes_gdf.iloc[q].index)
256
+ local_ebc = nx.edge_betweenness_centrality_subset(
257
+ G=G,
258
+ sources=[node],
259
+ targets=neighbours,
260
+ normalized=False, # important! otherwise the addition makes no sense
261
+ weight="weight" # using penalty for non-pbi
262
+ )
263
+
264
+ # update ebc dictionary
265
+ for k, v in local_ebc.items():
266
+ ebc[k] += v # updating ebc!!
267
+ return ebc
268
+
269
+ def rank_gaps_by_b(found_gaps_nsp, G, ebc):
270
+ """
271
+ calculates b for all gaps
272
+
273
+ Parameters
274
+ ----------
275
+ found_gaps_nsp: list
276
+ list of paths in network for all gaps in protected bicycle network
277
+ G: networkx.Graph
278
+ undirected simple graph representing the street network with weighted edges
279
+ ebc: dict
280
+ local betweenness centrality values for all edges in network
281
+
282
+ Returns
283
+ -------
284
+ Bs: list
285
+ list of values of b for all gaps in protected bicycle network
286
+ """
287
+ Bs = []
288
+ for nodelist in found_gaps_nsp:
289
+ edgelist = [tuple(sorted(z)) for z in zip(nodelist, nodelist[1:])]
290
+ lengths = np.array([G.edges[edge]["length"] for edge in edgelist])
291
+ ebcs = np.array([ebc[edge] for edge in edgelist])
292
+ B = sum(lengths * ebcs) / sum(lengths)
293
+ Bs.append(B)
294
+ return Bs
295
+
296
+ def get_correct_edgetuples(edge_gdf, nodelist):
297
+ """
298
+ helper function that maps a node list (output of nx.shortest_paths)
299
+ to the correct set of edge tuples that can be used for INDEXING THE EDGE GDF
300
+
301
+ Parameters
302
+ ----------
303
+ edge_gdf: geopandas.geodataframe.GeoDataFrame
304
+ The street network, in a projected coordinate reference system
305
+ nodelist: list
306
+ A list of nodes that make up source and targets of edges
307
+
308
+ Returns
309
+ -------
310
+ edgelist_final: list
311
+ List of edge tuples that can be used for INDEXING THE EDGE GDF
312
+ """
313
+ edgelist_prelim = zip(nodelist, nodelist[1:])
314
+ edgelist_final = []
315
+ for edge_prelim in edgelist_prelim:
316
+ if edge_prelim in edge_gdf.index:
317
+ edgelist_final.append(edge_prelim)
318
+ else:
319
+ edgelist_final.append(tuple([edge_prelim[1], edge_prelim[0]]))
320
+ return edgelist_final
321
+
322
+ def create_gdf_with_geoms(df, edges):
323
+ """
324
+ Parameters
325
+ ----------
326
+ df: pandas.DataFrame
327
+ Dataframe with path nodes and path edges
328
+ edges: geopandas.GeoDataFrame
329
+ The street network, in a projected coordinate reference system
330
+
331
+ Returns
332
+ -------
333
+ gdf: geopandas.GeoDataFrame
334
+ projected GeoDataFrame with path nodes and path edges and merged geometries
335
+ """
336
+ # get geometry by merging all geoms from edge gdf
337
+ df["geometry"] = df.edge_list.apply(
338
+ lambda x: edges.loc[x].geometry.union_all()
339
+ )
340
+ # convert edges into a gdf
341
+ gdf = gpd.GeoDataFrame(df, crs=edges.crs, geometry="geometry")
342
+ # merge multilinestring into linestring where possible (should be possible everywhere)
343
+ gdf["geometry"] = gdf.line_merge()
344
+ return gdf