forked from wingsweihua/colight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anon_env.py
executable file
·1663 lines (1337 loc) · 70.4 KB
/
anon_env.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
'''
Interactions with CityFlow, get/set values from CityFlow, pass it to RL agents
'''
import pickle
import numpy as np
import json
import sys
import pandas as pd
import os
import cityflow as engine
import time
import threading
from multiprocessing import Process, Pool
from script import get_traffic_volume
from copy import deepcopy
class RoadNet:
def __init__(self, roadnet_file):
self.roadnet_dict = json.load(open(roadnet_file,"r"))
self.net_edge_dict = {}
self.net_node_dict = {}
self.net_lane_dict = {}
self.generate_node_dict()
self.generate_edge_dict()
self.generate_lane_dict()
def generate_node_dict(self):
'''
node dict has key as node id, value could be the dict of input nodes and output nodes
:return:
'''
for node_dict in self.roadnet_dict['intersections']:
node_id = node_dict['id']
road_links = node_dict['roads']
input_nodes = []
output_nodes = []
input_edges = []
output_edges = {}
for road_link_id in road_links:
road_link_dict = self._get_road_dict(road_link_id)
if road_link_dict['startIntersection'] == node_id:
end_node = road_link_dict['endIntersection']
output_nodes.append(end_node)
# todo add output edges
elif road_link_dict['endIntersection'] == node_id:
input_edges.append(road_link_id)
start_node = road_link_dict['startIntersection']
input_nodes.append(start_node)
output_edges[road_link_id] = set()
pass
# update roadlinks
actual_roadlinks = node_dict['roadLinks']
for actual_roadlink in actual_roadlinks:
output_edges[actual_roadlink['startRoad']].add(actual_roadlink['endRoad'])
net_node = {
'node_id': node_id,
'input_nodes': list(set(input_nodes)),
'input_edges': list(set(input_edges)),
'output_nodes': list(set(output_nodes)),
'output_edges': output_edges# should be a dict, with key as an input edge, value as output edges
}
if node_id not in self.net_node_dict.keys():
self.net_node_dict[node_id] = net_node
def _get_road_dict(self, road_id):
for item in self.roadnet_dict['roads']:
if item['id'] == road_id:
return item
print("Cannot find the road id {0}".format(road_id))
sys.exit(-1)
# return None
def generate_edge_dict(self):
'''
edge dict has key as edge id, value could be the dict of input edges and output edges
:return:
'''
for edge_dict in self.roadnet_dict['roads']:
edge_id = edge_dict['id']
input_node = edge_dict['startIntersection']
output_node = edge_dict['endIntersection']
net_edge = {
'edge_id': edge_id,
'input_node': input_node,
'output_node': output_node,
'input_edges': self.net_node_dict[input_node]['input_edges'],
'output_edges': self.net_node_dict[output_node]['output_edges'][edge_id],
}
if edge_id not in self.net_edge_dict.keys():
self.net_edge_dict[edge_id] = net_edge
def generate_lane_dict(self):
lane_dict = {}
for node_dict in self.roadnet_dict['intersections']:
for road_link in node_dict["roadLinks"]:
lane_links = road_link["laneLinks"]
start_road = road_link["startRoad"]
end_road = road_link["endRoad"]
for lane_link in lane_links:
start_lane = start_road + "_" + str(lane_link['startLaneIndex'])
end_lane = end_road + "_" +str(lane_link["endLaneIndex"])
if start_lane not in lane_dict:
lane_dict[start_lane] = {
"output_lanes": [end_lane],
"input_lanes": []
}
else:
lane_dict[start_lane]["output_lanes"].append(end_lane)
if end_lane not in lane_dict:
lane_dict[end_lane] = {
"output_lanes": [],
"input_lanes": [start_lane]
}
else:
lane_dict[end_lane]["input_lanes"].append(start_lane)
self.net_lane_dict = lane_dict
def hasEdge(self, edge_id):
if edge_id in self.net_edge_dict.keys():
return True
else:
return False
def getEdge(self, edge_id):
if edge_id in self.net_edge_dict.keys():
return edge_id
else:
return None
def getOutgoing(self, edge_id):
if edge_id in self.net_edge_dict.keys():
return self.net_edge_dict[edge_id]['output_edges']
else:
return []
class Intersection:
DIC_PHASE_MAP = {
0: 1,
1: 2,
2: 3,
3: 4,
-1: 0
}
def __init__(self, inter_id, dic_traffic_env_conf, eng, light_id_dict,path_to_log):
self.inter_id = inter_id
self.inter_name = "intersection_{0}_{1}".format(inter_id[0], inter_id[1])
self.eng = eng
self.fast_compute = dic_traffic_env_conf['FAST_COMPUTE']
self.controlled_model = dic_traffic_env_conf['MODEL_NAME']
self.path_to_log = path_to_log
# ===== intersection settings =====
self.list_approachs = ["W", "E", "N", "S"]
self.dic_approach_to_node = {"W": 2, "E": 0, "S": 3, "N": 1}
# self.dic_entering_approach_to_edge = {
# approach: "road{0}_{1}_{2}".format(self.dic_approach_to_node[approach], light_id) for approach in self.list_approachs}
self.dic_entering_approach_to_edge = {"W": "road_{0}_{1}_0".format(inter_id[0] - 1, inter_id[1])}
self.dic_entering_approach_to_edge.update({"E": "road_{0}_{1}_2".format(inter_id[0] + 1, inter_id[1])})
self.dic_entering_approach_to_edge.update({"S": "road_{0}_{1}_1".format(inter_id[0], inter_id[1] - 1)})
self.dic_entering_approach_to_edge.update({"N": "road_{0}_{1}_3".format(inter_id[0], inter_id[1] + 1)})
self.dic_exiting_approach_to_edge = {
approach: "road_{0}_{1}_{2}".format(inter_id[0], inter_id[1], self.dic_approach_to_node[approach]) for
approach in self.list_approachs}
self.dic_entering_approach_lanes = {"W": [0], "E": [0], "S": [0], "N": [0]}
self.dic_exiting_approach_lanes = {"W": [0], "E": [0], "S": [0], "N": [0]}
# grid settings
self.length_lane = 300
self.length_terminal = 50
self.length_grid = 5
self.num_grid = int(self.length_lane // self.length_grid)
self.list_phases = dic_traffic_env_conf["PHASE"][dic_traffic_env_conf['SIMULATOR_TYPE']]
# generate all lanes
self.list_entering_lanes = []
for approach in self.list_approachs:
self.list_entering_lanes += [self.dic_entering_approach_to_edge[approach] + '_' + str(i) for i in
range(sum(list(dic_traffic_env_conf["LANE_NUM"].values())))]
self.list_exiting_lanes = []
for approach in self.list_approachs:
self.list_exiting_lanes += [self.dic_exiting_approach_to_edge[approach] + '_' + str(i) for i in
range(sum(list(dic_traffic_env_conf["LANE_NUM"].values())))]
self.list_lanes = self.list_entering_lanes + self.list_exiting_lanes
self.adjacency_row = light_id_dict['adjacency_row']
self.neighbor_ENWS = light_id_dict['neighbor_ENWS']
self.neighbor_lanes_ENWS = light_id_dict['entering_lane_ENWS']
def _get_top_k_lane(lane_id_list, top_k_input):
top_k_lane_indexes = []
for i in range(top_k_input):
lane_id = lane_id_list[i] if i < len(lane_id_list) else None
top_k_lane_indexes.append(lane_id)
return top_k_lane_indexes
self._adjacency_row_lanes = {}
# _adjacency_row_lanes is the lane id, not index
for lane_id in self.list_entering_lanes:
if lane_id in light_id_dict['adjacency_matrix_lane']:
self._adjacency_row_lanes[lane_id] = light_id_dict['adjacency_matrix_lane'][lane_id]
else:
self._adjacency_row_lanes[lane_id] = [_get_top_k_lane([], self.dic_traffic_env_conf["TOP_K_ADJACENCY_LANE"]),
_get_top_k_lane([], self.dic_traffic_env_conf["TOP_K_ADJACENCY_LANE"])]
# order is the entering lane order, each element is list of two lists
self.adjacency_row_lane_id_local = {}
for index, lane_id in enumerate(self.list_entering_lanes):
self.adjacency_row_lane_id_local[lane_id] = index
# previous & current
self.dic_lane_vehicle_previous_step = {}
self.dic_lane_waiting_vehicle_count_previous_step = {}
self.dic_vehicle_speed_previous_step = {}
self.dic_vehicle_distance_previous_step = {}
self.dic_lane_vehicle_current_step = {}
self.dic_lane_waiting_vehicle_count_current_step = {}
self.dic_vehicle_speed_current_step = {}
self.dic_vehicle_distance_current_step = {}
self.list_lane_vehicle_previous_step = []
self.list_lane_vehicle_current_step = []
# -1: all yellow, -2: all red, -3: none
self.all_yellow_phase_index = -1
self.all_red_phase_index = -2
self.current_phase_index = 1
self.previous_phase_index = 1
self.eng.set_tl_phase(self.inter_name, self.current_phase_index)
path_to_log_file = os.path.join(self.path_to_log, "signal_inter_{0}.txt".format(self.inter_name))
df = [self.get_current_time(), self.current_phase_index]
df = pd.DataFrame(df)
df = df.transpose()
df.to_csv(path_to_log_file, mode='a', header=False, index=False)
self.next_phase_to_set_index = None
self.current_phase_duration = -1
self.all_red_flag = False
self.all_yellow_flag = False
self.flicker = 0
self.dic_vehicle_min_speed = {} # this second
self.dic_vehicle_arrive_leave_time = dict() # cumulative
self.dic_feature = {} # this second
self.dic_feature_previous_step = {} # this second
def build_adjacency_row_lane(self, lane_id_to_global_index_dict):
self.adjacency_row_lanes = [] # order is the entering lane order, each element is list of two lists
for entering_lane_id in self.list_entering_lanes:
_top_k_entering_lane, _top_k_leaving_lane = self._adjacency_row_lanes[entering_lane_id]
top_k_entering_lane = []
top_k_leaving_lane = []
for lane_id in _top_k_entering_lane:
top_k_entering_lane.append(lane_id_to_global_index_dict[lane_id] if lane_id is not None else -1)
for lane_id in _top_k_leaving_lane:
top_k_leaving_lane.append(lane_id_to_global_index_dict[lane_id]
if (lane_id is not None) and (lane_id in lane_id_to_global_index_dict.keys()) # TODO leaving lanes of system will also have -1
else -1)
self.adjacency_row_lanes.append([top_k_entering_lane, top_k_leaving_lane])
# set
def set_signal(self, action, action_pattern, yellow_time, all_red_time):
if self.all_yellow_flag:
# in yellow phase
self.flicker = 0
if self.current_phase_duration >= yellow_time: # yellow time reached
self.current_phase_index = self.next_phase_to_set_index
self.eng.set_tl_phase(self.inter_name, self.current_phase_index) # if multi_phase, need more adjustment
path_to_log_file = os.path.join(self.path_to_log, "signal_inter_{0}.txt".format(self.inter_name))
df = [self.get_current_time(), self.current_phase_index]
df = pd.DataFrame(df)
df = df.transpose()
df.to_csv(path_to_log_file, mode='a', header=False, index=False)
self.all_yellow_flag = False
else:
pass
else:
# determine phase
if action_pattern == "switch": # switch by order
if action == 0: # keep the phase
self.next_phase_to_set_index = self.current_phase_index
elif action == 1: # change to the next phase
self.next_phase_to_set_index = (self.current_phase_index + 1) % len(self.list_phases) # if multi_phase, need more adjustment
else:
sys.exit("action not recognized\n action must be 0 or 1")
elif action_pattern == "set": # set to certain phase
self.next_phase_to_set_index = self.DIC_PHASE_MAP[action] # if multi_phase, need more adjustment
# set phase
if self.current_phase_index == self.next_phase_to_set_index: # the light phase keeps unchanged
pass
else: # the light phase needs to change
# change to yellow first, and activate the counter and flag
self.eng.set_tl_phase(self.inter_name, 0) # !!! yellow, tmp
path_to_log_file = os.path.join(self.path_to_log, "signal_inter_{0}.txt".format(self.inter_name))
df = [self.get_current_time(), self.current_phase_index]
df = pd.DataFrame(df)
df = df.transpose()
df.to_csv(path_to_log_file, mode='a', header=False, index=False)
#traci.trafficlights.setRedYellowGreenState(
# self.node_light, self.all_yellow_phase_str)
self.current_phase_index = self.all_yellow_phase_index
self.all_yellow_flag = True
self.flicker = 1
# update inner measurements
def update_previous_measurements(self):
self.previous_phase_index = self.current_phase_index
self.dic_lane_vehicle_previous_step = self.dic_lane_vehicle_current_step
self.dic_lane_waiting_vehicle_count_previous_step = self.dic_lane_waiting_vehicle_count_current_step
self.dic_vehicle_speed_previous_step = self.dic_vehicle_speed_current_step
self.dic_vehicle_distance_previous_step = self.dic_vehicle_distance_current_step
def update_current_measurements_map(self, simulator_state):
## need change, debug in seeing format
def _change_lane_vehicle_dic_to_list(dic_lane_vehicle):
list_lane_vehicle = []
for value in dic_lane_vehicle.values():
list_lane_vehicle.extend(value)
return list_lane_vehicle
if self.current_phase_index == self.previous_phase_index:
self.current_phase_duration += 1
else:
self.current_phase_duration = 1
self.dic_lane_vehicle_current_step = {}
self.dic_lane_waiting_vehicle_count_current_step = {}
for lane in self.list_entering_lanes:
self.dic_lane_vehicle_current_step[lane] = simulator_state["get_lane_vehicles"][lane]
self.dic_lane_waiting_vehicle_count_current_step[lane] = simulator_state["get_lane_waiting_vehicle_count"][lane]
for lane in self.list_exiting_lanes:
self.dic_lane_vehicle_current_step[lane] = simulator_state["get_lane_vehicles"][lane]
self.dic_lane_waiting_vehicle_count_current_step[lane] = simulator_state["get_lane_waiting_vehicle_count"][lane]
self.dic_vehicle_speed_current_step = simulator_state['get_vehicle_speed']
self.dic_vehicle_distance_current_step = simulator_state['get_vehicle_distance']
# get vehicle list
self.list_lane_vehicle_current_step = _change_lane_vehicle_dic_to_list(self.dic_lane_vehicle_current_step)
self.list_lane_vehicle_previous_step = _change_lane_vehicle_dic_to_list(self.dic_lane_vehicle_previous_step)
list_vehicle_new_arrive = list(set(self.list_lane_vehicle_current_step) - set(self.list_lane_vehicle_previous_step))
list_vehicle_new_left = list(set(self.list_lane_vehicle_previous_step) - set(self.list_lane_vehicle_current_step))
list_vehicle_new_left_entering_lane_by_lane = self._update_leave_entering_approach_vehicle()
list_vehicle_new_left_entering_lane = []
for l in list_vehicle_new_left_entering_lane_by_lane:
list_vehicle_new_left_entering_lane += l
# update vehicle arrive and left time
self._update_arrive_time(list_vehicle_new_arrive)
self._update_left_time(list_vehicle_new_left_entering_lane)
# update vehicle minimum speed in history, # to be implemented
#self._update_vehicle_min_speed()
# update feature
self._update_feature_map(simulator_state)
def update_current_measurements(self):
## need change, debug in seeing format
def _change_lane_vehicle_dic_to_list(dic_lane_vehicle):
list_lane_vehicle = []
for value in dic_lane_vehicle.values():
list_lane_vehicle.extend(value)
return list_lane_vehicle
if self.current_phase_index == self.previous_phase_index:
self.current_phase_duration += 1
else:
self.current_phase_duration = 1
self.dic_lane_vehicle_current_step =[] # = self.eng.get_lane_vehicles()
#not implement
flow_tmp = self.eng.get_lane_vehicles()
self.dic_lane_vehicle_current_step = {key: None for key in self.list_entering_lanes}
for lane in self.list_entering_lanes:
self.dic_lane_vehicle_current_step[lane] = flow_tmp[lane]
self.dic_lane_waiting_vehicle_count_current_step = self.eng.get_lane_waiting_vehicle_count()
self.dic_vehicle_speed_current_step = self.eng.get_vehicle_speed()
self.dic_vehicle_distance_current_step = self.eng.get_vehicle_distance()
# get vehicle list
self.list_lane_vehicle_current_step = _change_lane_vehicle_dic_to_list(self.dic_lane_vehicle_current_step)
self.list_lane_vehicle_previous_step = _change_lane_vehicle_dic_to_list(self.dic_lane_vehicle_previous_step)
list_vehicle_new_arrive = list(set(self.list_lane_vehicle_current_step) - set(self.list_lane_vehicle_previous_step))
list_vehicle_new_left = list(set(self.list_lane_vehicle_previous_step) - set(self.list_lane_vehicle_current_step))
list_vehicle_new_left_entering_lane_by_lane = self._update_leave_entering_approach_vehicle()
list_vehicle_new_left_entering_lane = []
for l in list_vehicle_new_left_entering_lane_by_lane:
list_vehicle_new_left_entering_lane += l
# update vehicle arrive and left time
self._update_arrive_time(list_vehicle_new_arrive)
self._update_left_time(list_vehicle_new_left_entering_lane)
# update vehicle minimum speed in history, # to be implemented
#self._update_vehicle_min_speed()
# update feature
self._update_feature()
def _update_leave_entering_approach_vehicle(self):
list_entering_lane_vehicle_left = []
# update vehicles leaving entering lane
if not self.dic_lane_vehicle_previous_step:
for lane in self.list_entering_lanes:
list_entering_lane_vehicle_left.append([])
else:
last_step_vehicle_id_list = []
current_step_vehilce_id_list = []
for lane in self.list_entering_lanes:
last_step_vehicle_id_list.extend(self.dic_lane_vehicle_previous_step[lane])
current_step_vehilce_id_list.extend(self.dic_lane_vehicle_current_step[lane])
list_entering_lane_vehicle_left.append(
list(set(last_step_vehicle_id_list) - set(current_step_vehilce_id_list))
)
return list_entering_lane_vehicle_left
def _update_arrive_time(self, list_vehicle_arrive):
ts = self.get_current_time()
# get dic vehicle enter leave time
for vehicle in list_vehicle_arrive:
if vehicle not in self.dic_vehicle_arrive_leave_time:
self.dic_vehicle_arrive_leave_time[vehicle] = \
{"enter_time": ts, "leave_time": np.nan}
else:
#print("vehicle: %s already exists in entering lane!"%vehicle)
#sys.exit(-1)
pass
def _update_left_time(self, list_vehicle_left):
ts = self.get_current_time()
# update the time for vehicle to leave entering lane
for vehicle in list_vehicle_left:
try:
self.dic_vehicle_arrive_leave_time[vehicle]["leave_time"] = ts
except KeyError:
print("vehicle not recorded when entering")
sys.exit(-1)
def update_neighbor_info(self, neighbors, dic_feature):
# print(dic_feature)
none_dic_feature = deepcopy(dic_feature)
for key in none_dic_feature.keys():
if none_dic_feature[key] is not None:
if "cur_phase" in key:
none_dic_feature[key] = [1] * len(none_dic_feature[key])
else:
none_dic_feature[key] = [0] * len(none_dic_feature[key])
else:
none_dic_feature[key] = None
for i in range(len(neighbors)):
neighbor = neighbors[i]
example_dic_feature = {}
if neighbor is None:
example_dic_feature["cur_phase_{0}".format(i)] = none_dic_feature["cur_phase"]
example_dic_feature["time_this_phase_{0}".format(i)] = none_dic_feature["time_this_phase"]
example_dic_feature["lane_num_vehicle_{0}".format(i)] = none_dic_feature["lane_num_vehicle"]
else:
example_dic_feature["cur_phase_{0}".format(i)] = neighbor.dic_feature["cur_phase"]
example_dic_feature["time_this_phase_{0}".format(i)] = neighbor.dic_feature["time_this_phase"]
example_dic_feature["lane_num_vehicle_{0}".format(i)] = neighbor.dic_feature["lane_num_vehicle"]
dic_feature.update(example_dic_feature)
return dic_feature
@staticmethod
def _add_suffix_to_dict_key(target_dict, suffix):
keys = list(target_dict.keys())
for key in keys:
target_dict[key+"_"+suffix] = target_dict.pop(key)
return target_dict
def _update_feature_map(self, simulator_state):
dic_feature = dict()
dic_feature["cur_phase"] = [self.current_phase_index]
dic_feature["time_this_phase"] = [self.current_phase_duration]
dic_feature["vehicle_position_img"] = None #self._get_lane_vehicle_position(self.list_entering_lanes)
dic_feature["vehicle_speed_img"] = None #self._get_lane_vehicle_speed(self.list_entering_lanes)
dic_feature["vehicle_acceleration_img"] = None
dic_feature["vehicle_waiting_time_img"] = None #self._get_lane_vehicle_accumulated_waiting_time(self.list_entering_lanes)
dic_feature["lane_num_vehicle"] = self._get_lane_num_vehicle(self.list_entering_lanes)
dic_feature["pressure"] = None # [self._get_pressure()]
if self.fast_compute:
dic_feature["coming_vehicle"] = None
dic_feature["leaving_vehicle"] = None
else:
dic_feature["coming_vehicle"] = self._get_coming_vehicles(simulator_state)
dic_feature["leaving_vehicle"] = self._get_leaving_vehicles(simulator_state)
dic_feature["lane_num_vehicle_been_stopped_thres01"] = None # self._get_lane_num_vehicle_been_stopped(0.1, self.list_entering_lanes)
dic_feature["lane_num_vehicle_been_stopped_thres1"] = self._get_lane_num_vehicle_been_stopped(1, self.list_entering_lanes)
dic_feature["lane_queue_length"] = None # self._get_lane_queue_length(self.list_entering_lanes)
dic_feature["lane_num_vehicle_left"] = None
dic_feature["lane_sum_duration_vehicle_left"] = None
dic_feature["lane_sum_waiting_time"] = None #self._get_lane_sum_waiting_time(self.list_entering_lanes)
dic_feature["terminal"] = None
dic_feature["adjacency_matrix"] = self._get_adjacency_row() # TODO this feature should be a dict? or list of lists
dic_feature["adjacency_matrix_lane"] = self._get_adjacency_row_lane() #row: entering_lane # columns: [inputlanes, outputlanes]
dic_feature['connectivity'] = self._get_connectivity(self.neighbor_lanes_ENWS)
self.dic_feature = dic_feature
# ================= calculate features from current observations ======================
def _get_adjacency_row(self):
return self.adjacency_row
def _get_adjacency_row_lane(self):
return self.adjacency_row_lanes
def lane_position_mapper(self, lane_pos, bins):
lane_pos_np = np.array(lane_pos)
digitized = np.digitize(lane_pos_np, bins)
position_counter = [len(lane_pos_np[digitized == i]) for i in range(1, len(bins))]
return position_counter
def _get_coming_vehicles(self, simulator_state):
## TODO f vehicle position eng.get_vehicle_distance() || eng.get_lane_vehicles()
coming_distribution = []
## dimension = num_lane*3*num_list_entering_lanes
lane_vid_mapping_dict = simulator_state['get_lane_vehicles']
vid_distance_mapping_dict = simulator_state['get_vehicle_distance']
## TODO LANE LENGTH = 300
bins = np.linspace(0, 300, 4).tolist()
for lane in self.list_entering_lanes:
coming_vehicle_position = []
vehicle_position_lane = lane_vid_mapping_dict[lane]
for vehicle in vehicle_position_lane:
coming_vehicle_position.append(vid_distance_mapping_dict[vehicle])
coming_distribution.extend(self.lane_position_mapper(coming_vehicle_position, bins))
return coming_distribution
def _get_leaving_vehicles(self, simulator_state):
leaving_distribution = []
## dimension = num_lane*3*num_list_entering_lanes
lane_vid_mapping_dict = simulator_state['get_lane_vehicles']
vid_distance_mapping_dict = simulator_state['get_vehicle_distance']
## TODO LANE LENGTH = 300
bins = np.linspace(0, 300, 4).tolist()
for lane in self.list_exiting_lanes:
coming_vehicle_position = []
vehicle_position_lane = lane_vid_mapping_dict[lane]
for vehicle in vehicle_position_lane:
coming_vehicle_position.append(vid_distance_mapping_dict[vehicle])
leaving_distribution.extend(self.lane_position_mapper(coming_vehicle_position, bins))
return leaving_distribution
def _get_pressure(self):
##TODO eng.get_vehicle_distance(), another way to calculate pressure & queue length
pressure = 0
all_enter_car_queue = 0
for lane in self.list_entering_lanes:
all_enter_car_queue += self.dic_lane_waiting_vehicle_count_current_step[lane]
all_leaving_car_queue = 0
for lane in self.list_exiting_lanes:
all_leaving_car_queue += self.dic_lane_waiting_vehicle_count_current_step[lane]
p = all_enter_car_queue - all_leaving_car_queue
if p < 0:
p = -p
return p
def _get_lane_queue_length(self, list_lanes):
'''
queue length for each lane
'''
return [self.dic_lane_waiting_vehicle_count_current_step[lane] for lane in list_lanes]
def _get_lane_num_vehicle(self, list_lanes):
'''
vehicle number for each lane
'''
return [len(self.dic_lane_vehicle_current_step[lane]) for lane in list_lanes]
def _get_connectivity(self, dic_of_list_lanes):
'''
vehicle number for each lane
'''
result = []
for i in range(len(dic_of_list_lanes['lane_ids'])):
num_of_vehicles_on_road = sum([len(self.dic_lane_vehicle_current_step[lane]) for lane in dic_of_list_lanes['lane_ids'][i]])
result.append(num_of_vehicles_on_road)
lane_length = [0] + dic_of_list_lanes['lane_length']
if np.sum(result)==0:
result=[1]+result
else:
result = [np.sum(result)]+ result
connectivity = list(np.array(result * np.exp(-np.array(lane_length)/(self.length_lane*4))))
# print(connectivity)
# sys.exit()
return connectivity
def _get_lane_sum_waiting_time(self, list_lanes):
'''
waiting time for each lane
'''
raise NotImplementedError
def _get_lane_list_vehicle_left(self, list_lanes):
'''
get list of vehicles left at each lane
####### need to check
'''
raise NotImplementedError
# non temporary
def _get_lane_num_vehicle_left(self, list_lanes):
list_lane_vehicle_left = self._get_lane_list_vehicle_left(list_lanes)
list_lane_num_vehicle_left = [len(lane_vehicle_left) for lane_vehicle_left in list_lane_vehicle_left]
return list_lane_num_vehicle_left
def _get_lane_sum_duration_vehicle_left(self, list_lanes):
## not implemented error
raise NotImplementedError
def _get_lane_num_vehicle_been_stopped(self, thres, list_lanes):
return [self.dic_lane_waiting_vehicle_count_current_step[lane] for lane in list_lanes]
def _get_position_grid_along_lane(self, vec):
pos = int(self.dic_vehicle_sub_current_step[vec][get_traci_constant_mapping("VAR_LANEPOSITION")])
return min(pos//self.length_grid, self.num_grid)
def _get_lane_vehicle_position(self, list_lanes):
list_lane_vector = []
for lane in list_lanes:
lane_vector = np.zeros(self.num_grid)
list_vec_id = self.dic_lane_vehicle_current_step[lane]
for vec in list_vec_id:
pos = int(self.dic_vehicle_distance_current_step[vec])
pos_grid = min(pos//self.length_grid, self.num_grid)
lane_vector[pos_grid] = 1
list_lane_vector.append(lane_vector)
return np.array(list_lane_vector)
# debug
def _get_vehicle_info(self, veh_id):
try:
pos = self.dic_vehicle_distance_current_step[veh_id]
speed = self.dic_vehicle_speed_current_step[veh_id]
return pos, speed
except:
return None, None
def _get_lane_vehicle_speed(self, list_lanes):
return [self.dic_vehicle_speed_current_step[lane] for lane in list_lanes]
def _get_lane_vehicle_accumulated_waiting_time(self, list_lanes):
raise NotImplementedError
# ================= get functions from outside ======================
def get_current_time(self):
return self.eng.get_current_time()
def get_dic_vehicle_arrive_leave_time(self):
return self.dic_vehicle_arrive_leave_time
def get_feature(self):
return self.dic_feature
def get_state(self, list_state_features):
# customize your own state
# print(list_state_features)
# print(self.dic_feature)
dic_state = {state_feature_name: self.dic_feature[state_feature_name] for state_feature_name in list_state_features}
return dic_state
def get_reward(self, dic_reward_info):
# customize your own reward
dic_reward = dict()
dic_reward["flickering"] = None
dic_reward["sum_lane_queue_length"] = None
dic_reward["sum_lane_wait_time"] = None
dic_reward["sum_lane_num_vehicle_left"] = None
dic_reward["sum_duration_vehicle_left"] = None
dic_reward["sum_num_vehicle_been_stopped_thres01"] = None
dic_reward["sum_num_vehicle_been_stopped_thres1"] = np.sum(self.dic_feature["lane_num_vehicle_been_stopped_thres1"])
dic_reward['pressure'] = None # np.sum(self.dic_feature["pressure"])
reward = 0
for r in dic_reward_info:
if dic_reward_info[r] != 0:
reward += dic_reward_info[r] * dic_reward[r]
return reward
class AnonEnv:
list_intersection_id = [
"intersection_1_1"
]
def __init__(self, path_to_log, path_to_work_directory, dic_traffic_env_conf):
self.path_to_log = path_to_log
self.path_to_work_directory = path_to_work_directory
self.dic_traffic_env_conf = dic_traffic_env_conf
self.simulator_type = self.dic_traffic_env_conf["SIMULATOR_TYPE"]
self.list_intersection = None
self.list_inter_log = None
self.list_lanes = None
self.system_states = None
self.feature_name_for_neighbor = self._reduce_duplicates(self.dic_traffic_env_conf["LIST_STATE_FEATURE"])
# check min action time
if self.dic_traffic_env_conf["MIN_ACTION_TIME"] <= self.dic_traffic_env_conf["YELLOW_TIME"]:
print ("MIN_ACTION_TIME should include YELLOW_TIME")
pass
#raise ValueError
# touch new inter_{}.pkl (if exists, remove)
for inter_ind in range(self.dic_traffic_env_conf["NUM_INTERSECTIONS"]):
path_to_log_file = os.path.join(self.path_to_log, "inter_{0}.pkl".format(inter_ind))
f = open(path_to_log_file, "wb")
f.close()
def reset(self):
print("# self.eng.reset() to be implemented")
cityflow_config = {
"interval": self.dic_traffic_env_conf["INTERVAL"],
"seed": 0,
"laneChange": False,
"dir": self.path_to_work_directory+"/",
"roadnetFile": self.dic_traffic_env_conf["ROADNET_FILE"],
"flowFile": self.dic_traffic_env_conf["TRAFFIC_FILE"],
"rlTrafficLight": self.dic_traffic_env_conf["RLTRAFFICLIGHT"],
"saveReplay": self.dic_traffic_env_conf["SAVEREPLAY"],
"roadnetLogFile": "frontend/web/roadnetLogFile.json",
"replayLogFile": "frontend/web/replayLogFile.txt"
}
print("=========================")
print(cityflow_config)
with open(os.path.join(self.path_to_work_directory,"cityflow.config"), "w") as json_file:
json.dump(cityflow_config, json_file)
self.eng = engine.Engine(os.path.join(self.path_to_work_directory,"cityflow.config"), thread_num=1)
# self.load_roadnet()
# self.load_flow()
# get adjacency
if self.dic_traffic_env_conf["USE_LANE_ADJACENCY"]:
self.traffic_light_node_dict = self._adjacency_extraction_lane()
else:
self.traffic_light_node_dict = self._adjacency_extraction()
# initialize intersections (grid)
self.list_intersection = [Intersection((i+1, j+1), self.dic_traffic_env_conf, self.eng,
self.traffic_light_node_dict["intersection_{0}_{1}".format(i+1, j+1)],self.path_to_log)
for i in range(self.dic_traffic_env_conf["NUM_ROW"])
for j in range(self.dic_traffic_env_conf["NUM_COL"])]
self.list_inter_log = [[] for i in range(self.dic_traffic_env_conf["NUM_ROW"] *
self.dic_traffic_env_conf["NUM_COL"])]
# set index for intersections and global index for lanes
self.id_to_index = {}
count_inter = 0
for i in range(self.dic_traffic_env_conf["NUM_ROW"]):
for j in range(self.dic_traffic_env_conf["NUM_COL"]):
self.id_to_index['intersection_{0}_{1}'.format(i+1, j+1)] = count_inter
count_inter += 1
self.lane_id_to_index = {}
count_lane = 0
for i in range(len(self.list_intersection)): # TODO
for j in range(len(self.list_intersection[i].list_entering_lanes)):
lane_id = self.list_intersection[i].list_entering_lanes[j]
if lane_id not in self.lane_id_to_index.keys():
self.lane_id_to_index[lane_id] = count_lane
count_lane += 1
# build adjacency_matrix_lane in index from _adjacency_matrix_lane
for inter in self.list_intersection:
inter.build_adjacency_row_lane(self.lane_id_to_index)
# get new measurements
system_state_start_time = time.time()
if self.dic_traffic_env_conf["FAST_COMPUTE"]:
self.system_states = {"get_lane_vehicles": self.eng.get_lane_vehicles(),
"get_lane_waiting_vehicle_count": self.eng.get_lane_waiting_vehicle_count(),
"get_vehicle_speed": None,
"get_vehicle_distance": None
}
else:
self.system_states = {"get_lane_vehicles": self.eng.get_lane_vehicles(),
"get_lane_waiting_vehicle_count": self.eng.get_lane_waiting_vehicle_count(),
"get_vehicle_speed": self.eng.get_vehicle_speed(),
"get_vehicle_distance": self.eng.get_vehicle_distance()
}
print("Get system state time: ", time.time()-system_state_start_time)
update_start_time = time.time()
for inter in self.list_intersection:
inter.update_current_measurements_map(self.system_states)
print("Update_current_measurements_map time: ", time.time()-update_start_time)
#update neighbor's info
neighbor_start_time = time.time()
if self.dic_traffic_env_conf["NEIGHBOR"]:
for inter in self.list_intersection:
neighbor_inter_ids = inter.neighbor_ENWS
neighbor_inters = []
for neighbor_inter_id in neighbor_inter_ids:
if neighbor_inter_id is not None:
neighbor_inters.append(self.list_intersection[self.id_to_index[neighbor_inter_id]])
else:
neighbor_inters.append(None)
inter.dic_feature = inter.update_neighbor_info(neighbor_inters,deepcopy(inter.dic_feature))
print("Update_neighbor time: ", time.time()-neighbor_start_time)
state, done = self.get_state()
# print(state)
return state
def step(self, action):
step_start_time = time.time()
list_action_in_sec = [action]
list_action_in_sec_display = [action]
for i in range(self.dic_traffic_env_conf["MIN_ACTION_TIME"]-1):
if self.dic_traffic_env_conf["ACTION_PATTERN"] == "switch":
list_action_in_sec.append(np.zeros_like(action).tolist())
elif self.dic_traffic_env_conf["ACTION_PATTERN"] == "set":
list_action_in_sec.append(np.copy(action).tolist())
list_action_in_sec_display.append(np.full_like(action, fill_value=-1).tolist())
average_reward_action_list = [0]*len(action)
for i in range(self.dic_traffic_env_conf["MIN_ACTION_TIME"]):
action_in_sec = list_action_in_sec[i]
action_in_sec_display = list_action_in_sec_display[i]
instant_time = self.get_current_time()
self.current_time = self.get_current_time()
before_action_feature = self.get_feature()
# state = self.get_state()
if self.dic_traffic_env_conf['DEBUG']:
print("time: {0}".format(instant_time))
else:
if i == 0:
print("time: {0}".format(instant_time))
self._inner_step(action_in_sec)
# get reward
if self.dic_traffic_env_conf['DEBUG']:
start_time = time.time()
reward = self.get_reward()
if self.dic_traffic_env_conf['DEBUG']:
print("Reward time: {}".format(time.time()-start_time))
for j in range(len(reward)):
average_reward_action_list[j] = (average_reward_action_list[j] * i + reward[j]) / (i + 1)
# average_reward_action = (average_reward_action*i + reward[0])/(i+1)
# log
self.log(cur_time=instant_time, before_action_feature=before_action_feature, action=action_in_sec_display)
next_state, done = self.get_state()
print("Step time: ", time.time() - step_start_time)
return next_state, reward, done, average_reward_action_list
def _inner_step(self, action):
# copy current measurements to previous measurements
for inter in self.list_intersection:
inter.update_previous_measurements()
# set signals
# multi_intersection decided by action {inter_id: phase}
for inter_ind, inter in enumerate(self.list_intersection):
inter.set_signal(
action=action[inter_ind],
action_pattern=self.dic_traffic_env_conf["ACTION_PATTERN"],
yellow_time=self.dic_traffic_env_conf["YELLOW_TIME"],
all_red_time=self.dic_traffic_env_conf["ALL_RED_TIME"]
)
# run one step
for i in range(int(1/self.dic_traffic_env_conf["INTERVAL"])):
self.eng.next_step()
if self.dic_traffic_env_conf['DEBUG']:
start_time = time.time()
system_state_start_time = time.time()
if self.dic_traffic_env_conf["FAST_COMPUTE"]:
self.system_states = {"get_lane_vehicles": self.eng.get_lane_vehicles(),
"get_lane_waiting_vehicle_count": self.eng.get_lane_waiting_vehicle_count(),
"get_vehicle_speed": None,
"get_vehicle_distance": None
}
else:
self.system_states = {"get_lane_vehicles": self.eng.get_lane_vehicles(),
"get_lane_waiting_vehicle_count": self.eng.get_lane_waiting_vehicle_count(),
"get_vehicle_speed": self.eng.get_vehicle_speed(),
"get_vehicle_distance": self.eng.get_vehicle_distance()
}
# print("Get system state time: ", time.time()-system_state_start_time)
if self.dic_traffic_env_conf['DEBUG']:
print("Get system state time: {}".format(time.time()-start_time))
# get new measurements
if self.dic_traffic_env_conf['DEBUG']:
start_time = time.time()
update_start_time = time.time()
for inter in self.list_intersection:
inter.update_current_measurements_map(self.system_states)