forked from GiorgioRen/distributed-computing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscrete_event_sim.py
More file actions
56 lines (41 loc) · 1.61 KB
/
discrete_event_sim.py
File metadata and controls
56 lines (41 loc) · 1.61 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
import logging
from heapq import *
# TODO: implement the event queue!
# suggestion: have a look at the heapq library (https://docs.python.org/dev/library/heapq.html)
# and in particular heappush and heappop
class Simulation:
"""Subclass this to represent the simulation state.
Here, self.t is the simulated time and self.events is the event queue.
"""
def __init__(self):
"""Extend this method with the needed initialization.
You can call super().__init__() there to call the code here.
"""
self.t = 0 # simulated time
# set up self.events as an empty queue
self.events = []
def schedule(self, delay, event):
"""Add an event to the event queue after the required delay."""
# add event to the queue at time self.t + delay
heappush(self.events, (self.t + delay, event))
def run(self, max_t=float('inf')):
"""Run the simulation. If max_t is specified, stop it at that time."""
while self.events != [] : # as long as the event queue is not empty:
t, event = heappop(self.events) # get the first event from the queue
if t > max_t:
break
self.t = t
event.process(self)
def log_info(self, msg):
logging.info(f'{self.t:.2f}: {msg}')
class Event:
"""
Subclass this to represent your events.
You may need to define __init__ to set up all the necessary information.
"""
def __init__(self):
pass
def __lt__(self, other):
return id(self) < id(other)
def process(self, sim):
raise NotImplementedError