-
Notifications
You must be signed in to change notification settings - Fork 0
/
FireABM_opt_Keel.py
1601 lines (1362 loc) · 72.2 KB
/
FireABM_opt_Keel.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
import osmnx as ox
import numpy as np
import pandas as pd
import geopandas as gpd
import shapely
from shapely.geometry import Point, LineString
from collections import deque, Counter
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as patches
import matplotlib.collections as collections
import matplotlib.lines as mp_lines
from IPython.display import HTML
import networkx as nx
from networkx.utils import generate_unique_node
import random
import copy
import ipywidgets as widgets
from traitlets import traitlets
import os
import csv
import time
import math
import pytz
from datetime import datetime
from heapq import heappush, heappop
from itertools import count
#plt.rcParams['animation.writer']='avconv'
plt.rcParams['animation.writer']='ffmpeg'
DEFAULT_VEHICLE_LENGTH=3 #meters, couting from the head of the vehicle, no other vehicles after [length] meters
DEFAULT_ROAD_LANES=1 # For viz puporses (and convenience), limiting road_lanes to 1. Different lanes could be modeled as different keys of the same i,j
DEFAULT_ROAD_SPEED=15 # m/s, ~35 mph
time_zone = pytz.timezone('America/Chicago')
seed_number = None
def set_seeds(in_seed_number): # sets seed for reproducibility, both python and numpy random generators used
np.random.seed(in_seed_number)
random.seed(in_seed_number)
global seed_number
seed_number = in_seed_number
return seed_number
def check_seed():
print (seed_number)
def gen_seeds(tot_size, sel_size, seed_number):
seeds = []
np.random.seed(seed_number)
while len(seeds) < sel_size:
r = np.random.randint(tot_size)
if r not in seeds:
seeds.append(r)
return seeds
def time_stamp(start_time=None):
print(datetime.now(time_zone).strftime("%H:%M:%S"))
if start_time == None:
return time.time()
else:
return abm_timer(start_time, time.time())
def abm_timer(start, end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
def setup_sim(g, seed=51, no_seed=False):
fig, ax = ox.plot_graph(g, node_size=0, figsize=(18, 15), show=False) #keel w=~h*1.2, remove margin
fig.tight_layout()
if not no_seed:
set_seeds(seed)
return fig, ax
def str_replace_mult(string, rep_list):
for r in rep_list:
string = string.replace(*r)
return string
def mph2ms(mph):
return mph*0.44704
def dist2(a,b):
dx=a[0]-b[0]
dy=a[1]-b[1]
return dx*dx+dy*dy
def get_node_edge_gdf(g):
nodes = ox.graph_to_gdfs(g, nodes=True, edges=False)
edges = ox.graph_to_gdfs(g, nodes=False, edges=True)
return(nodes, edges)
def load_road_graph(pkl_file):
g = nx.read_gpickle(path=pkl_file)
return g
def create_bboxes(gdf_nodes, buffer_pct=0.15, buff_adj=None):
if buff_adj:
xposadj, xnegadj, yposadj, ynegadj = buff_adj[0], buff_adj[1], buff_adj[2], buff_adj[3]
else:
xposadj, xnegadj, yposadj, ynegadj = 1, 1, 1, 1
# find buffer in xy coordinates to use in map
xbuff = (max(gdf_nodes['x']) - min(gdf_nodes['x'])) * buffer_pct
ybuff = (max(gdf_nodes['y']) - min(gdf_nodes['y'])) * buffer_pct
bbox = [min(gdf_nodes['x']) + (xbuff*xposadj), min(gdf_nodes['y']) + (ybuff*yposadj),
max(gdf_nodes['x']) - (xbuff*xnegadj), max(gdf_nodes['y']) - (ybuff*ynegadj)]
# find buffer in lat/long to use in simulation
latbuff = (max(gdf_nodes['lat']) - min(gdf_nodes['lat'])) * buffer_pct
lonbuff = (max(gdf_nodes['lon']) - min(gdf_nodes['lon'])) * buffer_pct
lbbox = [min(gdf_nodes['lon']) + (lonbuff*xposadj), min(gdf_nodes['lat']) + (latbuff*yposadj),
max(gdf_nodes['lon']) - (lonbuff*xnegadj), max(gdf_nodes['lat']) - (latbuff*ynegadj)]
# fill out coordinates into a rectangle and extract xy for plotting
poly = shapely.geometry.box(*bbox)
x,y = poly.exterior.xy
return (bbox, lbbox, poly, x, y)
def check_graphs(gdf_edges, x=None, y=None, shpfile=None, is_fire=True, zorder=4, figsize=(8,8)):
fig, ax = plt.subplots(figsize=figsize)
gdf_edges.plot(ax=ax)
if x and y:
ax.plot(x, y, color='red', alpha=0.7, linewidth=3, solid_capstyle='round', zorder=2)
if shpfile is not None:
if is_fire:
shpfile.plot(column="SimTime", ax=ax, zorder=zorder)
else:
shpfile.plot(ax=ax, cmap='Greens', zorder=zorder)
return (fig, ax)
def inspect(g, nid, mid=None, radius=300, showMap=False, fullMap=True): # Becky add g, showMap
#if 'x' in g.nodes[nid]: # Becky added if statement, fix graph
# loc=(g.nodes[nid]['y'],g.nodes[nid]['x'])
#else:
#loc=(g.nodes[nid]['lat'],g.nodes[nid]['lon']) # Becky change y, x to lat, lon
if nid is not None:
loc=(g.nodes[nid]['lat'],g.nodes[nid]['lon']) # Becky change y, x to lat, lon
if fullMap:
t=g
else:
t=ox.graph_from_point(loc, distance=radius, distance_type='bbox', network_type='drive')
if not mid:
nc = ['r' if node==nid else '#336699' for node in t.nodes()]
ns = [50 if node==nid else 8 for node in t.nodes()]
ox.plot_graph(t,node_size=ns,node_color=nc,node_zorder=2)
if showMap: # Becky add showMap logic
return ox.plot_graph_folium(t)
else:
ec = ['r' if u==nid and v==mid else '#336699' for u, v, key, data in t.edges(keys=True, data=True)]
es = [3 if u==nid and v==mid else 1 for u, v, key, data in t.edges(keys=True, data=True)]
ox.plot_graph(t, node_size=30, edge_color=ec, edge_linewidth=es, edge_alpha=0.5)
if showMap: # Becky add showMap logic
return ox.plot_graph_folium(t)
def highlight(g,edgelist,showMap=False):
ec = ['r' if (u,v,key) in edgelist else '#336699' for u, v, key in g.edges(keys=True)]
es = [3 if (u,v,key) in edgelist else 1 for u, v,key in g.edges(keys=True)]
ox.plot_graph(g, node_size=30, edge_color=ec, edge_linewidth=es, edge_alpha=0.5)
if showMap:
return ox.plot_graph_folium(g)
class LoadedButton(widgets.Button):
"""A button that can holds a value as a attribute."""
def __init__(self, value=None, *args, **kwargs):
super(LoadedButton, self).__init__(*args, **kwargs)
# Create the value attribute.
self.add_traits(value=traitlets.Any(value))
def select_nearest_node(g, show_info=False):
global fig, ax
fig, ax = ox.plot_graph(g, node_size=30, edge_alpha=0.5)
global coords
coords = [None, None]
global near_node_id
near_node_id = None
def print_coords(button_inst):
if show_info:
print (coords)
def print_node_id(button_inst):
if show_info:
print (near_node_id)
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
global coords
coords = (ix, iy)
revcords = (iy, ix)
global near_node_id
near_node_id = ox.geo_utils.get_nearest_node(g, revcords, method='euclidean')
print(near_node_id)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
cords_button = LoadedButton(description='Get coordinates!')
cords_button.on_click(print_coords)
display(cords_button)
node_button = LoadedButton(description='Get node!')
node_button.on_click(print_node_id)
display(node_button)
def view_node_attrib(g, attrib, show_null=False):
if attrib == 'culdesacs':
culdesacs = [key for key, value in g.graph['streets_per_node'].items() if value==1]
nc = ['r' if node in culdesacs else 'none' for node in g.nodes()]
ox.plot_graph(g, node_color=nc)
def view_edge_attrib(g, attrib, figsize=(10, 8), show_null=False, show_edge_values=False, edge_value_rm=None, show_val=False, val=None, num_bins=5, set_range=None, breaks=None, set_colors=None, node_size=5): #keel
gdf_edges = ox.graph_to_gdfs(g, nodes=False, edges=True)
if attrib in gdf_edges:
print('Attribute: '+attrib+', Type: '+str(gdf_edges[attrib].dtype))
elw = [1 for u, v, key, data in g.edges(keys=True, data=True)]
legend_items = {'colors':[], 'names':[]}
if show_null:
ec = ['red' if attrib not in data else 'grey' for u, v, key, data in g.edges(keys=True, data=True)]
legend_items['colors'] = ['red', 'grey']
legend_items['names'] = ['Null attribute', 'Attribute exists']
elif set_range:
if set_colors:
colors = set_colors
else:
colors = ox.get_colors(len(set_range), cmap=cmap)
ec = []
elw = []
for u, v, key, data in g.edges(keys=True, data=True):
included = False
for rindx, range_ele in enumerate(set_range):
if data[attrib] > range_ele[0] and data[attrib] < range_ele[1]:
ec.append(colors[rindx])
included = True
elw.append(3)
if included == False:
ec.append('grey')
elw.append(1)
legend_items['colors'] = colors
legend_items['names'] = [str(rng[0])+'-'+str(rng[1]) for rng in set_range]
elif show_val:
if isinstance(val, str):
ec = ['red' if data[attrib] == val else 'grey' for u, v, key, data in g.edges(keys=True, data=True)]
legend_items['colors'] = ['red', 'grey']
legend_items['names'] = [val, 'not '+str(val)]
else:
cats = list(range(len(val)))
cat_names = val
colors = ox.get_colors(len(val), cmap=cmap)
ec = [colors[val.index(data[attrib])] if data[attrib] in val else 'grey' for u, v, key, data in g.edges(keys=True, data=True)]
legend_items['colors'] = colors
legend_items['names'] = list(cat_names)
if len(colors) > len(cat_names):
legend_items['names'].append('Not in list')
else:
if gdf_edges[attrib].dtype in ['int64', 'float64', 'float', 'int'] and attrib is not 'key':
print('min', round(gdf_edges[attrib].min(), 2), 'max', round(gdf_edges[attrib].max(), 2))
ec, colors, bins = get_edge_colors_by_attr(g, attr=attrib, num_bins=num_bins, cmap=cmap, bin_cuts=breaks)
#print('c and b', colors, bins)
legend_items['colors'] = colors
for indx in range(len(colors)):
leg_item = str(round(bins[indx], 2)) + " - " + str(round(bins[indx+1], 2))
legend_items['names'].append(leg_item)
elif gdf_edges[attrib].dtype == 'O' or attrib is 'key':
edge_series = copy.deepcopy(gdf_edges[attrib])
for index, edgs in enumerate(edge_series):
if type(edgs) == list:
edge_series[index] = edgs[0]
cats = edge_series.astype("category").cat.codes
cat_names = edge_series.astype("category").cat.categories
colors = ox.get_colors(len(edge_series.unique()), cmap=cmap)
ec = [colors[int(cat)] if pd.notnull(cat) else na_color for cat in cats]
legend_items['colors'] = colors
legend_items['names'] = list(cat_names)
if len(colors) > len(cat_names):
legend_items['names'].append('Null')
else:
try:
cats = gdf_edges[attrib].astype("category").cat.codes
cat_names = gdf_edges[attrib].astype("category").cat.categories
colors = ox.get_colors(len(gdf_edges[attrib].unique()), cmap=cmap)
ec = [colors[int(cat)] if pd.notnull(cat) else na_color for cat in cats]
legend_items['colors'] = colors
legend_items['names'] = list(cat_names)
if len(colors) > len(cat_names):
legend_items['names'].append('Null')
except:
ec = 'blue'
legend_items['colors'] = ['blue']
legend_items['names'] = ['Unable to parse variable']
if show_edge_values:
fig_size = (24, 20) #keel
fig, ax = ox.plot_graph(g, figsize=fig_size, node_size=node_size, edge_color=ec, edge_alpha=0.5, edge_linewidth=elw, show=False, close=False) #keel
if show_edge_values:
for index, row in gdf_edges.iterrows():
if attrib in row:
edge_val_txt = str(row[attrib])
if edge_val_txt != 'nan':
if edge_value_rm:
for repl in edge_value_rm:
edge_val_txt = edge_val_txt.replace(repl, '')
plt.text(row.geometry.centroid.x, row.geometry.centroid.y, edge_val_txt, zorder=4)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height * 0.8])
proxies = [make_proxy(item, linewidth=5) for item in legend_items['colors']]
ax.legend(proxies, legend_items['names'], loc='center left', bbox_to_anchor=(1, 0.5))
#plt.show()
return (fig, ax)
else:
print('attribute not found in edges')
# adapted from https://stackoverflow.com/questions/19877666/add-legends-to-linecollection-plot/19881647#19881647
def make_proxy(color, **kwargs):
return mp_lines.Line2D([0, 1], [0, 1], color=color, **kwargs)
def get_edge_colors_by_attr(g, attr, num_bins=5, cmap='viridis', start=0, stop=1, na_color='none', bin_cuts=None): #overloaded osnmx function (support both continuous and non continuous vars)
if num_bins is None:
num_bins=len(g.edges())
if bin_cuts:
num_bins = len(bin_cuts)+1
bin_labels = range(num_bins)
attr_values = pd.Series([data[attr] for u, v, key, data in g.edges(keys=True, data=True)])
try:
if not bin_cuts:
cats, bins = pd.qcut(x=attr_values, q=num_bins, labels=bin_labels, retbins=True)
else:
print('bin_cuts!!', bin_cuts)
cats, bins = pd.cut(x=attr_values, bins=bin_cuts, labels=bin_labels, retbins=True)
except: #added to support non continuous vars
cats, bins = pd.cut(x=attr_values, bins=num_bins, labels=bin_labels, retbins=True)
colors = ox.get_colors(num_bins, cmap, start, stop)
edge_colors = [colors[int(cat)] if pd.notnull(cat) else na_color for cat in cats]
return edge_colors, colors, bins
def load_shpfile(g, path_list):
in_file = gpd.read_file(os.path.join(*path_list))
ox_crs = find_UTM_crs(g.nodes[list(g.nodes)[0]]['lat'], g.nodes[list(g.nodes)[0]]['lon'])
prj_file = in_file.to_crs(ox_crs)
return prj_file
def show_fire(g, fire_perim, show_graph=True, sim_time_num=None): #Becky added
if sim_time_num:
fire_perim = fire_perim[fire_perim["SimTime"]==sim_time_num]
if show_graph == True:
fig, ax = ox.plot_graph(g, node_size=30, edge_alpha=0.5, show=False, axis_off=False, close=False)
fire_perim.plot(ax=ax, cmap='YlOrRd', alpha=0.1, zorder=4)
fire_perim.boundary.plot(ax=ax, color='grey', alpha=0.75, zorder=4)
else:
fire_perim.plot(cmap='YlOrRd', alpha=0.2, edgecolor='grey')
plt.show()
def show_shpfile(g, shpfile, show_graph=True, is_fire=True, sim_time_num=None): #Becky added
if is_fire:
if sim_time_num:
shpfile = shpfile[shpfile["SimTime"]==sim_time_num]
if show_graph == True:
fig, ax = ox.plot_graph(g, node_size=30, edge_alpha=0.5, show=False, axis_off=False, close=False)
shpfile.plot(ax=ax, cmap='YlOrRd', alpha=0.1, zorder=4)
shpfile.boundary.plot(ax=ax, color='grey', alpha=0.75, zorder=4)
else:
shpfile.plot(cmap='YlOrRd', alpha=0.2, edgecolor='grey')
plt.show()
def convert_fire_time(fire_perim, spread_num=None, sim_time_num=None, length=False):
fire_list = sorted(list(set(fire_perim["SimTime"])))
if spread_num:
if spread_num < len(fire_list):
return fire_list[spread_num]
else:
print('index out of range for fire_list')
elif sim_time_num:
if sim_time_num in fire_list:
return fire_list.index(sim_time_num)
else:
print('fire_list not in index')
elif length:
return len(fire_list)
else:
return fire_list
def setup_graph(g): # Becky added
fig, ax = ox.plot_graph(g, node_size=0, figsize=(18,15), show=False) #keel
fig.tight_layout()
return fig, ax
def resolve_deadend(g):
deadEnds=[e for e in g.edges(keys=True,data=True) if len(g.adj[e[1]])==0] # Becky update fix
for d in deadEnds:
g.add_edge(d[1],d[0],key=0)
return g
def fillPhantom(g):
for e in g.edges(keys=True, data=True):
if 'geometry' not in e[3]:
u=e[0]
v=e[1]
e[3]['geometry']=LineString([Point(g.nodes[u]['x'],g.nodes[u]['y']), Point(g.nodes[v]['x'],g.nodes[v]['y'])])
return g
def adjustLength(g):
for e in g.edges(keys=True, data=True):
if 'geometry' in e[3]:
e[3]['length']=e[3]['geometry'].length
return g
def add_unit_speed(g): # Becky add for routing
for e in g.edges(keys=True, data=True):
if 'maxspeed' in e[3]:
s = e[3]['maxspeed']
if type(s) == list:
s = s[0]
# sm = mph2ms(int(s[:2]))
e[3]['speed'] = mph2ms(int(s[:2])) ## -> Quickest
if e[3]['speed'] > 0:
e[3]['seg_time']=e[3]['length'] / e[3]['speed']
else:
e[3]['seg_time']=e[3]['length'] / DEFAULT_ROAD_SPEED
e[3]['speed'] = DEFAULT_ROAD_SPEED
else:
e[3]['seg_time']=e[3]['length'] / DEFAULT_ROAD_SPEED
e[3]['speed'] = DEFAULT_ROAD_SPEED
e[3]['ett'] = e[3]['length'] / e[3]['speed'] ## -> Quickest
return g
def add_road_type_weights(g, rt_weights=[1, 1, 5, 10, 15, 20, 20]): # Becky add for routing
# https://wiki.openstreetmap.org/wiki/Key:highway
for e in g.edges(keys=True, data=True):
if 'highway' in e[3]:
rt = e[3]['highway']
if rt in ['motorway', 'motorway_link']:
e[3]['rt_weight']=rt_weights[0]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[0]
elif rt in ['trunk', 'trunk_link']:
e[3]['rt_weight']=rt_weights[1]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[1]
elif rt in ['primary', 'primary_link']:
e[3]['rt_weight']=rt_weights[2]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[2]
elif rt in ['secondary', 'secondary_link']:
e[3]['rt_weight']=rt_weights[3]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[3]
elif rt in ['tertiary', 'tertiary_link']:
e[3]['rt_weight']=rt_weights[4]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[4]
elif rt == 'unclassified':
e[3]['rt_weight']=rt_weights[5]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[5]
elif rt == 'residential':
e[3]['rt_weight']=rt_weights[6]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[6]
else:
e[3]['rt_weight']=rt_weights[5]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[5]
else:
e[3]['rt_weight']=rt_weights[5]
e[3]['rt_weighted_len']=e[3]['length']*rt_weights[5]
return g
def add_households(g, hh_shp, shp_name, hh_col_name, cut_off_len=10, num_col=10, bbox_poly=None): # Becky add for placing vehicles
gdf_edges = ox.graph_to_gdfs(g, nodes=False, edges=True)
edges_with_hhs = gpd.sjoin(gdf_edges, hh_shp, how="inner", op='intersects')
name_list = [shp_name[:cut_off_len-(len(str(i))+1)]+"_"+str(i) for i in range(1, num_col)]
name_list.append(shp_name[:cut_off_len])
for col_name in [d_name for d_name in name_list if d_name in edges_with_hhs.columns and d_name != hh_col_name]:
edges_with_hhs = edges_with_hhs.drop([col_name], axis=1)
hh_dict = {}
tract_dict = {}
for i in list(zip(edges_with_hhs['u'], edges_with_hhs['v'], edges_with_hhs['key'], edges_with_hhs[hh_col_name])):
hh_dict[(i[0], i[1], i[2])] = i[3]
for i in list(zip(edges_with_hhs['u'], edges_with_hhs['v'], edges_with_hhs['key'], edges_with_hhs['NAME'])):
tract_dict[(i[0], i[1], i[2])] = i[3]
nx.set_edge_attributes(g, hh_dict, 'Tot_Est_HH_uncpd')
nx.set_edge_attributes(g, tract_dict, 'Tract_name')
return_list = [g]
if bbox_poly:
overlap = hh_shp['geometry'].intersection(bbox_poly)
hh_shp['full_tract_area'] = hh_shp.geometry.area
hh_shp_pts = hh_shp.copy()
overlap_poly = overlap[~overlap.is_empty].copy()
ovlp_gdf = gpd.GeoDataFrame(overlap_poly, geometry=overlap_poly)
ovlp_gdf["cp_area"] = ovlp_gdf.geometry.area
hh_shp_pts['geometry'] = ovlp_gdf['geometry'].centroid
ovlp_gdf_join = gpd.sjoin(ovlp_gdf, hh_shp_pts, how="left", op='intersects')
ovlp_gdf_join['Est_Area_Cpd_Ratio'] = ovlp_gdf_join['cp_area']/ovlp_gdf_join['full_tract_area']
ovlp_pts = ovlp_gdf.copy()
ovlp_pts['geometry'] = ovlp_pts['geometry'].centroid
cpd_hh_join = gpd.sjoin(hh_shp, ovlp_pts, how="left", op='intersects')
cpd_hh_join['Est_Area_Cpd_Ratio'] = cpd_hh_join['cp_area']/cpd_hh_join.geometry.area
cpd_hh_join_sel = cpd_hh_join[['NAME', 'Est_Area_Cpd_Ratio']]
edges_with_hhs_cpd = edges_with_hhs.merge(cpd_hh_join_sel, on='NAME')
edges_with_hhs_cpd['Tot_Est_HH_cpd'] = edges_with_hhs_cpd[hh_col_name]*edges_with_hhs_cpd['Est_Area_Cpd_Ratio']
edges_with_hhs_cpd['HH_Cpd_pct'] = edges_with_hhs_cpd['Tot_Est_HH_cpd'] / edges_with_hhs_cpd['Tot_Est_HH_cpd'].sum()
extra_prc = edges_with_hhs_cpd.loc[0]['HH_Cpd_pct']+(1-edges_with_hhs_cpd['HH_Cpd_pct'].sum())
edges_with_hhs_cpd.loc[0, 'HH_Cpd_pct'] = extra_prc
#print(edges_with_hhs_cpd['HH_Cpd_pct'].sum())
cpt_dict = {}
tot_hh_cpt_dict = {}
tot_hh_cpt_pct_dict = {}
for i in list(zip(edges_with_hhs_cpd['u'], edges_with_hhs_cpd['v'], edges_with_hhs_cpd['key'], edges_with_hhs_cpd['Est_Area_Cpd_Ratio'])):
cpt_dict[(i[0], i[1], i[2])] = i[3]
for i in list(zip(edges_with_hhs_cpd['u'], edges_with_hhs_cpd['v'], edges_with_hhs_cpd['key'], edges_with_hhs_cpd['Tot_Est_HH_cpd'])):
tot_hh_cpt_dict[(i[0], i[1], i[2])] = i[3]
for i in list(zip(edges_with_hhs_cpd['u'], edges_with_hhs_cpd['v'], edges_with_hhs_cpd['key'], edges_with_hhs_cpd['HH_Cpd_pct'])):
tot_hh_cpt_pct_dict[(i[0], i[1], i[2])] = i[3]
nx.set_edge_attributes(g, cpt_dict, 'Est_Area_Cpd_Ratio')
nx.set_edge_attributes(g, tot_hh_cpt_dict, 'Tot_Est_HH_Cpd')
nx.set_edge_attributes(g, tot_hh_cpt_pct_dict, 'Pct_HH_Cpd')
gdf_edges = ox.graph_to_gdfs(g, nodes=False, edges=True)
return_list.append(ovlp_gdf_join)
return return_list
def set_test_hh_ratio(g, rat_dict):
for e in g.edges(keys=True, data=True):
if 'Tract_name' in e[3]:
if e[3]['Tract_name'] in rat_dict.keys():
e[3]['Test_Cpd_Ratio'] = rat_dict[e[3]['Tract_name']]
else:
e[3]['Test_Cpd_Ratio'] = 0.0
return g
def poly_to_gdf(poly):
poly_gdf = gpd.GeoDataFrame([1], geometry=[poly])
return poly_gdf
def adj_speed_value(g, populate=False, overwrite=False): # Becky Add for routing
for e in g.edges(keys=True, data=True):
if 'maxspeed' in e[3]:
s = e[3]['maxspeed']
if type(s) == list:
s = s[0]
sa = int(s[:2])
e[3]['adj_speed'] = sa
else:
if populate:
if 'highway' in e[3]:
if e[3]['highway'] == 'road':
e[3]['adj_speed'] = 0
else:
e[3]['adj_speed'] = DEFAULT_ROAD_SPEED
else:
e[3]['adj_speed'] = 0
return g
def add_fire_distance(g, fire_df, norm=False, inv=False):
#print('adding fire distance, norm', norm, 'inv', inv)
for e in g.edges(keys=True, data=True):
if 'geometry' in e[3]:
s = e[3]['geometry'].distance(fire_df.unary_union)
e[3]['fire_dist'] = s
else:
e[3]['fire_dist'] = None
if norm:
gdf_edges = ox.graph_to_gdfs(g, nodes=False, edges=True)
g = normalize_edge_attribute(g, 'fire_dist', min(gdf_edges.fire_dist),
max(gdf_edges.fire_dist), 'fire_dist_n')
if inv:
g = invert_norm_edge_attribute(g, 'fire_dist_n', 'inv_fire_dist_n')
return g
def normalize_edge_attribute(g, attr, att_min, att_max, new_name):
for e in g.edges(keys=True, data=True):
if attr in e[3]:
e[3][new_name] = (e[3][attr]-att_min)/(att_max-att_min)
else:
e[3][new_name] = None
return g
def invert_norm_edge_attribute(g, attr, new_name):
for e in g.edges(keys=True, data=True):
if attr in e[3]:
e[3][new_name] = max(min((1-e[3][attr]), 1), 0)
else:
e[3][new_name] = None
return g
def combine_attribute(g, attrs, weights, new_name):
#print('combining', str(attrs), 'at weights', str(weights), 'to', new_name)
for e in g.edges(keys=True, data=True):
if all(attr in e[3] for attr in attrs):
e[3][new_name] = sum([(weights[i]*e[3][a]) for i, a in enumerate(attrs)])
else:
e[3][new_name] = None
return g
def cleanUp(g):
return adjustLength(fillPhantom(g))
def project_lat_lon(lat, lon):
return ox.projection.project_geometry(Point(lon, lat))[0].coords[0] #keel
# Becky added function
def project_UTM(y, x, crs):
return ox.projection.project_geometry(Point(y, x), crs=crs, to_latlong=True)[0].coords[0] #keel
# Becky added function
def find_UTM_crs(lat, lon):
return ox.projection.project_geometry(Point(lon, lat))[1] #keel
def isNodeInBbox(node, bbox):
return bbox[0][0]<node['x']<bbox[1][0] and bbox[0][1]<node['y']<bbox[1][1]
def view_path(g, start_point, exit_point, strategy=[], showMap=False, norm=True): # Becky added, show path choosen by driving strategy
path_list = []
if strategy == []:
sweight = 'length'
path = nx.shortest_path(g, source=start_point, target=exit_point, weight=sweight)
if showMap:
ox.plot.plot_graph_route(g, path)
path_list.append(['dist', path])
else:
colors = ox.get_colors(len(strategy))
rc = [colors[strategy.index(x)] for x in strategy for y in x]
for rs in strategy:
if rs == 'dist':
if norm:
sweight = 'length_n'
else:
sweight = 'length'
elif rs == 'dist+speed':
if norm:
print('not implemented')
else:
sweight = 'seg_time'
elif rs == 'dist+road_type_weight':
if norm:
sweight = 'rt_wght_len_n'
else:
sweight = 'rt_weighted_len'
elif rs == 'dist+from+fire':
if norm:
sweight = 'inv_fire_dist_n'
else:
print('not implemented')
elif rs == 'fire+dist':
if norm:
sweight = 'fire_leng_n'
else:
print('not implemented')
elif rs == 'fire+rdty_weight':
if norm:
sweight = 'fire_rd_wght_n'
else:
print('not implemented')
path = nx.shortest_path(g, source=start_point, target=exit_point, weight=sweight)
if showMap:
ox.plot.plot_graph_route(g, path, route_color=rc)
path_list.append([rs, path])
return path_list
def strategy_opts():
ops = ['dist', 'dist+speed', 'dist+road_type_weight',
'dist+from+fire', 'fire+dist', 'fire+rdty_weight']
return ops
def convt_strategy_opts_to_weights(ops):
for idx, strat in enumerate(ops):
if strat == 'dist':
#ops[idx] = 'length'
ops[idx] = 'length_n'
elif strat == 'dist+speed':
#ops[idx] = 'seg_time'
ops[idx] = 'seg_time_n'
elif strat == 'dist+road_type_weight':
#ops[idx] = 'rt_weighted_len'
ops[idx] = 'rt_wght_len_n'
elif strat == 'dist+from+fire':
ops[idx] = 'inv_fire_dist_n'
elif strat == 'fire+dist':
ops[idx] = 'fire_leng_n'
elif strat == 'fire+rdty_weight':
ops[idx] = 'fire_rd_wght_n'
return ops
def compare_paths(g, paths, strategies=None, showMap=False): # Becky added, show path choosen by driving strategy
colors = ox.get_colors(len(paths))
rc = [colors[paths.index(x)] for x in paths for y in x]
nc = [val for val in colors for _ in (0, 1)]
# plot the routes
if showMap:
fig, ax = ox.plot_graph_routes(g, paths, route_color=rc, orig_dest_node_color=nc, node_size=0)
if strategies:
lengths = [nx.shortest_path_length(g, p, strategies[i]) for (i,p) in enumerate(paths)]
return lengths
############################################################################
############################################################################
class Road:
def __init__(self, g, node_i, node_j, key, attr, lanes=DEFAULT_ROAD_LANES, speed=DEFAULT_ROAD_SPEED):
self.g=g
self.node_i = node_i
self.node_j = node_j
self.key = key
self.idx = (node_i, node_j, key)
self.attr = attr
self.geom = self.attr['geometry']
self.length = self.geom.length
self.vehicles = deque()
self.requests = []
self.isBlocked = False
if 'maxspeed' in self.attr:
s=self.attr['maxspeed']
if type(s)==list:
s=s[0]
self.speed=mph2ms(int(s[:2]))
else:
self.speed=speed*(np.random.random()*2+0.5) # 0.5-2.5 of inital speed
self.normal_speed = self.speed
assert self.speed>=0
## -> quickest time
self.checkins = {} # the entry time and position of current vehicles
self.ett = {} # estimated travel time based on exit vehicles, at time t, ett updated by v
## <- quickest time
if 'Tract_name' in self.attr:
self.tract = self.attr['Tract_name']
else:
self.tract = None
if 'Test_Cpd_Ratio' in self.attr:
self.test_hh_ratio = self.attr['Test_Cpd_Ratio']
if self.test_hh_ratio is None:
self.test_hh_ratio = 0
else:
self.test_hh_ratio = 0
if 'Pct_HH_Cpd' in self.attr:
self.hh_ratio = self.attr['Pct_HH_Cpd']
if self.hh_ratio is None:
self.hh_ratio = 0
else:
self.hh_ratio = 0
## -> quickest time
#ett = length/speed
def check_in(self, vid, pos, frame_number):
#print('checkin vid:', vid, 'fn:', frame_number, 'rdidx:', self.idx)
self.checkins[vid]=(pos, frame_number)
def check_out(self, vid, last_pos, frame_number):
assert vid in self.checkins
delta = last_pos - self.checkins[vid][0] #Last pos - first pos
if abs(delta) > 1e-7:
#print('checkout vid:', vid, 'fn:', frame_number, 'first pos', self.checkins[vid][1], 'rdidx:', self.idx, 'delta:', delta)
self.ett[frame_number] = ((frame_number - 1 - self.checkins[vid][1]) / delta * self.length, vid, delta/(frame_number - 1 - self.checkins[vid][1]))
#print('full ett: ', self.ett)
del self.checkins[vid]
## <- quickest time
def set_block(self): # set to block road by fire spread
self.isBlocked = True
def mutate_block(self, prob=0.1):
if not self.isBlocked:
if np.random.random() < prob:
#if not self.isBlocked:
self.isBlocked = True
return True
return False
#else:
# self.isBlocked = False
# collection.remove(self.idx)
def mutate_speed(self, prob=0.9):
if np.random.random() < prob: # stay unchanged for most of time
if self.normal_speed == self.speed:
self.speed = 1.0 if np.random.random() > 0.5 else 30 # Road mutate
else:
self.speed = self.normal_speed # Road restored
def show(self, vehicles=None):
if vehicles is None:
vehicles = self.vehicles
return shapely.geometry.GeometryCollection([self.geom]+[self.geom.interpolate(_.pos) for _ in vehicles])
def tail_space(self):
if len(self.vehicles) == 0:
return self.length
return max(self.vehicles[-1].pos - self.vehicles[-1].length, 0)
#def remain_space(self):
# return self.length-sum(_.length for _ in self.vehicles)
def add_vehicle(self, v):
if self.tail_space() <= 0:
return False
if v.pos is 0:
v.pos = np.random.random()*self.tail_space() ##!!! This is not true random
self.vehicles.append(v)
return True
#def adjust(self):
# n=len(self.vehicles)
# if n == 0:
# return
# poses = np.random.random(n)*self.remain_space()
# poses.sort()
# acc_length = 0
# for i in range(n):
# acc_length += self.vehicles[n-1-i].length
# self.vehicles[n-1-i].pos=poses[i]+acc_length
def move(self, frame_number, timestep=1):
if len(self.vehicles) == 0:
return
distance = self.speed * timestep
previous = None
for v in self.vehicles:
v.new_pos = v.pos + distance
if previous is None: # first car
if v.new_pos > self.length: # need transit
if v.next_road is None or v.next_road.isBlocked: # in dead end or blocked road, wait at the beginning
v.new_pos = self.length
v.last_move = v.new_pos - v.pos
else:
v.next_road.request_join(v.new_pos - self.length, v, self, timestep, frame_number) # timestep instead of frame_number
else:
v.last_move = distance
else:
v.new_pos = min(v.new_pos, previous)
v.last_move = v.new_pos - v.pos
previous = v.new_pos - v.length
def request_join(self, momentum, v, from_road, timestep, frame_number):
self.requests.append((momentum, v, from_road, timestep, frame_number))
def resolve_requests(self, frame_number): # being called after all moves() done
if len(self.requests) == 0:
return
self.requests.sort()
if len(set(_[1].vid for _ in self.requests)) < len(self.requests):
raise ValueError('Duplicate vehicle in requests')
while self.tail_space() > 0 and len(self.requests) > 0: # receive new vehicles as much as possible
momentum, v, from_road, timestep, frame_number = self.requests.pop()
from_road.check_out(v.vid, v.pos, frame_number) # quickest path
v.new_pos = min(self.tail_space(), momentum)
v.last_move = v.new_pos + from_road.length - v.pos
v.pos = v.new_pos
from_road.vehicles.popleft()
self.check_in(v.vid, v.pos, frame_number)
self.vehicles.append(v)
v.road = self
v.trajectory.append((self.idx, frame_number))
v.choose_next(frame_number)
for momentum, v, from_road, timestep, frame_number in self.requests: # Those failed to udpate
v.new_pos = from_road.length # wait at the top of their original road
v.last_move = v.new_pos - v.pos
self.requests=[]
def sync_pos(self):
for v in self.vehicles:
v.pos = v.new_pos
def report_veh_num(self):
if self.length > 0:
return (len(self.vehicles), len(self.vehicles)/self.length)
else:
return (len(self.vehicles), None)
class Vehicle:
def __init__(self, g, vid, road=None, length=DEFAULT_VEHICLE_LENGTH, pos=0, target=None, st_weight='length'):
self.g=g
self.vid=vid
self.road = road
self.timer=0
self.length=length
self.pos=pos
self.target=target
self.st_weight = st_weight
self.goal_time = None
self.trajectory = []
if target is None:
self.isStuck = True
else:
self.isStuck = False
self.set_route_times = 0
self.is_clear = False
self.init_paths = None
#if self.road:
# self.addTo(self.road)
# self.navigate()
#if self.road:
# self.addTo(self.road, self.pos)
# if not pos:
# self.pos=np.random.random()*self.road.length
def choose_target(self, target_list=None):
#print('choose_target navigate seting routes')
if target_list is None:
if type(self.target) == list:
target_list = self.target
else:
self.isStuck = True
return
ans = [float('inf'), None, None] # length, target, path
for t in target_list:
#print('choose_target find targets')
if nx.has_path(self.g, self.road.node_j, t):
### Shortest Path
#print('path weight,', self.st_weight,'is used')
paths = nx.shortest_path(self.g, self.road.node_j, t, weight=self.st_weight)
#paths = abm_shortest_path(self.g, self.road.node_j, t, weight=self.st_weight)
if self.st_weight == 'dist': # Becky added if statements to determine overall shortest path by adjusted weight
#length = sum(self.g.adj[paths[i]][paths[i+1]][0]['length'] for i in range(len(paths)-1))
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['length_n'] for i in range(len(paths)-1))
elif self.st_weight == 'dist+speed':
#length = sum(self.g.adj[paths[i]][paths[i+1]][0]['seg_time'] for i in range(len(paths)-1))
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['seg_time_n'] for i in range(len(paths)-1))
elif self.st_weight == 'dist+road_type_weight':
#length = sum(self.g.adj[paths[i]][paths[i+1]][0]['rt_weighted_len'] for i in range(len(paths)-1))
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['rt_wght_len_n'] for i in range(len(paths)-1))
elif self.st_weight == 'dist+from+fire':
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['inv_fire_dist_n'] for i in range(len(paths)-1))
elif self.st_weight == 'fire+dist':
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['fire_leng_n'] for i in range(len(paths)-1))
elif self.st_weight == 'fire+rdty_weight':
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['fire_rd_wght_n'] for i in range(len(paths)-1))
elif self.st_weight == 'quickest':
#print('quickest weight, ett is used')
length = sum(self.g.adj[paths[i]][paths[i+1]][0]['ett'] for i in range(len(paths)-1))
else:
print('BAD weight key!!! :', self.st_weight)
if length < ans[0]:
ans[0] = length
ans[1] = t
ans[2] = paths
if ans[1] is None:
self.isStuck = True
else:
self.goal = ans[1]
self.routes = ans[2]