This repository was archived by the owner on May 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSIM
More file actions
executable file
·391 lines (291 loc) · 11.6 KB
/
Copy pathSIM
File metadata and controls
executable file
·391 lines (291 loc) · 11.6 KB
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
#!/usr/bin/python3
#NOTE: RUN FROM COMMAND LINE AS:
#python3 SIM 10 sim-traces-0-1/uniform-0-1-00.dat sim-traces-0-1/uniform-0-1-01.dat sim-traces-0-1/uniform-0-1-02.dat
#
# Stacia Near and Chin Isaac-Heslop
# Simulation assignment
# Crosswalk sim
#
import sys
import os
from enum import Enum
import io
#importing of the class files
from classes import safety_signals as s
from classes import ped
from classes import auto as auto
from classes import event
from classes import stats as st
from classes import input as i
import argparse
from classes.event import event_type
try:
import Queue as Q # ver. < 3.0
except ImportError:
import queue as Q
#statistical imports
import math
from random import expovariate # exponenial(lamb)
from random import normalvariate #(mu, sigma)
from random import uniform
from statistics import mean
from statistics import median
#mport matplotlib.pyplot as plt
#import numpy as np
#Global declarations
#TODO: priority queues: notation is "put" and "get"
eventList = event.event_list #event.event_list = Q.PriorityQueue()
s.event_list = event.event_list
#peds_at_crosswalk = Q.PriorityQueue()
#s.waiting_peds = peds_at_crosswalk
pedList = ped.ped_list #ped.ped_list = []
s.ped_list = ped.ped_list
auto_list = []
n = 0
t = 0
autoTracefile = ""
pedTracefile = ""
buttonTracefile = ""
pedNum = 1
s.t = t
autoNum = 1
#initialize pointers in stats
#st.autoNum = autoNum
#st.pedNum = pedNum- no longer global
st.n = n
#safety signal instace global
safetySignal = s.safety_signals()
debugAuto = False
def main():
parseArgs()
#if (debugAuto):
#runAutoTest()
run()
#-----------------------------------------------------------------------------------
#Main simulation loop
#-----------------------------------------------------------------------------------
def run():
#Use globals
## these variables are all used in the same function main so no need to describe as global since not used elsewhere without being passed
global n
global t
global eventList #event.event_list
global peds_at_crosswalk
global pedList #ped.ped_list
global auto_list
global pedNum
global autoNum
global red_timer
global safetySignal
#initialize sim variables
t = 0 #sim_time
#TEST CODE
#i.input.testRandomValues(i)
#To begin, we will spawn the first auto and ped
#when each arrival is processed, it spawns the next arrival of the same type
#spawn does not occur if the number exceeds user input "N" value
spawnAuto()
spawnPed()
while not event.event_list.empty(): #event_list non empty
e = eventList.get() #event.event_list.get() #remove current from event list
t = e.time
s.t = t #update for safety signals class
print(safetySignal.signal)
print("Event: time %.2f type %s id %s" %(e.time,e.type,e.id))
if e.type == event.event_type.AUTO_ARRIVAL:
#if auto arrival, spawn the next auto
#and schedule the exit of the current auto
spawnAuto()
#Schedule auto exit in safety signal instead
#trigger on yellow and calculate delay
#scheduleExitAuto(e.id)
elif e.type == event.event_type.PED_ARRIVAL:
spawnPed()
#scheduleExitPed(e.id)
#wrp = safetySignal.walk_request_pushed(s.signal, pedNum)
#safetySignal.button_press( s, wrp )
elif e.type == event.event_type.PED_AT_BUTTON:
wrp = safetySignal.walk_request_pushed(pedNum)
safetySignal.ped_at_button(e.data )
elif e.type == event.event_type.PED_IMPATIENT:
#wrp = safetySignal.walk_request_pushed(pedNum )
safetySignal.button_press( 1 )
elif e.type == event.event_type.GREEN_EXPIRES:
safetySignal.green_expires()
elif e.type == event.event_type.YELLOW_EXPIRES:
safetySignal.yellow_expires()
#Calculate auto delay on yellow
#schedule exit events for all active autos
time_yellow_began = t - 8; #yellow lasts 8 sec, and it just expired at t
exitedAutosList = []
#check for ids of autos who already have exit events
for e in eventList.queue:
if (e.type == event_type.AUTO_EXIT):
exitedAutosList.append(e.id)
for a in auto_list:
#if exit already scheduled, dont schedule a duplicate
if exitedAutosList.__contains__(a.id):
continue;
if auto_list.__sizeof__() != 0:
st.autoNum +=1
delay = a.calculate_auto_delay(time_yellow_began)
scheduleExitAuto(a.id, a.exit_time_if_no_delay() + delay)
#TODO WELFORDS EQUATIONS
elif e.type == event.event_type.RED_EXPIRES:
safetySignal.red_expires()
elif e.type == event.event_type.AUTO_EXIT:
exitAuto(e.id)
elif e.type == event.event_type.PED_EXIT:
exitPed(e.time, e.data)
#once the event list is empty, final statistics are ready to be output
print("Global pedNum: ", pedNum ," Global autonum: ", autoNum);
st.stats.print_final_statistics(st)
i.input.closeFiles(i)
#-----------------------------------------------------------------------------------
#End Main simulation
#-----------------------------------------------------------------------------------
def spawnAuto():
global eventList #event.event_list
global auto_list
global autoNum
#no spawns if exceed number
if (autoNum > n):
return
auto_interarrival = i.input.getNextAutoInterarrival(i)
auto_arrival = t + auto_interarrival
velocity = i.input.getNextAutoSpeed(i)
newAuto = auto.auto(auto_arrival, velocity, autoNum)
eventList.put( event.event(auto_arrival, event.event_type.AUTO_ARRIVAL, autoNum ))
#event.event_list.put( event.event(auto_arrival, event.event_type.AUTO_ARRIVAL, autoNum))
auto_list.append(newAuto)
autoNum += 1
#st.autoNum = autoNum
#ok its kind of a hacky solution to update the autoNum
#that belongs to the stat class here, but its the best I could do
#because for some reason NO OTHER CLASS can import SIM or see its global variables
print("Spawn auto: " , str(newAuto))
def spawnPed():
global eventList #event.event_list
global peds_at_crosswalk
global pedList #ped.ped_list
global pedNum
global safetySignal
if (pedNum > n):
return
ped_interarrival = i.input.getNextPedInterarrival(i)
ped_arrival = t + ped_interarrival
velocity = i.input.getNextPedSpeed(i)
newPed = ped.ped(ped_arrival, velocity, pedNum)
eventList.put( event.event( ped_arrival, event.event_type.PED_ARRIVAL, pedNum ))
eventList.put( event.event( ped_arrival + safetySignal.get_ped( newPed ), event.event_type.PED_AT_BUTTON, pedNum, newPed ) )
pedList.append( newPed )
pedNum += 1
def scheduleExitAuto(id, true_exit_time):
global eventList #event.event_list
for a in auto_list:
if a.id == id:
#if correct id, keep as "a"
#TODO these should all be before the break
eventList.put( event.event(true_exit_time, event.event_type.AUTO_EXIT, a.id ))
#event.event_list.put( event.event(true_exit_time, event.event_type.AUTO_EXIT, a.id))
break
#def scheduleExitPed(id):
# global event_list
#
# for p in ped_list:
# if p.id == id:
# #TODO make it actual exit time not exit time with no delay
# event_list.put( event.event( p.exit_time_if_no_delay(), event.event_type.PED_EXIT, p.id ) )
# break
def exitAuto(id):
global auto_list
for a in auto_list:
if a.id == id:
auto_list.remove(a) #if correct id, remove from list of autos
break
#CALCULATE DELAY
#a.calculate_auto_delay()
def exitPed(time, ped):
if pedList.__sizeof__() != 0:
st.pedNum += 1
ped.calculate_ped_delay( time )
def parseArgs():
#TODO: must handle any problems with argument values and exit with descriptive non zero
#use globals!
global n
global autoTracefile
global pedTracefile
global buttonTracefile
#note that "SIM" counts as an arg
if len(sys.argv) != 5 :
print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))
print("Usage: python3 SIM [1 2 3 4]\n \
1. N, the number of automobile and pedestrian arrivals to generate (N>0).\n \
2. A Uniform(0,1) trace file of random values for automobile arrivals and speeds.\n \
3. A Uniform(0,1) trace file of random values for pedestrian arrivals and speeds.\n \
4. A Uniform(0,1) trace file of random values for resolving crosswalk button presses.\n")
sys.exit (1)
n = int(sys.argv[1])
st.n = n
if (n <= 0):
print("Need positive number of auto/pedestrian arrivals.")
sys.exit(1)
autoTracefile = sys.argv[2] #Uniform(0,1)
pedTracefile = sys.argv[3] #Uniform(0,1)
buttonTracefile = sys.argv[4] #Uniform(0,1)
#pass in file object to input handler once it has been opened
try:
i.autoTracefile = open(autoTracefile, 'r')
i.pedTracefile = open(pedTracefile, 'r')
i.buttonTracefile = open(buttonTracefile, 'r')
except IOError:
print("Could not read file")
sys.exit(1)
except Exception as err:
print(err.args[0], err.args[1])
sys.exit(1)
if __name__ == "__main__":
main()
#main simulation, but with ONLY auto
'''
def runAutoTest():
global n
global t
global eventList #event.event_list
global peds_at_crosswalk
global pedList #ped.ped_list
global auto_list
global pedNum
global autoNum
global red_light_times
global safetySignal
t = 0 #sim_time
i.input.testRandomValues(i)
lightNum = 0
eventList.put( event.event(t+35, event.event_type.GREEN_EXPIRES, lightNum))
spawnAuto()
while not event.event_list.empty(): #event_list non empty
if (autoNum >= n): break
e = eventList.get() #event.event_list.get() #remove current from event list
t = e.time
s.t = t #update for safety signals class
print("Event: time %.2f type %s id %s" %(e.time,e.type,e.id))
if e.type == event.event_type.AUTO_ARRIVAL:
spawnAuto()
elif e.type == event.event_type.GREEN_EXPIRES:
eventList.put( event.event(t+8+18, event.event_type.YELLOW_EXPIRES, lightNum))
elif e.type == event.event_type.YELLOW_EXPIRES:
eventList.put( event.event(t+35, event.event_type.GREEN_EXPIRES, lightNum))
#Calculate auto delay on yellow
#schedule exit events for all active autos
time_yellow_began = t - 8; #yellow lasts 8 sec, and it just expired at t
for a in auto_list:
delay = a.calculate_auto_delay(time_yellow_began)
scheduleExitAuto(a.id, a.exit_time_if_no_delay() + delay)
#TODO WELFORDS EQUATIONS
elif e.type == event.event_type.AUTO_EXIT:
exitAuto(e.id)
#once the event list is empty, final statistics are ready to be output
st.stats.print_final_statistics(st)
'''