forked from wingsweihua/presslight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
construct_sample.py
282 lines (234 loc) · 11.6 KB
/
construct_sample.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
import numpy as np
import pickle
from multiprocessing import Pool, Process
import os
import traceback
import pandas as pd
class ConstructSample:
def __init__(self, path_to_samples, cnt_round, dic_traffic_env_conf):
self.parent_dir = path_to_samples
self.path_to_samples = path_to_samples + "/round_" + str(cnt_round)
self.cnt_round = cnt_round
self.dic_traffic_env_conf = dic_traffic_env_conf
self.logging_data_list_per_gen = None
self.hidden_states_list = None
self.samples = []
self.samples_all_intersection = [None]*self.dic_traffic_env_conf['NUM_INTERSECTIONS']
def load_data(self, folder, i):
try:
f_logging_data = open(os.path.join(self.path_to_samples, folder, "inter_{0}.pkl".format(i)), "rb")
logging_data = pickle.load(f_logging_data)
f_logging_data.close()
return 1, logging_data
except Exception as e:
print("Error occurs when making samples for inter {0}".format(i))
print('traceback.format_exc():\n%s' % traceback.format_exc())
return 0, None
def load_data_for_system(self, folder):
'''
Load data for all intersections in one folder
:param folder:
:return: a list of logging data of one intersection for one folder
'''
self.logging_data_list_per_gen = []
# load settings
print("Load data for system in ", folder)
self.measure_time = self.dic_traffic_env_conf["MEASURE_TIME"]
self.interval = self.dic_traffic_env_conf["MIN_ACTION_TIME"]
for i in range(self.dic_traffic_env_conf['NUM_INTERSECTIONS']):
pass_code, logging_data = self.load_data(folder, i)
if pass_code == 0:
return 0
self.logging_data_list_per_gen.append(logging_data)
return 1
def load_hidden_state_for_system(self, folder):
print("loading hidden states: {0}".format(os.path.join(self.path_to_samples, folder, "hidden_states.pkl")))
# load settings
if self.hidden_states_list is None:
self.hidden_states_list = []
try:
f_hidden_state_data = open(os.path.join(self.path_to_samples, folder, "hidden_states.pkl"), "rb")
hidden_state_data = pickle.load(f_hidden_state_data) # hidden state_data is a list of numpy array
# print(hidden_state_data)
print(len(hidden_state_data))
self.hidden_states_list.append(np.stack(hidden_state_data, axis=2))
return 1
except Exception as e:
print("Error occurs when loading hidden states in ", folder)
print('traceback.format_exc():\n%s' % traceback.format_exc())
return 0
def construct_state(self,features,time,i):
'''
:param features:
:param time:
:param i: intersection id
:return:
'''
state = self.logging_data_list_per_gen[i][time]
assert time == state["time"]
if self.dic_traffic_env_conf["BINARY_PHASE_EXPANSION"]:
state_after_selection = {}
for key, value in state["state"].items():
if key in features:
if "cur_phase" in key:
state_after_selection[key] = self.dic_traffic_env_conf['PHASE'][self.dic_traffic_env_conf['SIMULATOR_TYPE']][value[0]]
else:
state_after_selection[key] = value
else:
state_after_selection = {key: value for key, value in state["state"].items() if key in features}
# print(state_after_selection)
return state_after_selection
def _construct_state_process(self, features, time, state, i):
assert time == state["time"]
if self.dic_traffic_env_conf["BINARY_PHASE_EXPANSION"]:
state_after_selection = {}
for key, value in state["state"].items():
if key in features:
if "cur_phase" in key:
state_after_selection[key] = self.dic_traffic_env_conf['PHASE'][self.dic_traffic_env_conf['SIMULATOR_TYPE']][value[0]]
else:
state_after_selection[key] = value
else:
state_after_selection = {key: value for key, value in state["state"].items() if key in features}
return state_after_selection, i
def get_reward_from_features(self, rs):
reward = {}
reward["sum_lane_queue_length"] = np.sum(rs["lane_queue_length"])
reward["sum_lane_wait_time"] = np.sum(rs["lane_sum_waiting_time"])
reward["sum_lane_num_vehicle_left"] = np.sum(rs["lane_num_vehicle_left"])
reward["sum_duration_vehicle_left"] = np.sum(rs["lane_sum_duration_vehicle_left"])
reward["sum_num_vehicle_been_stopped_thres01"] = np.sum(rs["lane_num_vehicle_been_stopped_thres01"])
reward["sum_num_vehicle_been_stopped_thres1"] = np.sum(rs["lane_num_vehicle_been_stopped_thres1"])
reward['pressure'] = np.absolute(np.sum(rs["pressure"]))
return reward
def cal_reward(self, rs, rewards_components):
r = 0
for component, weight in rewards_components.items():
if weight == 0:
continue
if component not in rs.keys():
continue
if rs[component] is None:
continue
r += rs[component] * weight
return r
def construct_reward(self,rewards_components,time, i):
rs = self.logging_data_list_per_gen[i][time + self.measure_time - 1]
assert time + self.measure_time - 1 == rs["time"]
rs = self.get_reward_from_features(rs['state'])
r_instant = self.cal_reward(rs, rewards_components)
# average
list_r = []
for t in range(time, time + self.measure_time):
#print("t is ", t)
rs = self.logging_data_list_per_gen[i][t]
assert t == rs["time"]
rs = self.get_reward_from_features(rs['state'])
r = self.cal_reward(rs, rewards_components)
list_r.append(r)
r_average = np.average(list_r)
return r_instant, r_average
def judge_action(self,time,i):
if self.logging_data_list_per_gen[i][time]['action'] == -1:
raise ValueError
else:
return self.logging_data_list_per_gen[i][time]['action']
def make_reward(self, folder, i):
'''
make reward for one folder and one intersection,
add the samples of one intersection into the list.samples_all_intersection[i]
:param i: intersection id
:return:
'''
if self.samples_all_intersection[i] is None:
self.samples_all_intersection[i] = []
if i % 100 == 0:
print("make reward for inter {0} in folder {1}".format(i, folder))
list_samples = []
try:
total_time = int(self.logging_data_list_per_gen[i][-1]['time'] + 1)
# construct samples
time_count = 0
for time in range(0, total_time - self.measure_time + 1, self.interval):
state = self.construct_state(self.dic_traffic_env_conf["LIST_STATE_FEATURE"], time, i)
reward_instant, reward_average = self.construct_reward(self.dic_traffic_env_conf["DIC_REWARD_INFO"],
time, i)
action = self.judge_action(time, i)
if time + self.interval == total_time:
next_state = self.construct_state(self.dic_traffic_env_conf["LIST_STATE_FEATURE"],
time + self.interval - 1, i)
else:
next_state = self.construct_state(self.dic_traffic_env_conf["LIST_STATE_FEATURE"],
time + self.interval, i)
sample = [state, action, next_state, reward_average, reward_instant, time,
folder+"-"+"round_{0}".format(self.cnt_round)]
list_samples.append(sample)
self.samples_all_intersection[i].extend(list_samples)
return 1
except Exception as e:
print("Error occurs when making rewards in generator {0} for intersection {1}".format(folder, i))
print('traceback.format_exc():\n%s' % traceback.format_exc())
return 0
def make_reward_for_system(self):
'''
Iterate all the generator folders, and load all the logging data for all intersections for that folder
At last, save all the logging data for that intersection [all the generators]
:return:
'''
for folder in os.listdir(self.path_to_samples):
print(folder)
if "generator" not in folder:
continue
if self.dic_traffic_env_conf['MODEL_NAME'] == "STGAT":
if not self.evaluate_sample(folder) or not self.load_data_for_system(folder) or not self.load_hidden_state_for_system(folder):
continue
else:
if not self.evaluate_sample(folder) or not self.load_data_for_system(folder):
continue
for i in range(self.dic_traffic_env_conf['NUM_INTERSECTIONS']):
pass_code = self.make_reward(folder, i)
if pass_code == 0:
continue
for i in range(self.dic_traffic_env_conf['NUM_INTERSECTIONS']):
self.dump_sample(self.samples_all_intersection[i],"inter_{0}".format(i))
if self.dic_traffic_env_conf["MODEL_NAME"]=="STGAT":
self.dump_hidden_states("")
def dump_hidden_states(self, folder):
total_hidden_states = np.vstack(self.hidden_states_list)
print("dump_hidden_states shape:",total_hidden_states.shape)
if folder == "":
with open(os.path.join(self.parent_dir, "total_hidden_states.pkl"),"ab+") as f:
pickle.dump(total_hidden_states, f, -1)
elif "inter" in folder:
with open(os.path.join(self.parent_dir, "total_hidden_states_{0}.pkl".format(folder)),"ab+") as f:
pickle.dump(total_hidden_states, f, -1)
else:
with open(os.path.join(self.path_to_samples, folder, "hidden_states_{0}.pkl".format(folder)),'wb') as f:
pickle.dump(total_hidden_states, f, -1)
def evaluate_sample(self, generator_folder):
return True
print("Evaluate samples")
list_files = os.listdir(os.path.join(self.path_to_samples, generator_folder, ""))
df = []
# print(list_files)
for file in list_files:
if ".csv" not in file:
continue
data = pd.read_csv(os.path.join(self.path_to_samples, generator_folder, file))
df.append(data)
df = pd.concat(df)
num_vehicles = len(df['Unnamed: 0'].unique()) -len(df[df['leave_time'].isna()]['leave_time'])
if num_vehicles < self.dic_traffic_env_conf['VOLUME']* self.dic_traffic_env_conf['NUM_ROW'] and self.cnt_round > 10: # Todo Heuristic
return False
else:
return True
def dump_sample(self, samples, folder):
if folder == "":
with open(os.path.join(self.parent_dir, "total_samples.pkl"),"ab+") as f:
pickle.dump(samples, f, -1)
elif "inter" in folder:
with open(os.path.join(self.parent_dir, "total_samples_{0}.pkl".format(folder)),"ab+") as f:
pickle.dump(samples, f, -1)
else:
with open(os.path.join(self.path_to_samples, folder, "samples_{0}.pkl".format(folder)),'wb') as f:
pickle.dump(samples, f, -1)