-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
250 lines (175 loc) · 7.06 KB
/
app.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
import csv
import sys
import os
router_matrix = []
matrix_set = 0
nodes = []
distances = {}
unvisited = {}
previous = {}
visited = {}
interface = {}
path = []
start = 0
end = 0
# Function to print the choices when program starts.
def print_choices():
os.system("figlet Link State Routing Simulator")
print("\n######################################################\n")
print("(1) Input Network Topology File")
print("(2) Build a Connection Table")
print("(3) Shortest Path to Destination Router")
print("(4) Exit")
print("\n######################################################\n")
pass
def check_choices(command):
if not command.isdigit():
print("Please enter a number as command from given choices..")
return -1
else:
command = int(command)
if command > 4 or command < 1 :
print("Please enter a valid command from given choices..")
return -1
else:
return command
# Function to process the given input file.
def process_file(fname):
global matrix_set
global router_matrix
matrix_set = 0
router_matrix = []
with open(fname) as f:
router_matrix=[list(map(int,x.split())) for x in f] # Data from input file is stored in a two dimensional list(array).
matrix_set = 1
print("\nReview original topology matrix:\n")
for line in router_matrix :
for item in line :
print(item, end=' ')
print()
print()
set_distances(router_matrix) # Distances are stored in a dictionary - key,value pair - with source router as key and distances in form of a dictionary as value.
# Function to store the distances in dictionary format.
def set_distances(router_matrix):
global distances
global nodes
distances = {}
nodes = []
num_nodes = len(router_matrix)
for i in range(num_nodes):
tempdict = {}
for j in range(num_nodes):
if i!=j and router_matrix[i][j]!=-1:
tempdict[j+1] = router_matrix[i][j]
distances[i+1] = tempdict
nodes.append(i+1)
# print("Distances:- \n",distances)
# print("Nodes:- \n",nodes)
def dijkstra(start):
global distances
global nodes
global unvisited
global previous
global visited
global interface
# set the values to none for initialization.
unvisited = {node: None for node in nodes}
previous = {node: None for node in nodes}
interface = {node: None for node in nodes}
visited = {node: None for node in nodes}
current = int(start)
currentDist = 0
unvisited[current] = currentDist
while True:
for next, distance in list(distances[current].items()):
if next not in unvisited: continue
newDist = currentDist + distance
if not unvisited[next] or unvisited[next] > newDist:
unvisited[next] = newDist
previous[next] = current
if not interface[current]:
interface[next] = next
else:
interface[next] = interface[current]
visited[current] = currentDist
del unvisited[current]
done = 1
for x in unvisited:
if unvisited[x]:
done = 0
break
if not unvisited or done:
break
elements = [node for node in list(unvisited.items()) if node[1]]
current, currentDist = sorted(elements, key = lambda x: x[1])[0]
# Function to generate the shortest path using the parent table generated by function dijkstra.
def shortest_path(start, end):
global path
path = []
dest = int(end)
src = int(start)
path.append(dest)
while dest != src:
path.append(previous[dest])
dest = previous[dest]
path.reverse()
if __name__ == "__main__":
print_choices()
command = 0
# Run till user wants to exit.
while command !=4 :
command = check_choices(input("Choice: "))
# Accept the topology file.
if command == 1:
if matrix_set == 1:
answer = input("\nThe network topology is already uploaded. Do you want to overwrite? (Y/N) :")
if matrix_set == 0 or answer == 'Y' or answer == 'y':
filename = input("\nInput original network topology matrix data file[ NxN distance matrix. (value : -1 for no link, 0 for self loop) : ")
if os.path.isfile(filename):
process_file(filename)
start = 0
end = 0
else:
print("\nThe file does not exist. Please try again..")
# Accept the source router and display the connection table.
elif command == 2:
if matrix_set == 1 :
start = input("\nSelect a source router : ")
if start.isdigit() and int(start) > 0 and int(start) <= len(router_matrix):
dijkstra(start)
print("\nDestination Next Hop")
for key in interface:
print(key,"\t\t", interface[key])
else:
start = 0
print("\nPlease enter a valid source router.")
else:
print("\nNo network topology matrix exist. Please upload the data file first.. ")
# Accept the destination router and display the shortest path and cost.
elif command == 3:
if matrix_set == 1 :
end = input("\nSelect a destination router : ")
if end.isdigit() and int(end) > 0 and int(end) <= len(router_matrix):
if int(start) == 0:
print("\nNo source router selected yet. Please select a source router using choice : 2.")
elif int(start) == int(end):
print("\nSource and Destination routers are same. Please select a different destination router.")
elif not previous[int(end)] :
print("\nThere does not exist any route from Source : %s to Destination : %s. \nPlease select a different destination router. " %(start, end))
else:
shortest_path(start,end)
print("\nThe shortest path from router %s to router %s : " %(start, end), end=' ')
for item in path:
print(str(item) + ' ', end=' ')
print('')
cost = 0
if visited[int(end)]:
cost = visited[int(end)]
print("\nThe total cost is : ", cost)
else:
print("\nPlease enter a valid destination router.")
pass
else :
print("\nNo network topology matrix exist. Please upload the data file first.. ")
#Exit if command is 4.
print("\nBye!\n")