-
Notifications
You must be signed in to change notification settings - Fork 0
/
traffic.py
322 lines (236 loc) · 9.72 KB
/
traffic.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
#!/usr/bin/env python
import os, os.path
import random
import string
import time
import datetime
import cherrypy
from cherrypy.process import wspbus, plugins
from cherrypy.process.plugins import Monitor
from cherrypy import log
from scenarioloader import ScenarioLoader
from referencetrackshandler import ReferenceTracksHandler
from scenario import Scenario
import simplejson as json
from predictor import Predictor
from copy import deepcopy
import progaconstants
import requests
import pdb
"""
The Traffic object is istanciated by proga and it handles the dynamic evolution of the aircraft
during the simulation. It is constructed as a cherrypy Monitor, this means one of its function is
called periodically to update the traffic situation
"""
class Traffic(plugins.Monitor):
exposed = True
def __init__(self, bus, sleeping_time):
#chiama costruttore super-classe e registra la funzione che viene ripetuta
plugins.Monitor.__init__(self, bus, self.startSimulation, sleeping_time)
self.sleeping_time = sleeping_time
self.myState = None
self.scenarioloader = None
self.scenario = None
self.t0 = None
self.tracks = None
self.justStarted = True
self.startedTracks = None
self.finishedTracks = None
self.referenceTracksHandler = None
self.simulationStarted = False
self.ownship_intent = None
self.ownship_intent_id = None
self.ownship_id = None
def getActiveFlightIDs(self):
if self.startedTracks == None:
return []
ids = [t.getTrackId() for t in self.startedTracks]
#pdb.set_trace()
return ids
def getOwnshipIntentID(self):
return self.ownship_intent_id
def getOwnshipIntent(self):
return self.ownship_intent
def sendFinishedCommand(self):
s = requests.Session()
r = s.post('http://127.0.0.1:8080/traffic', params={'command':'stop'})
def startSimulation(self):
elapsed_seconds = time.time() - self.t0
int_elapsed_seconds = int(elapsed_seconds)
#cherrypy.log("elapsed seconds:"+str(int_elapsed_seconds))
#pdb.set_trace()
if len(self.finishedTracks) == len(self.tracks):
#cherrypy.engine.publish(progaconstants.SIMULATION_FINISHED_CHANNEL_NAME)
pass
#self.sendFinishedCommand()
else:
if len(self.startedTracks) != len(self.tracks):
#in questo punto ci andranno gli aerei che si muovono
if self.justStarted:
#se abbiamo appena iniziato, passati 0 secondi, faccio partire tutte le tracce senza delay o con anticipo
for track in self.tracks:
#cherrypy.log("i'm track " + track.getTrackId() + " and my start is " + str(track.getStartTime()))
if track.getStartTime() <= 0 and track.hasStarted()==False:
#cherrypy.log("starting track " + track.getTrackId())
track.startTrack()
self.startedTracks.append(track)
self.justStarted = False
else:
for track in self.tracks:
if track.getStartTime() == int_elapsed_seconds and track.hasStarted()==False:
#cherrypy.log("starting track " + track.getTrackId())
track.startTrack()
self.startedTracks.append(track)
#cherrypy.log('\nsono passati ' + str(elapsed_seconds) + 'secondi')
for startedTrack in self.startedTracks[:]:
if self.makeStep(startedTrack,elapsed_seconds) == True:
self.startedTracks.remove(startedTrack)
#pdb.set_trace()
cherrypy.log('%s' % (self.getStrMyState()), context='OWNSHIP')
cherrypy.engine.publish(progaconstants.UPDATED_TRAFFIC_CHANNEL_NAME,elapsed_seconds)
def makeStep(self, track, elapsed_seconds):
cherrypy.log("making step of track: " + track.getTrackId(), context='TRAFFIC')
#pdb.set_trace()
arrived = not track.next(elapsed_seconds, progaconstants.PLAYER_POINTER_INCREMENT)
stringToLog = json.dumps(track.getCurrentState())
cherrypy.log('%s' % (stringToLog), context='TRAFFIC')
if arrived:
#pdb.set_trace()
self.finishedTracks.append(track)
return arrived
@cherrypy.tools.accept(media='text/plain')
def GET(self, item=None):
#cherrypy.log("position requested")
#ci va una condizione per ogni item che vogliamo esporre
#in questo caso my-state
if item == None or item == progaconstants.ITEM_MY_STATE:
#cherrypy.log("returning position")
return self.getStrMyState()
if item == None or item == progaconstants.ITEM_TRAFFIC:
#cherrypy.log("returning traffic")
return self.getJSONTraffic()
if item == progaconstants.ITEM_TRAFFIC4MFS:
#cherrypy.log("returning traffic for microsoft fsx", context="MFS")
return self.getJSONTraffic(progaconstants.ITEM_TRAFFIC4MFS)
#questo rende sempre una versione stringa della posizione
def getStrMyState(self):
return json.dumps(self.myState)
#return str(self.myState['lat']) + ' ' + str(self.myState['lon'])
def getMyState(self):
return self.myState
def getJSONTraffic(self,requestFrom=None):
return json.dumps(deepcopy(self.getTraffic(requestFrom)))
def getTraffic(self, requestFrom=None):
traffic = {}
for track in self.startedTracks:
if requestFrom == None:
traffic[track.track_id] = track.getCurrentState()
else:
#pdb.set_trace()
traffic[track.track_id] = track.getCurrentState()
#traffic[track.track_id] = track.getFutureState(4)
return traffic
def getIntent(self, track_id):
return ''
"""
Computes the initial weights of the reference tracks for each flight in the scenario.
Returns a dictionary made like the followinf
['AZA1234' : (ReferenceTrack1, ReferenceTrack2, ReferenceTrack3 ... ReferenceTrackN) ]
Each ReferenceTrack item in the value list is a ReferenceTrack object. You can access the computed weight by
the ReferenceTrack.w field.
"""
def computeInitialWeightsForReferenceTracks(self):
weights = {}
for track in self.tracks:
if track.declaredIntent == None:
#cherrypy.log("computing weights for track:" + track.track_id)
#returns a list of referencetrack objects without any weight but already associated with the given id
all_intents = self.referenceTracksHandler.getAllIntents(track.track_id)
wt = []
for intent in all_intents:
intent.w = 1.0/len(all_intents)
wt.append(intent)
weights[track.track_id] = wt
else:
declared_intent = track.declaredIntent
declared_intent.w = progaconstants.DECLARED_INTENT_PROBABILITY
#cherrypy.log("computing weights for track:" + track.track_id)
if declared_intent.refTrackID == None:
#cherrypy.log("computing weights for track:" + track.track_id)
all_intents = self.referenceTracksHandler.getAllIntents(track.track_id)
wt = []
wt.append(declared_intent)
residual = 1.0 - progaconstants.DECLARED_INTENT_PROBABILITY
for intent in all_intents:
intent.w = residual/len(all_intents)
wt.append(intent)
weights[track.track_id] = wt
else:
#cherrypy.log("computing weights for track:" + track.track_id)
all_intents = self.referenceTracksHandler.getAllIntents(track.track_id)
wt = []
wt.append(declared_intent)
residual = 1.0 - progaconstants.DECLARED_INTENT_PROBABILITY
for intent in all_intents:
pdb.set_trace
if intent.refTrackID != declared_intent.refTrackID:
intent.w = residual/(len(all_intents)-1)
wt.append(intent)
weights[track.track_id] = wt
#pdb.set_trace()
return weights
def POST(self,command=None,scenario_name=None):
if command == 'start':
if self.scenarioloader is not None:
cherrypy.log("Starting simulation", context='AUTO')
#si iscrive
self.subscribe()
#si iscrive anche agli aggiornamenti di posizione pubblicati nel canale MYPOSITION_CHANNEL_NAME
#e gli associa una funzione di gestione
self.bus.subscribe(progaconstants.MYSTATE_CHANNEL_NAME,self.setMyState)
#fa partire tutto
self.t0 = time.time()
self.startedTracks = []
self.start()
cherrypy.engine.publish(progaconstants.SIMULATION_STARTED_CHANNEL_NAME, self.t0)
self.simulationStarted = True
else:
cherrypy.log("No scenario loaded. Can't start simulation", context='AUTO')
raise cherrypy.HTTPError(400,"Can't start simulation: no scenario was loaded. Use loadscenario as command and provide a scenario folder")
if command == 'stop':
cherrypy.log("Simulation is finished", context='AUTO')
#pdb.set_trace();
cherrypy.engine.publish(progaconstants.SIMULATION_STOPPED_CHANNEL_NAME)
self.unsubscribe()
self.stop()
self.simulationStarted = False
if command == 'loadscenario':
if self.simulationStarted:
cherrypy.log("Can't load scenario while simulation is running. Stop simulation first and then load new scenario", context='AUTO')
else:
self.referenceTracksHandler = ReferenceTracksHandler(scenario_name)
self.scenarioloader = ScenarioLoader(progaconstants.SCENARIOS_FOLDER, self.referenceTracksHandler)
self.scenario = self.scenarioloader.loadScenario(scenario_name)
self.tracks = self.scenario.getTracks()
self.initialWeights = self.computeInitialWeightsForReferenceTracks()
self.ownship_intent_id = self.scenario.getOwnshipIntentID()
self.ownship_intent = self.referenceTracksHandler.getReferenceTrack(self.ownship_intent_id)
cherrypy.engine.publish(progaconstants.INITIAL_WEIGHTS_COMPUTED_CHANNEL_NAME,self.initialWeights)
#for flight_id, r_tracks in self.initialWeights.items():
#cherrypy.log(flight_id + " n references: " + str(len(r_tracks)))
#for t in r_tracks:
#cherrypy.log("ref_track:"+t.refTrackID+" w:"+str(t.w))
self.startedTracks = []
self.finishedTracks = []
cherrypy.engine.publish(progaconstants.SCENARIO_LOADED_CHANNEL_NAME,self.scenario)
#for track in self.tracks:
#cherrypy.log("I'm " + track.getTrackId() + " and i'll start at " + str(track.getStartTime()))
return "hello world"
def setMyState(self, myState):
#cherrypy.log("state set")
self.myState = myState
#pdb.set_trace()
def PUT(self,another_string):
pass
def DELETE(self):
pass