-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra_simulator.py
815 lines (533 loc) · 26 KB
/
dijkstra_simulator.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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
#importing the required libraries
#Tkinter is standard GUI package
#matplotlib provides object oriented API for embedding plots in GUI
#pylab interface used for interactive calculations and plotting
import Tkinter as tk
import ttk
import tkMessageBox
import tkFileDialog
import copy
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pylab
#different types of fonts used
LARGE_FONT= ("Verdana", 20)
MEDIUM_FONT= ("Verdana",16)
SMALL_FONT= ("Verdana",12)
#User defined custom exception, used for catching incorrect node values
class IncorrectNodeException(Exception):
pass
#main class for UI
class SeaofBTCapp(tk.Tk):
#def __init__ is the function that is called automatically upon an object's construction
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Computer Networks Project")
#container for all the frames
self.container = tk.Frame(self)
#self is used to reference the object itself
self.container.pack(side="top", fill="both", expand = True)
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
self.frames = {}
# this is a dictionary of frames
#all static windows are contained in this frame
for F in (StartPage, enter_source_node,selection_page,add_node_page,add_edge_page):
frame = F(self.container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
#used to display a frame
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
#tkraise shows one window at a time by bringing a window in front of the other
#method for formation of connection table
def connection_table(self,pre, source, g):
nodes = len(g[0])
a = copy.copy(pre)
c = {}
c[source] = '-'
for i in range(nodes):
l = []
if i == source:
continue
j = i
l = [i]
while j != source:
l.append(a[j][0])
j =a[j][0]
l = l[::-1]
c[i] = l[1]
return c
#returns a dictionary of values in the connection table
def dijkstra_algo(self,g, source):
#implementation of dijkstra algorithm
nodes = len(g[0])
pre = {}
dist = {}
q = []
for i in range(nodes):
dist[i] = 999
pre[i] = [-1]
q.append(i)
dist[source] = 0
while len(q) != 0:
n_dist = {}
for i in q:
n_dist[i] = dist[i]
u = min(n_dist.items(), key=lambda x: x[1])
u = u[0]
q.remove(u)
for i in range(nodes):
if g[u][i] not in [0,-1]:
alt = dist[u] + g[u][i]
if alt < dist[i]:
dist[i] = alt
pre[i] = [u]
elif alt == dist[i]:
pre[i].append(u)
return pre
def get_the_network(self):
#reading the matrix file that is taken as an input from the user
try:
file = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
data=file.read()
g = []
data = data.split('\n')
for i in data:
g.append(map(int,i.split()))
self.data = g
self.show_frame(enter_source_node)
#Exception for invalid entry like special characters or any other combinations.
except ValueError:
tkMessageBox.showerror(
"Input File Error",
"Oops! That was not a valid input file. Please Try again with a valid '.txt' file..."
)
#method to get the source node entry from the user
def get_source(self, source):
try:
self.source = int(source.get())
#Checking if source entered not a valid node from topology, then an exception will be raised
if self.source > (len(self.data)-1):
raise IncorrectNodeException
self.show_frame(selection_page)
#Exception for invalid entry like special characters or any other combinations.
except ValueError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a valid Source Node..."
)
#Custom exception for incorrect node or any other integer other than node entered
except IncorrectNodeException:
tkMessageBox.showerror(
"Node Error",
"Oops! That was not a valid node for the topology selected. Please Try again with a valid Source Node..."
)
return
#method to display the network
def display_network(self):
frame = display_network_page(self.container, self)
self.frames[display_network_page] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(display_network_page)
#method to create an object for destination page and raising it above other windows
def enter_destination(self):
try:
self.pre = self.dijkstra_algo(self.data,self.source)
self.connection = self.connection_table(self.pre,self.source,self.data)
frame = enter_destination_page(self.container, self)
self.frames[enter_destination_page] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(enter_destination_page)
except IndexError:
tkMessageBox.showerror(
"Memory Error",
"Oops! There are too many destinations entered earlier. Please use Back to Home button to start again from fresh..."
)
return
#method to get the destination node from the user
def network_to_destination(self,entry):
try:
self.destination = int(entry.get())
#Checking if destination entered not a valid node from topology, then an exception will be raised
if self.destination > (len(self.data)-1):
raise IncorrectNodeException
frame = network_to_destination_page(self.container, self)
self.frames[network_to_destination_page] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(network_to_destination_page)
#Exception for invalid entry like special characters or any other combinations.
except ValueError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a valid Destination Node..."
)
#Custom exception for incorrect node or any other integer other than destination node entered
except IncorrectNodeException:
tkMessageBox.showerror(
"Node Error",
"Oops! That was not a valid node for the topology selected. Please Try again with a valid Destination Node..."
)
return
#method to create an object of connection table frame and raising it above other windows
def display_connection_table(self):
try:
self.pre = self.dijkstra_algo(self.data,self.source)
self.connection = self.connection_table(self.pre,self.source,self.data)
frame = display_connection_table_page(self.container, self)
self.frames[display_connection_table_page] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(display_connection_table_page)
except ValueError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a valid weights..."
)
except IndexError:
tkMessageBox.showerror(
"Memory Error",
"Oops! There are too many connection tables opened earlier. Please use Back to Home button to start again from fresh..."
)
return
#method to create an object of display shortest path frame and raising it above other windows
def display_shortest_path(self):
try:
self.pre = self.dijkstra_algo(self.data,self.source)
self.connection = self.connection_table(self.pre,self.source,self.data)
frame = display_shortest_path_page(self.container, self)
self.frames[display_shortest_path_page] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(display_shortest_path_page)
except IndexError:
tkMessageBox.showerror(
"Memory Error",
"Oops! There are too many shortest paths displayed earlier. Please use Back to Home button to start again from fresh..."
)
return
#method to add a node
def add_node(self,new_node):
try:
self.new_node = new_node.get().split()
self.new_node = map(int,self.new_node)
if len(self.new_node) != len(self.data):
raise IncorrectNodeException
self.new_node.append(0)
for i in range(len(self.data)):
self.data[i].append(self.new_node[i])
self.data.append(self.new_node)
self.show_frame(selection_page)
except ValueError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a valid weights..."
)
except IndexError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a space between values..."
)
except IncorrectNodeException:
tkMessageBox.showerror(
"Node Error",
"Oops! That was not a valid number of node. Please Try with %s nodes..." % len(self.data)
)
return
#method to add an edge
def add_edge(self,new_edge,new_weight):
try:
self.new_edge = new_edge.get().split()
self.new_edge = map(int,self.new_edge)
#Checking if entered edge, whose weight needs to be modified contains two valid nodes from topology,
#if not raise an exception
for i in self.new_edge:
if i not in range(0, len(self.data)):
raise IncorrectNodeException
self.new_weight = new_weight.get()
self.new_weight = int(self.new_weight)
self.data[self.new_edge[0]][self.new_edge[1]] = self.new_weight
self.data[self.new_edge[1]][self.new_edge[0]] = self.new_weight
self.show_frame(selection_page)
except ValueError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a valid weight..."
)
except IndexError:
tkMessageBox.showerror(
"Input Error",
"Oops! That was not a valid input. Please Try again with a space between values..."
)
#Custom exception for incorrect node or any other integer other than destination node entered
except IncorrectNodeException:
tkMessageBox.showerror(
"Node Error",
"Oops! That was not a valid node for the topology selected. Please Try again with a valid Node for Edge..."
)
return
class StartPage(tk.Frame):
#StartPage is inheriting from TK FRAME
#here controller represents the container
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
#creating a label
label = ttk.Label(self, text="Implementation Of Dijkstra Algorithm", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#creating a button
button = ttk.Button(self, text="Enter the network matrix",
command=lambda: controller.get_the_network())
button.pack()
class enter_source_node(tk.Frame):
#enter_source_node is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating a label
label = ttk.Label(self, text="Please Enter the source node", font=LARGE_FONT)
label.pack(pady=10,padx=10)
entry = ttk.Entry(self, width=10)
entry.pack(pady=10,padx=10)
#creating a button
button = ttk.Button(self, text="Enter!!",
command=lambda: controller.get_source(entry))
button.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack(pady=10,padx=10)
class selection_page(tk.Frame):
#selection_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating a label
label = ttk.Label(self, text="Select from the following options", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#creating buttons
#click button to display the network frame
button1 = ttk.Button(self, text="Display the Network",
command=lambda: controller.display_network())
button1.pack(pady=10,padx=10)
#click button to display the connection table frame
button2 = ttk.Button(self, text="Display the connection table",
command=lambda: controller.display_connection_table())
button2.pack(pady=10,padx=10)
#click button to display the shortest path to all nodes frame
button3 = ttk.Button(self, text="Display the shortest path to all nodes",
command=lambda: controller.display_shortest_path())
button3.pack(pady=10,padx=10)
#click button to display path to a destination frame
button6 = ttk.Button(self, text="Display path to a destination",
command=lambda: controller.enter_destination())
button6.pack(pady=10,padx=10)
#click button to add an extra node frame
button4 = ttk.Button(self, text="Add an extra node",
command=lambda: controller.show_frame(add_node_page))
button4.pack(pady=10,padx=10)
#click button to add or modify the edge weight frame
button5 = ttk.Button(self, text="Add or modify edge weight",
command=lambda: controller.show_frame(add_edge_page))
button5.pack(pady=10,padx=10)
#click button to take us back to the home page frame
button6 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button6.pack(pady=10,padx=10)
#click button to take us back to the selection page frame
button7 = ttk.Button(self, text="Back to Source Node Selection Page",
command=lambda: controller.show_frame(enter_source_node))
button7.pack(pady=10,padx=10)
class display_connection_table_page(tk.Frame):
#display_connection_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating a scrollbar to scroll through the connection table frame
scrollbar = tk.Scrollbar(self)
scrollbar.pack(side = tk.RIGHT, fill= tk.Y)
#creating a list box to populate the connection table
mylist = tk.Listbox(self, yscrollcommand = scrollbar.set )
mylist.insert(tk.END, "\nRouter %s Connection Table \n" % controller.source)
mylist.insert(tk.END, "{:<8} {:<15}".format('Destination ',' Interface'))
for k, v in controller.connection.iteritems():
mylist.insert(tk.END,"\t {:<8} \t {:<15}".format(k, v))
mylist.insert(tk.END,"\n")
mylist.pack(fill = "both",expand=True)
#creating a button and click the button to get back to selection page
button1 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button1.pack()
class display_shortest_path_page(tk.Frame):
#display_shortest_path_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
main_graph = nx.Graph()
i=0
for row in controller.data:
j=0
for col in row:
if col not in [0,-1]:
main_graph.add_edge(i,j, weight = int(controller.data[i][j]) )
j = j+1
i = i+1
#creating scrollbar to scroll through the shortest path frame
scrollbar = tk.Scrollbar(self)
scrollbar.pack(side = tk.RIGHT, fill= tk.Y)
mylist = tk.Listbox(self, yscrollcommand = scrollbar.set )
self.a = copy.copy(controller.pre)
for i in range(len(controller.data)):
if i == controller.source:
continue
mylist.insert(tk.END,"smallest path from node %s to node %s" % (controller.source,i))
paths = nx.all_shortest_paths(main_graph,source=controller.source,target= i, weight = 'weight')
for path in paths:
mylist.insert(tk.END,"path = %s" % path)
self.cost = self.calculating_total_cost(path,controller.data)
mylist.insert(tk.END,"Cost = %s " % self.cost)
mylist.insert(tk.END,"\n")
scrollbar.config( command = mylist.yview )
mylist.pack(fill = "both",expand=True)
button1 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button1.pack()
#method for calculating total cost
def calculating_total_cost(self,l,g):
sum1 = 0
i = 0
j = 1
for r in range(len(l)-1):
sum1 = sum1 + g[l[i]][l[j]]
i += 1
j += 1
return sum1
class add_node_page(tk.Frame):
#add_node_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating a label
label = ttk.Label(self, text="Enter the edge weights from new node to other nodes", font=LARGE_FONT)
label.pack(pady=10,padx=10)
entry = ttk.Entry(self, width=10)
entry.pack(pady=10,padx=10)
#creating buttons
#click the button to add the node taken as input from user to the network
button = ttk.Button(self, text="Add Node",
command=lambda: controller.add_node(entry))
button.pack(pady=10,padx=10)
#click button to go back to selection page frame
button2 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button2.pack()
#click button to go back to home page frame
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack(pady=10,padx=10)
class add_edge_page(tk.Frame):
#add_edge_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating labels
label = ttk.Label(self, text="Enter the edge to change the weight(For ex:4 5)", font=LARGE_FONT)
label.pack(pady=10,padx=10)
entry_edge = ttk.Entry(self, width=10)
entry_edge.pack(pady=10,padx=10)
label = ttk.Label(self, text="Enter the new weight", font=LARGE_FONT)
label.pack(pady=10,padx=10)
entry_weight = ttk.Entry(self, width=10)
entry_weight.pack(pady=10,padx=10)
#creating buttons
#click button to make the changes to the network
button = ttk.Button(self, text="Change Edge Weight",
command=lambda: controller.add_edge(entry_edge, entry_weight))
#calling the function add_edge to make changes in the network
button.pack(pady=10,padx=10)
#click button to go to the Selection page frame
button2 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button2.pack()
#click button to go to back to home page frame
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack(pady=10,padx=10)
class display_network_page(tk.Frame):
#display_network_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
graph = nx.Graph()
i = 0
edge_labels = {}
for row in controller.data:
j=0
for col in row:
if col not in [0,-1]:
graph.add_edge(i,j)
edge_labels[(i,j)] = int(controller.data[i][j])
j = j+1
i = i+1
f = plt.figure(figsize=(5,4))
plt.axis('off')
pos = nx.circular_layout(graph)
nx.draw(graph,pos,with_labels = True)
nx.draw_networkx_edge_labels(graph,pos,edge_labels = edge_labels)
#creating a canvas to draw the network
canvas = FigureCanvasTkAgg(f, master=self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
canvas.draw()
#click button to go to back to selection page frame
button1 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button1.pack()
class enter_destination_page(tk.Frame):
#enter_destination_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#creating a label
label = ttk.Label(self, text="Please Enter the destination node", font=LARGE_FONT)
label.pack(pady=10,padx=10)
entry = ttk.Entry(self, width=10)
entry.pack(pady=10,padx=10)
#creating buttons
button = ttk.Button(self, text="Enter!!",
command=lambda: controller.network_to_destination(entry))
button.pack(pady=10,padx=10)
#click button to go to back to selection page frame
button1 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button1.pack()
class network_to_destination_page(tk.Frame):
#network_to_destination_page is inheriting from TK FRAME
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
main_graph = nx.Graph()
i=0
for row in controller.data:
j=0
for col in row:
if col not in [0,-1]:
main_graph.add_edge(i,j, weight = int(controller.data[i][j]) )
j = j+1
i = i+1
graph = nx.Graph()
edge_labels = {}
for p in nx.all_shortest_paths(main_graph,source=controller.source,target=controller.destination, weight = 'weight'):
edge = []
for i in range(len(p)-1):
edge = [p[i],p[i+1]]
graph.add_edge(edge[0],edge[1])
edge_labels[(p[i],p[i+1])] = int(controller.data[p[i]][p[i+1]])
f = plt.figure(figsize=(5,4))
pos = nx.circular_layout(graph)
nx.draw(graph,pos,with_labels = True)
nx.draw_networkx_edge_labels(graph,pos,edge_labels = edge_labels)
#creating a canvas to draw the shortest path network
canvas = FigureCanvasTkAgg(f, master=self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
canvas.draw()
#click button to go to back to selection page frame
button1 = ttk.Button(self, text="Back to Selection Page",
command=lambda: controller.show_frame(selection_page))
button1.pack()
#object of sea class
app = SeaofBTCapp()
#for recursive call
app.mainloop()