-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_HyperETA.py
executable file
·309 lines (275 loc) · 11.1 KB
/
run_HyperETA.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
import json
import pickle
import numpy
import pandas
from pandas import DataFrame
from dtw import accelerated_dtw
import math
from math import cos
from math import sin
from math import radians
from math import asin
from preprocess import trajModel
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--trainDataFile', type = str)
parser.add_argument('--trajModel', type = str)
parser.add_argument('--testDataFile', type = str)
parser.add_argument('--testTrajPreprocessed', type = str)
args = parser.parse_args()
config = json.load(open('./config.json', 'r'))
def getOverlayOneCubeWithPointAmount(trajList1, trajList2, dtime, distX, distY, angDiffConst, pointAmountRatio=0):
maxTime = trajList1[9] + dtime
minTime = trajList1[9] - dtime
trajList3 = trajList2.loc[(trajList2[9] > minTime) & (trajList2[9] < maxTime),]
if trajList3.size <= 0:
# print('trajList3.size <= 0')
return None
trajList4 = trajList3.loc[abs(trajList3[9] - trajList1[9]) < dtime,]
if trajList4.size <= 0:
# print('trajList4.size <= 0, < dtime')
return None
trajList4 = trajList4.loc[abs(trajList4[3] - trajList1[3]) < distX,]
if trajList4.size <= 0:
# print('trajList4.size <= 0, < distX')
return None
trajList4 = trajList4.loc[abs(trajList4[4] - trajList1[4]) < distY,]
if trajList4.size <= 0:
# print('trajList4.size <= 0, < distY')
return None
trajList4 = trajList4.loc[angleDiff(trajList4[8], trajList1[8]) < angDiffConst,]
if trajList4.size <= 0:
# print('trajList4.size <= 0, < angDiffConst')
return None
while pointAmountRatio > 0:
trajList5 = trajList4.loc[abs(trajList4[0] - trajList1[0]) < (trajList1[0] * (1 - pointAmountRatio)),]
if trajList5.size > 0:
trajList4 = trajList5
break
pointAmountRatio -= 0.1
if trajList4.size <= 0:
return None
n1 = trajList4.shape[0]
area1 = DataFrame(numpy.zeros((n1, 3), dtype=int))
area1[0] = trajList4[5].values # 其它軌
area1[1] = trajList4[1].values # 其它軌第幾cube
area1[2] = trajList4.index.values # 其它軌此cube在總名單上第幾
return area1
def getOverlayOneCube(trajList1, trajList2, dtime, distX, distY, angDiffConst):
maxTime = trajList1[9] + dtime
minTime = trajList1[9] - dtime
trajList3 = trajList2.loc[(trajList2[9] > minTime) & (trajList2[9] < maxTime),]
trajList4 = trajList3.loc[abs(trajList3[9] - trajList1[9]) < dtime,]
trajList4 = trajList4.loc[abs(trajList4[3] - trajList1[3]) < distX,]
trajList4 = trajList4.loc[abs(trajList4[4] - trajList1[4]) < distY,]
trajList4 = trajList4.loc[angleDiff(trajList4[8], trajList1[8]) < angDiffConst,]
n1 = trajList4.shape[0]
area1 = DataFrame(numpy.zeros((n1, 3), dtype=int))
area1[0] = trajList4[5].values # 其它軌
area1[1] = trajList4[1].values # 其它軌第幾cube
area1[2] = trajList4.index.values # 其它軌此cube在總名單上第幾
return area1
def angleDiff(a, b):
result = abs(a - b)
result = result.values
if len(a) > 1:
index = result > 180
result[index] = 360 - result[index]
else:
if result > 180:
result = 360 - result
return result
def getDistanceXY(x, y):
Long1, Lat1 = x
Long2, Lat2 = y
deltaX = cos(radians(Lat2)) * cos(radians(Long2)) \
- cos(radians(Lat1)) * cos(radians(Long1))
deltaY = cos(radians(Lat2)) * sin(radians(Long2)) \
- cos(radians(Lat1)) * sin(radians(Long1))
deltaZ = sin(radians(Lat2)) - sin(radians(Lat1))
C = numpy.linalg.norm(numpy.array([deltaX, deltaY, deltaZ]))
deltaSigma = 2 * asin(C / 2)
d = round(6371 * 1000 * deltaSigma)
return d
def getDTWeachRow(row, x, mappingTrain, trajTrainOri):
tempTrajOriNo = mappingTrain.loc[
(mappingTrain[2] == row[5]) &
(mappingTrain[4] == row[1])
, 3].to_list()
y = trajTrainOri.loc[
(trajTrainOri[5] == row[5]) &
(trajTrainOri[1].isin(tempTrajOriNo))
, [3, 4]].to_numpy()
d, cost_matrix, acc_cost_matrix, path = accelerated_dtw(x, y, getDistanceXY)
return d
def getTimeByMinDtw(targetNo,
area,
targetTrajOri,
targetMapping,
trajTrain,
trajTrainOri,
mappingTrain):
trajTrainCubesIndex = area[2]
targetTrajOriResetIndex = targetTrajOri.set_index(1)
x = targetTrajOriResetIndex.loc[
targetMapping.loc[targetMapping[4] == targetNo, 3],
[3, 4]
].to_numpy()
# result = []
dfTrajNoWiCubeNo = trajTrain.loc[trajTrainCubesIndex, [5, 1]]
n = dfTrajNoWiCubeNo.shape[0]
result = dfTrajNoWiCubeNo.apply(getDTWeachRow, axis=1, args=(x, mappingTrain, trajTrainOri))
minIndex = result.idxmin()
minTrajTrain = trajTrain.loc[minIndex,]
commonTime = trajTrain.loc[minIndex, 10] - trajTrain.loc[minIndex, 9]
return (commonTime, minIndex, result[minIndex])
def getFullTime2(cube, trajTrainOri, mappingTrain):
targetTrainOri = trajTrainOri.loc[(trajTrainOri[5] == cube[5]),]
indexOri = mappingTrain.loc[(mappingTrain[2] == cube[5]) & (mappingTrain[4] == cube[1]), 3]
result = targetTrainOri.iloc[indexOri.to_list()[-1],]
return result['postTime']
def getTestResult4OneTarget2(targetTrajNo,
trajTest,
trajTestOri,
mappingTest,
trajTrain,
trajTrainOri,
mappingTrain,
epLng, epLat):
targetTraj = trajTest.loc[trajTest[5] == targetTrajNo,].copy()
targetTrajOri = trajTestOri.loc[trajTestOri[5] == targetTrajNo,].copy()
targetMapping = mappingTest.loc[mappingTest[2] == targetTrajNo,].copy()
# result = ignoreBeginOrLastOnePointCube(targetTraj, targetTrajOri, targetMapping, epLng, epLat)
# result = ignoreBeginOrLastOnePointCube_Origi(targetTraj, targetTrajOri, targetMapping)
# if result is None:
# return (0, 0, 0, None)
# targetNew, targetOriNew = result
targetNew = targetTraj.copy()
targetOriNew = targetTrajOri.copy()
targetNew2 = targetNew.copy()
realTime = targetNew.iloc[-1, 10] - targetNew.iloc[0, 9]
realTime2 = realTime
totalTime = 0
n = targetNew.shape[0]
commonTime = 0
tempExpResult = numpy.zeros((n, 4), dtype='int')
tempExpResult[:, 0] = targetNew.iloc[:, 10] - targetNew.iloc[:, 9]
listArea = []
nextPointTime = 0
prePointTime = 0
preCubeTimeDiff = 0
preNextPointTime = 0
countAreaNone = 0
for i2 in range(n):
if i2 > 0:
targetNew.iloc[i2, 9] = targetNew.iloc[i2 - 1, 9] + commonTime
tau = 3600
maxAngle = 10
area = getOverlayOneCubeWithPointAmount(targetNew.iloc[i2,],
trajTrain,
tau,
epLng,
epLat,
maxAngle, 0.5)
if area is None:
countAreaNone += 1
print('ERROR: index=', i2, ' area is None')
flagGiveUp = False
epLngEpLatMultiply = 1
while area is None:
if tau < 86400:
tau += 3600
elif maxAngle < 180:
maxAngle = 180
elif epLngEpLatMultiply < 10:
epLngEpLatMultiply += 1
else:
flagGiveUp = True
break
area = getOverlayOneCubeWithPointAmount(targetNew.iloc[i2,],
trajTrain,
tau,
epLng * epLngEpLatMultiply,
epLat * epLngEpLatMultiply,
maxAngle, 0.5)
if flagGiveUp:
print('Give Up!')
continue
commonTime, minIndex, dtwResult = getTimeByMinDtw(targetNew.iloc[i2, 1],
area,
targetOriNew,
targetMapping,
trajTrain,
trajTrainOri,
mappingTrain)
commonTime2 = getFullTime2(trajTrain.loc[minIndex,], trajTrainOri, mappingTrain)
commonTime += commonTime2
tempExpResult[i2, 2] = commonTime
totalTime += commonTime
tempExpResult[i2, 3] = dtwResult
confidence = float(n - countAreaNone) / float(n)
return (totalTime, realTime, realTime2, tempExpResult, confidence)
#python run_HyperETA.py --trainDataFile ./data/train --testDataFile ./data/testRemoveBeginLast
#python run_HyperETA.py --trajModel trainTrajModel.pickle --testTrajPreprocessed testPreprocessed.pickle
if __name__ == '__main__':
if args.trainDataFile :
oTrainTrajModel = trajModel(config)
oTrainTrajModel.inputTraj(args.trainDataFile)
elif args.trajModel :
with open(args.trajModel, 'rb') as f:
oTrainTrajModel = pickle.load(f)
if args.testDataFile :
oTestTrajModel = trajModel(config)
oTestTrajModel.epLat = oTrainTrajModel.epLat
oTestTrajModel.epLng = oTrainTrajModel.epLng
oTestTrajModel.epTime = oTrainTrajModel.epTime
oTestTrajModel.inputTraj(args.testDataFile)
elif args.testTrajPreprocessed :
with open(args.testTrajPreprocessed, 'rb') as f:
oTestTrajModel = pickle.load(f)
trajTrain = oTrainTrajModel.traj
trajTrainOri = oTrainTrajModel.trajOri
mappingTrain = oTrainTrajModel.mapping
epLat = oTrainTrajModel.epLat
epLng = oTrainTrajModel.epLng
epTime = oTrainTrajModel.epTime
trajTest = oTestTrajModel.traj
trajTestOri = oTestTrajModel.trajOri
mappingTest = oTestTrajModel.mapping
trajNoList = numpy.unique(trajTest[5])
expResult = numpy.zeros((trajNoList.max()+1,6),dtype='float')
expResult[:,4] = list(range(trajNoList.max()+1))
for targetTrajNo in trajNoList:
print(targetTrajNo, end=' ', flush=True)
totalTime,realTime,realTime2,tempExpResult,confidence = \
getTestResult4OneTarget2(targetTrajNo,
trajTest,
trajTestOri,
mappingTest,
trajTrain,
trajTrainOri,
mappingTrain,
epLng,epLat)
expResult[targetTrajNo,0] = 1
expResult[targetTrajNo,1] = totalTime
expResult[targetTrajNo,3] = realTime
expResult[targetTrajNo,5] = confidence
expResult2 = expResult[numpy.where(expResult[:, 0] == 1)[0]]
deviation = numpy.absolute(expResult2[:,1] - expResult2[:,3])
eachAPE = deviation * 100 / expResult2[:,3]
with open('output.txt','w') as f:
f.write('MAPE=' + str(eachAPE.mean() ) + '\n')
f.write('RMSE=' + str(numpy.sqrt( (numpy.square(deviation) ).mean() ) ) + '\n')
f.write('MAE=' + str(deviation.mean() ) + '\n')
if args.testDataFile :
print('testFileName=',args.testDataFile)
elif args.testTrajPreprocessed :
print('testFileName=',args.testTrajPreprocessed)
#MAPE
print('MAPE=', eachAPE.mean())
#RMSE
print('RMSE=', numpy.sqrt( (numpy.square(deviation) ).mean() ) )
#MAE
print('MAE=', deviation.mean() )
with open('expResult.pickle', 'wb') as f:
pickle.dump(expResult,f)