forked from mszell/bikenwgrowth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
2318 lines (1877 loc) · 97.5 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# GRAPH PLOTTING
def holepatchlist_from_cov(cov, map_center):
"""Get a patchlist of holes (= shapely interiors) from a coverage Polygon or MultiPolygon
"""
holeseq_per_poly = get_holes(cov)
holepatchlist = []
for hole_per_poly in holeseq_per_poly:
for hole in hole_per_poly:
holepatchlist.append(hole_to_patch(hole, map_center))
return holepatchlist
def fill_holes(cov):
"""Fill holes (= shapely interiors) from a coverage Polygon or MultiPolygon
"""
holeseq_per_poly = get_holes(cov)
holes = []
for hole_per_poly in holeseq_per_poly:
for hole in hole_per_poly:
holes.append(hole)
eps = 0.00000001
if isinstance(cov, shapely.geometry.multipolygon.MultiPolygon):
cov_filled = ops.unary_union([poly for poly in cov] + [Polygon(hole).buffer(eps) for hole in holes])
elif isinstance(cov, shapely.geometry.polygon.Polygon) and not cov.is_empty:
cov_filled = ops.unary_union([cov] + [Polygon(hole).buffer(eps) for hole in holes])
return cov_filled
def extract_relevant_polygon(placeid, mp):
"""Return the most relevant polygon of a multipolygon mp, for being considered the city limit.
Depends on location.
"""
if isinstance(mp, shapely.geometry.polygon.Polygon):
return mp
if placeid == "tokyo": # If Tokyo, take poly with most northern bound, otherwise largest
p = max(mp, key=lambda a: a.bounds[-1])
else:
p = max(mp, key=lambda a: a.area)
return p
def get_holes(cov):
"""Get holes (= shapely interiors) from a coverage Polygon or MultiPolygon
"""
holes = []
if isinstance(cov, shapely.geometry.multipolygon.MultiPolygon):
for pol in cov.geoms: # cov is generally a MultiPolygon, so we iterate through its Polygons
holes.append(pol.interiors)
elif isinstance(cov, shapely.geometry.polygon.Polygon) and not cov.is_empty:
holes.append(cov.interiors)
return holes
def cov_to_patchlist(cov, map_center, return_holes = True):
"""Turns a coverage Polygon or MultiPolygon into a matplotlib patch list, for plotting
"""
p = []
if isinstance(cov, shapely.geometry.multipolygon.MultiPolygon):
for pol in cov.geoms: # cov is generally a MultiPolygon, so we iterate through its Polygons
p.append(pol_to_patch(pol, map_center))
elif isinstance(cov, shapely.geometry.polygon.Polygon) and not cov.is_empty:
p.append(pol_to_patch(cov, map_center))
if not return_holes:
return p
else:
holepatchlist = holepatchlist_from_cov(cov, map_center)
return p, holepatchlist
def pol_to_patch(pol, map_center):
"""Turns a coverage Polygon into a matplotlib patch, for plotting
"""
y, x = pol.exterior.coords.xy
pos_transformed, _ = project_pos(y, x, map_center)
return matplotlib.patches.Polygon(pos_transformed)
def hole_to_patch(hole, map_center):
"""Turns a LinearRing (hole) into a matplotlib patch, for plotting
"""
y, x = hole.coords.xy
pos_transformed, _ = project_pos(y, x, map_center)
return matplotlib.patches.Polygon(pos_transformed)
def set_analysissubplot(key):
ax.set_xlim(0, 1)
ax.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1])
if key in ["length", "length_lcc", "coverage", "poi_coverage", "components", "efficiency_local", "efficiency_global"]:
ax.set_ylim(bottom = 0)
if key in ["directness_lcc", "directness_lcc_linkwise", "directness", "directness_all_linkwise"]:
ax.set_ylim(bottom = 0.2)
if key in ["directness_lcc", "directness_lcc_linkwise", "directness", "directness_all_linkwise", "efficiency_global", "efficiency_local"]:
ax.set_ylim(top = 1)
def initplot():
fig = plt.figure(figsize=(plotparam["bbox"][0]/plotparam["dpi"], plotparam["bbox"][1]/plotparam["dpi"]), dpi=plotparam["dpi"])
plt.axes().set_aspect('equal')
plt.axes().set_xmargin(0.01)
plt.axes().set_ymargin(0.01)
plt.axes().set_axis_off() # Does not work anymore - unnown why not.
return fig
def nodesize_from_pois(nnids):
"""Determine POI node size based on number of POIs.
The more POIs the smaller (linearly) to avoid overlaps.
"""
minnodesize = 30
maxnodesize = 220
return max(minnodesize, maxnodesize-len(nnids))
def simplify_ig(G):
"""Simplify an igraph with ox.simplify_graph
"""
G_temp = copy.deepcopy(G)
G_temp.es["length"] = G_temp.es["weight"]
output = ig.Graph.from_networkx(ox.simplify_graph(nx.MultiDiGraph(G_temp.to_networkx())).to_undirected())
output.es["weight"] = output.es["length"]
return output
def nxdraw(G, networktype, map_center = False, nnids = False, drawfunc = "nx.draw", nodesize = 0, weighted = False, maxwidthsquared = 0, simplified = False):
"""Take an igraph graph G and draw it with a networkx drawfunc.
"""
if simplified:
G.es["length"] = G.es["weight"]
G_nx = ox.simplify_graph(nx.MultiDiGraph(G.to_networkx())).to_undirected()
else:
G_nx = G.to_networkx()
if nnids is not False: # Restrict to nnids node ids
nnids_nx = [k for k,v in dict(G_nx.nodes(data=True)).items() if v['id'] in nnids]
G_nx = G_nx.subgraph(nnids_nx)
pos_transformed, map_center = project_nxpos(G_nx, map_center)
if weighted is True:
# The max width should be the node diameter (=sqrt(nodesize))
widths = list(nx.get_edge_attributes(G_nx, "weight").values())
widthfactor = 1.1 * math.sqrt(maxwidthsquared) / max(widths)
widths = [max(0.33, w * widthfactor) for w in widths]
eval(drawfunc)(G_nx, pos_transformed, **plotparam[networktype], node_size = nodesize, width = widths)
elif type(weighted) is float or type(weighted) is int and weighted > 0:
eval(drawfunc)(G_nx, pos_transformed, **plotparam[networktype], node_size = nodesize, width = weighted)
else:
eval(drawfunc)(G_nx, pos_transformed, **plotparam[networktype], node_size = nodesize)
return map_center
# OTHER FUNCTIONS
def common_entries(*dcts):
"""Like zip() but for dicts.
See: https://stackoverflow.com/questions/16458340/python-equivalent-of-zip-for-dictionaries
"""
if not dcts:
return
for i in set(dcts[0]).intersection(*dcts[1:]):
yield (i,) + tuple(d[i] for d in dcts)
def project_nxpos(G, map_center = False):
"""Take a spatial nx network G and projects its GPS coordinates to local azimuthal.
Returns transformed positions, as used by nx.draw()
"""
lats = nx.get_node_attributes(G, 'x')
lons = nx.get_node_attributes(G, 'y')
pos = {nid:(lat,-lon) for (nid,lat,lon) in common_entries(lats,lons)}
if map_center:
loncenter = map_center[0]
latcenter = map_center[1]
else:
loncenter = np.mean(list(lats.values()))
latcenter = -1* np.mean(list(lons.values()))
local_azimuthal_projection = "+proj=aeqd +R=6371000 +units=m +lat_0={} +lon_0={}".format(latcenter, loncenter)
# Use transformer: https://gis.stackexchange.com/questions/127427/transforming-shapely-polygon-and-multipolygon-objects
wgs84_to_aeqd = pyproj.Transformer.from_proj(
pyproj.Proj("+proj=longlat +datum=WGS84 +no_defs"),
pyproj.Proj(local_azimuthal_projection))
pos_transformed = {nid:list(ops.transform(wgs84_to_aeqd.transform, Point(latlon)).coords)[0] for nid, latlon in pos.items()}
return pos_transformed, (loncenter,latcenter)
def project_pos(lats, lons, map_center = False):
"""Project GPS coordinates to local azimuthal.
"""
pos = [(lat,-lon) for lat,lon in zip(lats,lons)]
if map_center:
loncenter = map_center[0]
latcenter = map_center[1]
else:
loncenter = np.mean(list(lats.values()))
latcenter = -1* np.mean(list(lons.values()))
local_azimuthal_projection = "+proj=aeqd +R=6371000 +units=m +lat_0={} +lon_0={}".format(latcenter, loncenter)
# Use transformer: https://gis.stackexchange.com/questions/127427/transforming-shapely-polygon-and-multipolygon-objects
wgs84_to_aeqd = pyproj.Transformer.from_proj(
pyproj.Proj("+proj=longlat +datum=WGS84 +no_defs"),
pyproj.Proj(local_azimuthal_projection))
pos_transformed = [(ops.transform(wgs84_to_aeqd.transform, Point(latlon)).coords)[0] for latlon in pos]
return pos_transformed, (loncenter,latcenter)
def round_coordinates(G, r = 7):
for v in G.vs:
G.vs[v.index]["x"] = round(G.vs[v.index]["x"], r)
G.vs[v.index]["y"] = round(G.vs[v.index]["y"], r)
def mirror_y(G):
for v in G.vs:
y = G.vs[v.index]["y"]
G.vs[v.index]["y"] = -y
def dist(v1, v2):
dist = haversine((v1['y'],v1['x']),(v2['y'],v2['x']), unit="m") # x is lon, y is lat
return dist
def dist_vector(v1_list, v2_list):
dist_list = haversine_vector(v1_list, v2_list, unit="m") # [(lat,lon)], [(lat,lon)]
return dist_list
def osm_to_ig(node, edge, weighting):
""" Turns a node and edge dataframe into an igraph Graph.
"""
G = ig.Graph(directed=False)
x_coords = node['x'].tolist()
y_coords = node['y'].tolist()
ids = node['osmid'].tolist()
coords = []
for i in range(len(x_coords)):
G.add_vertex(x=x_coords[i], y=y_coords[i], id=ids[i])
coords.append((x_coords[i], y_coords[i]))
id_dict = dict(zip(G.vs['id'], np.arange(0, G.vcount()).tolist()))
coords_dict = dict(zip(np.arange(0, G.vcount()).tolist(), coords))
edge_list = []
edge_info = {
"weight": [],
"osmid": [],
# Only include ori_length if weighting is True
"ori_length": [] if weighting else None
}
for i in range(len(edge)):
edge_list.append([id_dict.get(edge['u'][i]), id_dict.get(edge['v'][i])])
edge_info["weight"].append(round(edge['length'][i], 10))
edge_info["osmid"].append(edge['osmid'][i])
if weighting: # Only add ori_length if weighting is True
edge_info["ori_length"].append(edge['ori_length'][i]) # Store the original length
G.add_edges(edge_list) # Add edges without attributes
for i in range(len(edge)):
G.es[i]["weight"] = edge_info["weight"][i]
G.es[i]["osmid"] = edge_info["osmid"][i]
if weighting: # Set the original length only if weighting is True
G.es[i]["ori_length"] = edge_info["ori_length"][i]
G.simplify(combine_edges=max)
return G
## Old
# def osm_to_ig(node, edge, weighting=None):
# """ Turns a node and edge dataframe into an igraph Graph. """
# G = ig.Graph(directed=False)
# # Print first few rows of edge dataframe
# print("First 5 edges with lengths and maxspeeds:")
# print(edge[['u', 'v', 'length', 'maxspeed']].head())
# x_coords = node['x'].tolist()
# y_coords = node['y'].tolist()
# ids = node['osmid'].tolist()
# coords = []
# for i in range(len(x_coords)):
# G.add_vertex(x=x_coords[i], y=y_coords[i], id=ids[i])
# coords.append((x_coords[i], y_coords[i]))
# id_dict = dict(zip(G.vs['id'], np.arange(0, G.vcount()).tolist()))
# coords_dict = dict(zip(np.arange(0, G.vcount()).tolist(), coords))
# edge_list = []
# edge_info = {"weight": [], "osmid": []}
# if weighting:
# print("Applying weighted calculation to edges.")
# for i in range(len(edge)):
# u, v = edge['u'][i], edge['v'][i]
# edge_list.append([id_dict.get(u), id_dict.get(v)])
# length = edge['length'][i]
# try:
# speed_limit = int(str(edge['maxspeed'][i]).split()[0]) if pd.notnull(edge['maxspeed'][i]) else 30
# except (ValueError, IndexError):
# speed_limit = 30
# weight = (length * (speed_limit / 10)) * 10000
# edge_info["weight"].append(round(weight, 10))
# edge_info["osmid"].append(edge['osmid'][i])
# else:
# print("Applying unweighted calculation to edges.")
# for i in range(len(edge)):
# edge_list.append([id_dict.get(edge['u'][i]), id_dict.get(edge['v'][i])])
# edge_info["weight"].append(round(edge['length'][i], 10))
# edge_info["osmid"].append(edge['osmid'][i])
# # Debug: Print edge list
# #print("Edge list:", edge_list)
# G.add_edges(edge_list)
# # Check that the edge count matches
# print(f"Number of edges in edge_list: {len(edge_list)}, edges in graph: {G.ecount()}")
# for i in range(len(edge_list)):
# G.es[i]["weight"] = edge_info["weight"][i]
# G.es[i]["osmid"] = edge_info["osmid"][i]
# # Debug: Print final edge weights
# print("Final edge weights after assignment:")
# print(G.es["weight"][:5]) # Check first few for validation
# G.simplify(combine_edges=max)
# # Assuming edges is a DataFrame or a list of your edges
# for index, edge in enumerate(edges.itertuples()):
# length = edge.length
# speed_limit = edge.maxspeed
# weight = length * (3600 / speed_limit) # Calculate the weight based on length and speed
# # Print only the first 15 edges
# if index < 15:
# print(f"Edge ID: {index}, Length: {length}, Speed limit: {speed_limit}, Calculated weight: {weight}")
# # Add the weight to the graph here
# return G
def compress_file(p, f, filetype = ".csv", delete_uncompressed = True):
with zipfile.ZipFile(p + f + ".zip", 'w', zipfile.ZIP_DEFLATED) as zfile:
zfile.write(p + f + filetype, f + filetype)
if delete_uncompressed: os.remove(p + f + filetype)
def ox_to_csv(G, p, placeid, parameterid, postfix = "", compress = True, verbose = True):
if "crs" not in G.graph:
G.graph["crs"] = 'epsg:4326' # needed for OSMNX's graph_to_gdfs in utils_graph.py
try:
node, edge = ox.graph_to_gdfs(G)
except ValueError:
node, edge = gpd.GeoDataFrame(), gpd.GeoDataFrame()
prefix = placeid + '_' + parameterid + postfix
node.to_csv(p + prefix + '_nodes.csv', index = True)
if compress: compress_file(p, prefix + '_nodes')
edge.to_csv(p + prefix + '_edges.csv', index = True)
if compress: compress_file(p, prefix + '_edges')
if verbose: print(placeid + ": Successfully wrote graph " + parameterid + postfix)
def check_extract_zip(p, prefix):
""" Check if a zip file prefix+'_nodes.zip' and + prefix+'_edges.zip'
is available at path p. If so extract it and return True, otherwise False.
If you call this function, remember to clean up (i.e. delete the unzipped files)
after you are done like this:
if compress:
os.remove(p + prefix + '_nodes.csv')
os.remove(p + prefix + '_edges.csv')
"""
try: # Use zip files if available
with zipfile.ZipFile(p + prefix + '_nodes.zip', 'r') as zfile:
zfile.extract(prefix + '_nodes.csv', p)
with zipfile.ZipFile(p + prefix + '_edges.zip', 'r') as zfile:
zfile.extract(prefix + '_edges.csv', p)
return True
except:
return False
def csv_to_ox(p, placeid, parameterid):
""" Load a networkx graph from _edges.csv and _nodes.csv
The edge file must have attributes u,v,osmid,length
The node file must have attributes y,x,osmid
Only these attributes are loaded.
"""
prefix = placeid + '_' + parameterid
compress = check_extract_zip(p, prefix)
with open(p + prefix + '_edges.csv', 'r') as f:
header = f.readline().strip().split(",")
lines = []
for line in csv.reader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True):
line_list = [c for c in line]
osmid = str(eval(line_list[header.index("osmid")])[0]) if isinstance(eval(line_list[header.index("osmid")]), list) else line_list[header.index("osmid")] # If this is a list due to multiedges, just load the first osmid
length = str(eval(line_list[header.index("length")])[0]) if isinstance(eval(line_list[header.index("length")]), list) else line_list[header.index("length")] # If this is a list due to multiedges, just load the first osmid
line_string = "" + line_list[header.index("u")] + " "+ line_list[header.index("v")] + " " + osmid + " " + length
lines.append(line_string)
G = nx.parse_edgelist(lines, nodetype = int, data = (("osmid", int),("length", float)), create_using = nx.MultiDiGraph) # MultiDiGraph is necessary for OSMNX, for example for get_undirected(G) in utils_graph.py
with open(p + prefix + '_nodes.csv', 'r') as f:
header = f.readline().strip().split(",")
values_x = {}
values_y = {}
for line in csv.reader(f, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True):
line_list = [c for c in line]
osmid = int(line_list[header.index("osmid")])
values_x[osmid] = float(line_list[header.index("x")])
values_y[osmid] = float(line_list[header.index("y")])
nx.set_node_attributes(G, values_x, "x")
nx.set_node_attributes(G, values_y, "y")
if compress:
os.remove(p + prefix + '_nodes.csv')
os.remove(p + prefix + '_edges.csv')
return G
def calculate_weight(row):
"""
Calculate new weight based on length and speed limit.
"""
# Default speed limit is 30 mph if 'maxspeed' is missing or NaN
if pd.isna(row['maxspeed']):
speed_factor = 3 # Corresponding to 30 mph
else:
speed_factor = int(str(row['maxspeed']).split()[0][0]) # Extract first digit from the speed.
# This presumes no speed limit over 99, which is reasonable for most roads.
# however this could produce issues in some countries with speed limits over 100 km/h?
# Multiply the speed factor by the length to get the new weight
return row['length'] * speed_factor
def csv_to_ig(p, placeid, parameterid, cleanup=True, weighting=None):
""" Load an ig graph from _edges.csv and _nodes.csv
The edge file must have attributes u,v,osmid,length
The node file must have attributes y,x,osmid
Only these attributes are loaded.
"""
prefix = placeid + '_' + parameterid
compress = check_extract_zip(p, prefix)
empty = False
try:
n = pd.read_csv(p + prefix + '_nodes.csv')
e = pd.read_csv(p + prefix + '_edges.csv')
except:
empty = True
if compress and cleanup and not SERVER: # Do not clean up on the server as csv is needed in parallel jobs
os.remove(p + prefix + '_nodes.csv')
os.remove(p + prefix + '_edges.csv')
if empty:
return ig.Graph(directed=False)
if weighting:
# Process the edges to modify length based on speed limits
e['maxspeed'] = e['maxspeed'].str.replace(' mph', '', regex=False).astype(float)
e['maxspeed'].fillna(20, inplace=True) # Assign default speed of 20 where NaN
e['ori_length'] = e['length'] # Store original length only if weighting is True
e['length'] = e['length'] * e['maxspeed'] # Modify the length based on speed
G = osm_to_ig(n, e, weighting) # Pass weighting to osm_to_ig
round_coordinates(G)
mirror_y(G)
return G
def ig_to_geojson(G):
linestring_list = []
for e in G.es():
linestring_list.append(geojson.LineString([(e.source_vertex["x"], -e.source_vertex["y"]), (e.target_vertex["x"], -e.target_vertex["y"])]))
G_geojson = geojson.GeometryCollection(linestring_list)
return G_geojson
# NETWORK GENERATION
def highest_closeness_node(G):
closeness_values = G.closeness(weights = 'weight')
sorted_closeness = sorted(closeness_values, reverse = True)
index = closeness_values.index(sorted_closeness[0])
return G.vs(index)['id']
def clusterindices_by_length(clusterinfo, rev = True):
return [k for k, v in sorted(clusterinfo.items(), key=lambda item: item[1]["length"], reverse = rev)]
class MyPoint:
def __init__(self,x,y):
self.x = x
self.y = y
def ccw(A,B,C):
return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)
def segments_intersect(A,B,C,D):
"""Check if two line segments intersect (except for colinearity)
Returns true if line segments AB and CD intersect properly.
Adapted from: https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect
"""
if (A.x == C.x and A.y == C.y) or (A.x == D.x and A.y == D.y) or (B.x == C.x and B.y == C.y) or (B.x == D.x and B.y == D.y): return False # If the segments share an endpoint they do not intersect properly
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
def new_edge_intersects(G, enew):
"""Given a graph G and a potential new edge enew,
check if enew will intersect any old edge.
"""
E1 = MyPoint(enew[0], enew[1])
E2 = MyPoint(enew[2], enew[3])
for e in G.es():
O1 = MyPoint(e.source_vertex["x"], e.source_vertex["y"])
O2 = MyPoint(e.target_vertex["x"], e.target_vertex["y"])
if segments_intersect(E1, E2, O1, O2):
return True
return False
def delete_overlaps(G_res, G_orig, verbose = False):
"""Deletes inplace all overlaps of G_res with G_orig (from G_res)
based on node ids. In other words: G_res -= G_orig
"""
del_edges = []
for e in list(G_res.es):
try:
n1_id = e.source_vertex["id"]
n2_id = e.target_vertex["id"]
# If there is already an edge in the original network, delete it
n1_index = G_orig.vs.find(id = n1_id).index
n2_index = G_orig.vs.find(id = n2_id).index
if G_orig.are_connected(n1_index, n2_index):
del_edges.append(e.index)
except:
pass
G_res.delete_edges(del_edges)
# Remove isolated nodes
isolated_nodes = G_res.vs.select(_degree_eq=0)
G_res.delete_vertices(isolated_nodes)
if verbose: print("Removed " + str(len(del_edges)) + " overlapping edges and " + str(len(isolated_nodes)) + " nodes.")
def constrict_overlaps(G_res, G_orig, factor = 5):
"""Increases length by factor of all overlaps of G_res with G_orig (in G_res) based on edge ids.
"""
for e in list(G_res.es):
try:
n1_id = e.source_vertex["id"]
n2_id = e.target_vertex["id"]
n1_index = G_orig.vs.find(id = n1_id).index
n2_index = G_orig.vs.find(id = n2_id).index
if G_orig.are_connected(n1_index, n2_index):
G_res.es[e.index]["weight"] = factor * G_res.es[e.index]["weight"]
except:
pass
def greedy_triangulation_routing_clusters(G, G_total, clusters, clusterinfo, prune_quantiles = [1], prune_measure = "betweenness", verbose = False, full_run = False):
"""Greedy Triangulation (GT) of a bike network G's clusters,
then routing on the graph G_total that includes car infra to connect the GT.
G and G_total are ipgraph graphs
The GT connects pairs of clusters in ascending order of their distance provided
that no edge crossing is introduced. It leads to a maximal connected planar
graph, while minimizing the total length of edges considered.
See: cardillo2006spp
Distance here is routing distance, while edge crossing is checked on an abstract
level.
"""
if len(clusters) < 2: return ([], []) # We can't do anything with less than 2 clusters
centroid_indices = [v["centroid_index"] for k, v in sorted(clusterinfo.items(), key=lambda item: item[1]["size"], reverse = True)]
G_temp = copy.deepcopy(G_total)
for e in G_temp.es: # delete all edges
G_temp.es.delete(e)
clusterpairs = clusterpairs_by_distance(G, G_total, clusters, clusterinfo, True, verbose, full_run)
if len(clusterpairs) == 0: return ([], [])
centroidpairs = [((clusterinfo[c[0][0]]['centroid_id'], clusterinfo[c[0][1]]['centroid_id']), c[2]) for c in clusterpairs]
GT_abstracts = []
GTs = []
for prune_quantile in prune_quantiles:
GT_abstract = copy.deepcopy(G_temp.subgraph(centroid_indices))
GT_abstract = greedy_triangulation(GT_abstract, centroidpairs, prune_quantile, prune_measure)
GT_abstracts.append(GT_abstract)
centroidids_closestnodeids = {} # dict for retrieveing quickly closest node ids pairs from centroidid pairs
for x in clusterpairs:
centroidids_closestnodeids[(clusterinfo[x[0][0]]["centroid_id"], clusterinfo[x[0][1]]["centroid_id"])] = (x[1][0], x[1][1])
centroidids_closestnodeids[(clusterinfo[x[0][1]]["centroid_id"], clusterinfo[x[0][0]]["centroid_id"])] = (x[1][1], x[1][0]) # also add switched version as we do not care about order
# Get node pairs we need to route, sorted by distance
routenodepairs = []
for e in GT_abstract.es:
# get the centroid-ids from closestnode-ids
routenodepairs.append([centroidids_closestnodeids[(e.source_vertex["id"], e.target_vertex["id"])], e["weight"]])
routenodepairs.sort(key=lambda x: x[1])
# Do the routing, on G_total
GT_indices = set()
for poipair, poipair_distance in routenodepairs:
poipair_ind = (G_total.vs.find(id = poipair[0]).index, G_total.vs.find(id = poipair[1]).index)
sp = set(G_total.get_shortest_paths(poipair_ind[0], poipair_ind[1], weights = "weight", output = "vpath")[0])
GT_indices = GT_indices.union(sp)
GT = G_total.induced_subgraph(GT_indices)
GTs.append(GT)
return(GTs, GT_abstracts)
def clusterpairs_by_distance(G, G_total, clusters, clusterinfo, return_distances = False, verbose = False, full_run = False):
"""Calculates the (weighted) graph distances on G for a number of clusters.
Returns all pairs of cluster ids and closest nodes in ascending order of their distance.
If return_distances, then distances are also returned.
Returns a list containing these elements, sorted by distance:
[(clusterid1, clusterid2), (closestnodeid1, closestnodeid2), distance]
"""
cluster_indices = clusterindices_by_length(clusterinfo, False) # Start with the smallest so the for loop is as short as possible
clusterpairs = []
clustercopies = {}
# Create copies of all clusters
for i in range(len(cluster_indices)):
clustercopies[i] = clusters[i].copy()
# Take one cluster
for i, c1 in enumerate(cluster_indices[:-1]):
c1_indices = G_total.vs.select(lambda x: x["id"] in clustercopies[c1].vs()["id"]).indices
print("Working on cluster " + str(i+1) + " of " + str(len(cluster_indices)) + "...")
for j, c2 in enumerate(cluster_indices[i+1:]):
closest_pair = {'i': -1, 'j': -1}
min_dist = np.inf
c2_indices = G_total.vs.select(lambda x: x["id"] in clustercopies[c2].vs()["id"]).indices
if verbose: print("... routing " + str(len(c1_indices)) + " nodes to " + str(len(c2_indices)) + " nodes in other cluster " + str(j+1) + " of " + str(len(cluster_indices[i+1:])) + ".")
if full_run:
# Compare all pairs of nodes in both clusters (takes long)
for a in list(c1_indices):
sp = G_total.get_shortest_paths(a, c2_indices, weights = "weight", output = "epath")
if all([not elem for elem in sp]):
# If there is no path from one node, there is no path from any node
break
else:
for path, c2_index in zip(sp, c2_indices):
if len(path) >= 1:
dist_nodes = sum([G_total.es[e]['weight'] for e in path])
if dist_nodes < min_dist:
closest_pair['i'] = G_total.vs[a]["id"]
closest_pair['j'] = G_total.vs[c2_index]["id"]
min_dist = dist_nodes
else:
# Do a heuristic that should be close enough.
# From cluster 1, look at all shortest paths only from its centroid
a = clusterinfo[c1]["centroid_index"]
sp = G_total.get_shortest_paths(a, c2_indices, weights = "weight", output = "epath")
if all([not elem for elem in sp]):
# If there is no path from one node, there is no path from any node
break
else:
for path, c2_index in zip(sp, c2_indices):
if len(path) >= 1:
dist_nodes = sum([G_total.es[e]['weight'] for e in path])
if dist_nodes < min_dist:
closest_pair['j'] = G_total.vs[c2_index]["id"]
min_dist = dist_nodes
# Closest c2 node to centroid1 found. Now find all c1 nodes to that closest c2 node.
b = G_total.vs.find(id = closest_pair['j']).index
sp = G_total.get_shortest_paths(b, c1_indices, weights = "weight", output = "epath")
if all([not elem for elem in sp]):
# If there is no path from one node, there is no path from any node
break
else:
for path, c1_index in zip(sp, c1_indices):
if len(path) >= 1:
dist_nodes = sum([G_total.es[e]['weight'] for e in path])
if dist_nodes <= min_dist: # <=, not <!
closest_pair['i'] = G_total.vs[c1_index]["id"]
min_dist = dist_nodes
if closest_pair['i'] != -1 and closest_pair['j'] != -1:
clusterpairs.append([(c1, c2), (closest_pair['i'], closest_pair['j']), min_dist])
clusterpairs.sort(key = lambda x: x[-1])
if return_distances:
return clusterpairs
else:
return [[o[0], o[1]] for o in clusterpairs]
def mst_routing(G, pois, weighting=None):
"""Minimum Spanning Tree (MST) of a graph G's node subset pois,
then routing to connect the MST.
G is an ipgraph graph, pois is a list of node ids.
The MST is the planar graph with the minimum number of (weighted)
links in order to assure connectedness.
Distance here is routing distance, while edge crossing is checked on an abstract
level.
"""
if len(pois) < 2: return (ig.Graph(), ig.Graph()) # We can't do anything with less than 2 POIs
# MST_abstract is the MST with same nodes but euclidian links
pois_indices = set()
for poi in pois:
pois_indices.add(G.vs.find(id = poi).index)
G_temp = copy.deepcopy(G)
for e in G_temp.es: # delete all edges
G_temp.es.delete(e)
poipairs = poipairs_by_distance(G, pois, weighting, True)
if len(poipairs) == 0: return (ig.Graph(), ig.Graph())
MST_abstract = copy.deepcopy(G_temp.subgraph(pois_indices))
for poipair, poipair_distance in poipairs:
poipair_ind = (MST_abstract.vs.find(id = poipair[0]).index, MST_abstract.vs.find(id = poipair[1]).index)
MST_abstract.add_edge(poipair_ind[0], poipair_ind[1] , weight = poipair_distance)
MST_abstract = MST_abstract.spanning_tree(weights = "weight")
# Get node pairs we need to route, sorted by distance
routenodepairs = {}
for e in MST_abstract.es:
routenodepairs[(e.source_vertex["id"], e.target_vertex["id"])] = e["weight"]
routenodepairs = sorted(routenodepairs.items(), key = lambda x: x[1])
# Do the routing
MST_indices = set()
for poipair, poipair_distance in routenodepairs:
poipair_ind = (G.vs.find(id = poipair[0]).index, G.vs.find(id = poipair[1]).index)
sp = set(G.get_shortest_paths(poipair_ind[0], poipair_ind[1], weights = "weight", output = "vpath")[0])
MST_indices = MST_indices.union(sp)
MST = G.induced_subgraph(MST_indices)
return (MST, MST_abstract)
def greedy_triangulation(GT, poipairs, prune_quantile = 1, prune_measure = "betweenness", edgeorder = False):
"""Greedy Triangulation (GT) of a graph GT with an empty edge set.
Distances between pairs of nodes are given by poipairs.
The GT connects pairs of nodes in ascending order of their distance provided
that no edge crossing is introduced. It leads to a maximal connected planar
graph, while minimizing the total length of edges considered.
See: cardillo2006spp
"""
for poipair, poipair_distance in poipairs:
poipair_ind = (GT.vs.find(id = poipair[0]).index, GT.vs.find(id = poipair[1]).index)
if not new_edge_intersects(GT, (GT.vs[poipair_ind[0]]["x"], GT.vs[poipair_ind[0]]["y"], GT.vs[poipair_ind[1]]["x"], GT.vs[poipair_ind[1]]["y"])):
GT.add_edge(poipair_ind[0], poipair_ind[1], weight = poipair_distance)
# Get the measure for pruning
if prune_measure == "betweenness":
BW = GT.edge_betweenness(directed = False, weights = "weight")
qt = np.quantile(BW, 1-prune_quantile)
sub_edges = []
for c, e in enumerate(GT.es):
if BW[c] >= qt:
sub_edges.append(c)
GT.es[c]["bw"] = BW[c]
GT.es[c]["width"] = math.sqrt(BW[c]+1)*0.5
# Prune
GT = GT.subgraph_edges(sub_edges)
elif prune_measure == "closeness":
CC = GT.closeness(vertices = None, weights = "weight")
qt = np.quantile(CC, 1-prune_quantile)
sub_nodes = []
for c, v in enumerate(GT.vs):
if CC[c] >= qt:
sub_nodes.append(c)
GT.vs[c]["cc"] = CC[c]
GT = GT.induced_subgraph(sub_nodes)
elif prune_measure == "random":
ind = np.quantile(np.arange(len(edgeorder)), prune_quantile, interpolation = "lower") + 1 # "lower" and + 1 so smallest quantile has at least one edge
GT = GT.subgraph_edges(edgeorder[:ind])
return GT
def restore_original_lengths(G):
"""Restore original lengths from the 'ori_length' attribute."""
for e in G.es:
e["weight"] = e["ori_length"]
def greedy_triangulation_routing(G, pois, weighting=None, prune_quantiles = [1], prune_measure = "betweenness"):
"""Greedy Triangulation (GT) of a graph G's node subset pois,
then routing to connect the GT (up to a quantile of betweenness
betweenness_quantile).
G is an ipgraph graph, pois is a list of node ids.
The GT connects pairs of nodes in ascending order of their distance provided
that no edge crossing is introduced. It leads to a maximal connected planar
graph, while minimizing the total length of edges considered.
See: cardillo2006spp
Distance here is routing distance, while edge crossing is checked on an abstract
level.
"""
if len(pois) < 2: return ([], []) # We can't do anything with less than 2 POIs
# GT_abstract is the GT with same nodes but euclidian links to keep track of edge crossings
pois_indices = set()
for poi in pois:
pois_indices.add(G.vs.find(id = poi).index)
G_temp = copy.deepcopy(G)
for e in G_temp.es: # delete all edges
G_temp.es.delete(e)
poipairs = poipairs_by_distance(G, pois, weighting, True)
if len(poipairs) == 0: return ([], [])
if prune_measure == "random":
# run the whole GT first
GT = copy.deepcopy(G_temp.subgraph(pois_indices))
for poipair, poipair_distance in poipairs:
poipair_ind = (GT.vs.find(id = poipair[0]).index, GT.vs.find(id = poipair[1]).index)
if not new_edge_intersects(GT, (GT.vs[poipair_ind[0]]["x"], GT.vs[poipair_ind[0]]["y"], GT.vs[poipair_ind[1]]["x"], GT.vs[poipair_ind[1]]["y"])):
GT.add_edge(poipair_ind[0], poipair_ind[1], weight = poipair_distance)
# create a random order for the edges
random.seed(0) # const seed for reproducibility
edgeorder = random.sample(range(GT.ecount()), k = GT.ecount())
else:
edgeorder = False
GT_abstracts = []
GTs = []
for prune_quantile in tqdm(prune_quantiles, desc = "Greedy triangulation", leave = False):
GT_abstract = copy.deepcopy(G_temp.subgraph(pois_indices))
GT_abstract = greedy_triangulation(GT_abstract, poipairs, prune_quantile, prune_measure, edgeorder)
GT_abstracts.append(GT_abstract)
# Get node pairs we need to route, sorted by distance
routenodepairs = {}
for e in GT_abstract.es:
routenodepairs[(e.source_vertex["id"], e.target_vertex["id"])] = e["weight"]
routenodepairs = sorted(routenodepairs.items(), key = lambda x: x[1])
# Do the routing
GT_indices = set()
for poipair, poipair_distance in routenodepairs:
poipair_ind = (G.vs.find(id = poipair[0]).index, G.vs.find(id = poipair[1]).index)
# debug
#print(f"Edge weights before routing: {G.es['weight'][:10]}") # Prints first 10 weights
#print(f"Routing between: {poipair[0]} and {poipair[1]} with distance: {poipair_distance}")
sp = set(G.get_shortest_paths(poipair_ind[0], poipair_ind[1], weights = "weight", output = "vpath")[0])
#print(f"Shortest path between {poipair[0]} and {poipair[1]}: {sp}")
GT_indices = GT_indices.union(sp)
GT = G.induced_subgraph(GT_indices)
GTs.append(GT)
return (GTs, GT_abstracts)
def poipairs_by_distance(G, pois, weighting=None, return_distances = False):
"""Calculates the (weighted) graph distances on G for a subset of nodes pois.
Returns all pairs of poi ids in ascending order of their distance.
If return_distances, then distances are also returned.
If we are using a weighted graph, we need to calculate the distances using orignal
edge lengths rather than adjusted weighted lengths.
"""
# Get poi indices
indices = []
for poi in pois:
indices.append(G_carall.vs.find(id = poi).index)
# Get sequences of nodes and edges in shortest paths between all pairs of pois
poi_nodes = []
poi_edges = []
for c, v in enumerate(indices):
poi_nodes.append(G.get_shortest_paths(v, indices[c:], weights = "weight", output = "vpath"))
poi_edges.append(G.get_shortest_paths(v, indices[c:], weights = "weight", output = "epath"))
# Sum up weights (distances) of all paths
poi_dist = {}
for paths_n, paths_e in zip(poi_nodes, poi_edges):
for path_n, path_e in zip(paths_n, paths_e):
# Sum up distances of path segments from first to last node
if weighting:
# Use the 'weight' for finding the shortest path
path_dist = sum([G.es[e]['ori_length'] for e in path_e]) # Use 'ori_length' for distance
else:
path_dist = sum([G.es[e]['weight'] for e in path_e]) # Fallback to 'weight' if weighting is False
if path_dist > 0:
poi_dist[(path_n[0], path_n[-1])] = path_dist
temp = sorted(poi_dist.items(), key = lambda x: x[1])
# Back to ids
output = []
for p in temp:
output.append([(G.vs[p[0][0]]["id"], G.vs[p[0][1]]["id"]), p[1]])
if return_distances:
return output
else:
return [o[0] for o in output]
# ANALYSIS
def rotate_grid(p, origin = (0, 0), degrees = 0):
"""Rotate a list of points around an origin (in 2D).
Parameters:
p (tuple or list of tuples): (x,y) coordinates of points to rotate
origin (tuple): (x,y) coordinates of rotation origin
degrees (int or float): degree (clockwise)
Returns:
ndarray: the rotated points, as an ndarray of 1x2 ndarrays
"""
# https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python
angle = np.deg2rad(-degrees)
R = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
o = np.atleast_2d(origin)
p = np.atleast_2d(p)
return np.squeeze((R @ (p.T-o.T) + o.T).T)
# Two functions from: https://github.com/gboeing/osmnx-examples/blob/v0.11/notebooks/17-street-network-orientations.ipynb
def reverse_bearing(x):
return x + 180 if x < 180 else x - 180
def count_and_merge(n, bearings):
# make twice as many bins as desired, then merge them in pairs
# prevents bin-edge effects around common values like 0° and 90°
n = n * 2
bins = np.arange(n + 1) * 360 / n
count, _ = np.histogram(bearings, bins=bins)
# move the last bin to the front, so eg 0.01° and 359.99° will be binned together
count = np.roll(count, 1)
return count[::2] + count[1::2]
def calculate_directness(G, numnodepairs = 500):
"""Calculate directness on G over all connected node pairs in indices. This calculation method divides the total sum of euclidian distances by total sum of network distances.
"""
indices = random.sample(list(G.vs), min(numnodepairs, len(G.vs)))
poi_edges = []
total_distance_direct = 0
for c, v in enumerate(indices):
poi_edges.append(G.get_shortest_paths(v, indices[c:], weights = "weight", output = "epath"))
temp = G.get_shortest_paths(v, indices[c:], weights = "weight", output = "vpath")
try:
total_distance_direct += sum(dist_vector([(G.vs[t[0]]["y"], G.vs[t[0]]["x"]) for t in temp], [(G.vs[t[-1]]["y"], G.vs[t[-1]]["x"]) for t in temp])) # must be in format lat,lon = y, x
except: # Rarely, routing does not work. Unclear why.
pass
total_distance_network = 0
for paths_e in poi_edges:
for path_e in paths_e:
# Sum up distances of path segments from first to last node
total_distance_network += sum([G.es[e]['weight'] for e in path_e])
return total_distance_direct / total_distance_network
def calculate_directness_linkwise(G, numnodepairs = 500):
"""Calculate directness on G over all connected node pairs in indices. This is maybe the common calculation method: It takes the average of linkwise euclidian distances divided by network distances.
If G has multiple components, node pairs in different components are discarded.
"""
indices = random.sample(list(G.vs), min(numnodepairs, len(G.vs)))
directness_links = np.zeros(int((len(indices)*(len(indices)-1))/2))
ind = 0
for c, v in enumerate(indices):
poi_edges = G.get_shortest_paths(v, indices[c:], weights = "weight", output = "epath")
for c_delta, path_e in enumerate(poi_edges[1:]): # Discard first empty list because it is the node to itself
if path_e: # if path is non-empty, meaning the node pair is in the same component