single link network simulation complete

parent 179db6b4
...@@ -3,24 +3,95 @@ from Node import Node ...@@ -3,24 +3,95 @@ from Node import Node
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Link(SystemEntity): class Link(SystemEntity):
def __init__(self,link): def __init__(self,link,network,linkDelay):
SystemEntity.__init__(self) '''
#link = (1,2) :param link: (1,2)
:param network:
:param linkDelay: delay of a link
'''
SystemEntity.__init__(self,network)
self.upNode = link[0] self.upNode = link[0]
self.downNode = link[1] self.downNode = link[1]
self.link = link self.link = link
self.messageQueue = []
self.linkDelay = linkDelay
''' '''
contains string command and its corresponding method to be executed contains string command and its corresponding method to be executed
useful to execute task from todolist useful to execute task from todolist
''' '''
self.commands = {"sendMessage": self.sendMessage, self.commands = {"delieverMessage": self.delieverMessage,
} }
pass pass
def delieverMessage(self,time,params):
'''
:param time:
:param params: [ whomtodeliever , payload ]
:return:
'''
node = self.network.nodes.get(params[0])
node.enqueMessge((time, params[1]))
pass
def enqueMessge(self,message):
'''
:param message: (timestamp , payload) --- timestamp is the tick value at which node has inserted this message in queue
payload #1 : ('NOde1', 'Node2', 'Content of message')
payload #2 :
:return:
'''
self.messageQueue.append(message)
print("message enqued")
def dequeMessge(self):
return self.messageQueue.pop(0)
def scheduleMessageDelievery(self,time,payload):
task = ("delieverMessage",payload[1],payload) #(command,whomtodeliever,what to deliever)
scheduledTime = str(int(time) + self.linkDelay)
self.todoList[scheduledTime].append(task)
def simulate(self,time): def simulate(self,time):
logger.info("simulating .. ") # logger.info("simulating .. ")
'''
Process message first then process task in todo-list
because messages in the link are placed in last tick
and the processing of those messages may create some tasks for current tick
all messages will be proceessed i.e., at the end of each tick simulation links will not have
any unprocessed message the receive buffer or message-queue
'''
#todo process messages in queue
# generate tasks for todolist based on messges
for message in self.messageQueue:
self.scheduleMessageDelievery(message[0],message[1])
# TODO : perform task from todolist which are relevant for current tick
try:
tasks = self.todoList.pop(time)
for task in tasks:
command = self.commands.get(task[0])
command(time,task[1:])
except KeyError as ke:
# not task pending at this time
pass
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -6,11 +6,11 @@ import logging ...@@ -6,11 +6,11 @@ import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Network(SystemEntity): class Network():
def __init__(self): def __init__(self):
SystemEntity.__init__(self)
self.nodes = {}#{1 : Node(1),2:Node(2)} self.nodes = {}#{1 : Node(1),2:Node(2)}
self.links = {} #{(1,2):Link(1-2),(2,1):Link(2,1),(3,2):Link(3*2)} linkID = tuple(1,2) self.links = {} #{(1,2):Link(1-2),(2,1):Link(2,1),(3,2):Link(3*2)} linkID = tuple(1,2)
self.networkClockTime = 0
def setupNetwork(self): def setupNetwork(self):
''' '''
...@@ -29,7 +29,7 @@ class Network(SystemEntity): ...@@ -29,7 +29,7 @@ class Network(SystemEntity):
reader = csv.reader(f) reader = csv.reader(f)
for row in reader: for row in reader:
node = row[0] # tuple of a link node = row[0] # tuple of a link
self.nodes.update({node:Node(node)}) self.nodes.update({node:Node(node,self)})
# print(self.nodes.get('1')) #keys are strings # print(self.nodes.get('1')) #keys are strings
...@@ -37,7 +37,8 @@ class Network(SystemEntity): ...@@ -37,7 +37,8 @@ class Network(SystemEntity):
reader = csv.reader(f) reader = csv.reader(f)
for row in reader: for row in reader:
link = tuple(row[0].split()) # tuple of a link link = tuple(row[0].split()) # tuple of a link
self.links.update({link:Link(link)}) linkDelay = 1
self.links.update({link:Link(link,self,linkDelay)})
# adding adjacent nodes list to each node # adding adjacent nodes list to each node
self.nodes.get(link[0]).adjacentNodes.append(link[1]) self.nodes.get(link[0]).adjacentNodes.append(link[1])
...@@ -45,15 +46,12 @@ class Network(SystemEntity): ...@@ -45,15 +46,12 @@ class Network(SystemEntity):
# print(self.links.get(('1', '2'))) #keys are strings # print(self.links.get(('1', '2'))) #keys are strings
pass pass
def simulate(self,time): def simulate(self,time):
logger.info("simulating .. ") logger.info("simulating .. ")
self.networkClockTime = time
# Note links should be simulated before nodes # Note links should be simulated before nodes
# in order to receive the messge which is supposed to be received in this tick # in order to receive the messge which is supposed to be received in this tick
for link in self.links.values(): for link in self.links.values():
......
...@@ -3,25 +3,70 @@ import logging ...@@ -3,25 +3,70 @@ import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Node(SystemEntity): class Node(SystemEntity):
def __init__(self,id): def __init__(self,id,network):
SystemEntity.__init__(self) SystemEntity.__init__(self,network)
self.id = id self.id = id
self.adjacentNodes = [] self.adjacentNodes = []
self.messageQueue = []
self.commands={"sendMessage":self.sendMessage, self.commands={"sendMessage":self.sendMessage,
} }
def sendMessage(self,params):
logger.info(str(params))
def enqueMessge(self,message):
'''
:param message: (timestamp , payload) --- timestamp is the tick value at which node has inserted this message in queue
payload #1 : ('NOde1', 'Node2', 'Content of message')
payload #2 :
:return:
'''
self.messageQueue.append(message)
print("message enqued")
def dequeMessge(self):
return self.messageQueue.pop(0)
def sendMessage(self,time,params):
'''
:param params: ('1','2','hello2')
:return:
'''
link = self.network.links.get((params[0],params[1]))
link.enqueMessge((time,params))
logger.info("Sending Message : " + str((time,params)))
pass pass
def processMessage(self,time,payload):
print("fianlly reachec : " + str(payload))
def simulate(self,time): def simulate(self,time):
logger.info("simulating .. ") # logger.info("simulating .. ")
'''
Process message first then process task in todo list
Here it is just intuition , i don`t what should be processing sequence
all messages will be proceessed i.e., at the end of each tick simulation links will not have
any unprocessed message the receive buffer or message-queue
'''
# todo process messages in queue
# generate tasks for todolist based on messges
for message in self.messageQueue:
self.processMessage(message[0],message[1]) # message : (time,(payload))
# TODO : perform task from todolist which are relevant for current tick
try: try:
tasks = self.todoList.pop(time) tasks = self.todoList.pop(time)
for task in tasks: for task in tasks:
command = self.commands.get(task[0]) command = self.commands.get(task[0])
command(task[1:]) command(time,task[1:])
except KeyError as ke: except KeyError as ke:
# not task pending at this time # not task pending at this time
pass pass
......
...@@ -5,8 +5,9 @@ logger = logging.getLogger(__name__) ...@@ -5,8 +5,9 @@ logger = logging.getLogger(__name__)
class SystemEntity(object): class SystemEntity(object):
def __init__(self): def __init__(self,network):
self.todoList = defaultdict(list) self.todoList = defaultdict(list)
self.network = network
#{'key': [('sendMessage','1','2','hello2'), ('sendMessage','1','3','hello3')],'key2':["hello"]} #{'key': [('sendMessage','1','2','hello2'), ('sendMessage','1','3','hello3')],'key2':["hello"]}
# key is timestamp at which to perfrom action # key is timestamp at which to perfrom action
...@@ -21,16 +22,3 @@ class SystemEntity(object): ...@@ -21,16 +22,3 @@ class SystemEntity(object):
''' '''
pass pass
class x(SystemEntity):
def __init__(self,id):
self.id = id
SystemEntity.__init__(self)
if __name__ == '__main__':
y = SystemEntity()
print(y.todoList)
m = x(1)
m.todoList["key"].append("a value")
m.todoList["key"].append("another value")
print(m.todoList)
...@@ -31,7 +31,7 @@ def simulateNetwork(net): ...@@ -31,7 +31,7 @@ def simulateNetwork(net):
populateTodolist(network) populateTodolist(network)
for time in range(15): for time in range(7):
logger.info("TIme : "+str(time)) logger.info("TIme : "+str(time))
network.simulate(str(time)) network.simulate(str(time))
......
1 10 sendMessage 1 2 hello2 1 5 sendMessage 1 2 hello2
1 9 sendMessage 1 4 hello2
1 10 sendMessage 1 2 hello2
1 8 sendMessage 1 2 hello2
2 11 sendMessage 1 2 hello2
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment