-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGraph.py
743 lines (536 loc) · 27 KB
/
Graph.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
import pygame, sys
from pygame.draw import line
from Node import Node
from Edge import Edge
from fringe import PriorityQueue
from TextBox import TextBox
class Graph:
def __init__(self, surface, screen, radius, directed = False):
self.surface = surface
self.screen = screen
self.radius = radius
self.margin = radius * 2 - 5 #> Outside the node
self.padding = radius - 5 #> Inside the node
self.nodes = []
self.edge = []
self.edges = []
self.directed = directed
self.font = pygame.font.Font("RobotoCondensed-Regular.ttf", 20)
self.adding = False
self.showHeuristic = False
self.showCost = False
self.node_sound = pygame.mixer.Sound("sound.wav")
self.node_sound.set_volume(0.1)
self.edge_sound= pygame.mixer.Sound("mouse_click.wav")
self.edge_sound.set_volume(0.1)
def addNode(self, point):
for node in self.nodes:
if (node.insideNode(point, self.margin)):
return False
self.nodes.append(Node(point, radius= self.radius))
self.node_sound.play()
self.adding = True
return True
def removeNode(self, point):
for nodeA in self.nodes:
if (nodeA.insideNode(point, self.padding)):
for nodeB in self.nodes:
nodeB.removeConnection(nodeA)
nodeB.color = Node.default_color
self.nodes.remove(nodeA)
self.edge = []
self.deleteEdge(nodeA)
return
def addEdge(self, point):
if (self.adding):
self.adding = False
else:
for node in self.nodes:
if (node.insideNode(point, self.padding)):
if (node in self.edge):
self.edge = []
node.color = Node.default_color
else:
self.edge.append(node)
self.edge_sound.play()
if len(self.edge) == 2:
if (Edge(self.edge[0], self.edge[1]) not in self.edges):
edge = Edge(self.edge[0], self.edge[1], self.directed,self.surface, self.screen)
self.edges.append(edge)
self.edge[0].addConnection(node, edge)
if not(self.directed):
self.edge[1].addConnection(self.edge[0], edge)
self.edge[0].color = Node.default_color
self.edge = []
def deleteEdge(self, node):
deleteIndex = []
for index, edge in enumerate(self.edges):
if node.center == edge.startingPoint or node.center == edge.endingPoint:
deleteIndex.append(index)
for i in deleteIndex[::-1]:
self.edges.pop(i)
def draw_nodes(self, point):
for state,node in enumerate(self.nodes):
if (node.type == "G"):
node.state = "G"
else:
node.state = "S" + str(state)
pygame.draw.circle(self.surface, (48, 48, 48), (node.center.x + 2, node.center.y + 2), node.radius) #> Shadow
if (node in self.edge): #> Selected
node.color = Node.selected_color
pygame.draw.circle(self.surface, node.color, node.center, node.radius) #> Node fill
node.draw_state(self.font, self.surface)
if (self.showHeuristic):
node.tb.render(self.surface, self.font)
if (node.insideNode(point, self.padding)): #> Hovering over node
# node.color = node.hovered_color
pygame.draw.circle(self.surface, Node.hovered_color, node.center, node.radius, 4) #> Node fill
else:
pygame.draw.circle(self.surface, (0,0,0), node.center, node.radius, 3) #> Node border
def draw_edges(self):
for edge in self.edges:
edge.draw(self.surface, edge.color, (0,255,0))
if (self.showCost):
edge.tb.render(self.surface, self.font)
def addWeight(self, point):
if (self.showHeuristic or self.showCost):
for node in self.nodes:
if(self.showHeuristic):
if (node.tb.rect.collidepoint(point)):
node.heuristic = node.tb.takeInput(self.surface, self.screen, self.font)
return True
if (self.showCost):
for adj in node.adjacent:
if(adj[1].tb.rect.collidepoint(point)):
adj[1].weight = adj[1].tb.takeInput(self.surface, self.screen, self.font)
return True
def isEmpty(self):
return True if len(self.edges) == 0 else False
def reset(self):
self.nodes = []
self.edges = []
self.edge = []
self.reset_nodes()
def printGraph(self):
for node in self.nodes:
print(node)
def path_to_goal(self, current):
cost = 0
while(current.parent is not None):
edge = current.getEdgeFromParent()
cost += edge.weight
edge.color = (76, 82, 245)
current = current.parent
return cost
def start_goal_states(self, point):
for node in self.nodes:
if(node.insideNode(point, self.padding)):
return node
def input_depth_limit(self, point):
prompt = "Please type the maximum depth."
prompt_surf = self.font.render(prompt, True, (0,0,0))
prompt_rect = prompt_surf.get_rect()
prompt_rect.center = self.surface.get_width() // 2, self.surface.get_height() // 2 - 20
box = pygame.Rect(0, 0, prompt_rect.width + 30, prompt_rect.height + 50)
box.center = (self.surface.get_width() // 2, self.surface.get_height() // 2)
tb = TextBox(box.centerx, box.centery + 12, hight=16, border= False, active=(255,255,255), allowZero= True)
pygame.draw.rect(self.surface, (255,255,255), box)
pygame.draw.rect(self.surface, (0,0,0), box, width = 3)
self.surface.blit(prompt_surf, prompt_rect)
tb.render(self.surface, self.font)
pygame.draw.line(self.surface, (0,0,0), (box.left + 50, box.bottom - 15), (box.right - 50, box.bottom - 15), 3)
return (tb.takeInput(self.surface, self.screen, self.font))
def runAlgorithm(self, panel, grid_surf, algorithm, speed, max_depth = -1):
loop = True
start_state = None
goal_states = []
message = ""
cost = 0
message = "Please select ONE START state"
while(loop):
mouse = pygame.mouse.get_pos()
#$ Event Loop
for event in pygame.event.get():
#$ QUIT event
if (event.type == pygame.QUIT):
loop = False
pygame.quit()
sys.exit()
if(event.type == pygame.MOUSEBUTTONDOWN):
self.edge_sound.play()
if(panel.mouseOnPanel(mouse)):
if (panel.showH_btn.detect_click()):
self.showHeuristic = panel.showH_btn.detect_toggle()
elif (panel.speed_btn.detect_click()):
speed = panel.speed_control()
elif (panel.showC_btn.detect_click()):
self.showCost = panel.showC_btn.detect_toggle()
elif (panel.play_btn.detect_click()):
if (start_state is not None and len(goal_states) > 0):
panel.play_btn.detect_toggle()
self.reset_nodes()
self.updateScreen(panel)
if (algorithm == "BFS"):
cost = self.BFS(start_state, goal_states, speed)
elif (algorithm == "UCS"):
cost = self.UCS(start_state, goal_states, speed)
elif (algorithm == "DFS"):
cost = self.DFS(start_state, goal_states, speed)
elif (algorithm == "ITD"):
cost = self.ITD(start_state, goal_states, speed, max_depth)
elif (algorithm == "DLS"):
cost = self.DLS(start_state, goal_states, speed, max_depth)
elif (algorithm == "GRY"):
cost = self.GRDY(start_state, goal_states, speed)
elif (algorithm == "AST"):
cost = self.ASRT(start_state, goal_states, speed)
message2 = f"Start state {start_state} nl Goal stats {list(map(lambda x: x.state, goal_states))}"
if(max_depth != -1):
message2 += f" nl Max Depth {max_depth}"
message ="Algorithm has finished execution nl " + message2 + f" nl Total Cost to goal {cost}. nl Press `Play` to run the algorithm again or nl Press stop search to return back to drawing."
# elif (panel.speed_btn.detect_click()):
# speed = panel.speed_control()
elif(panel.stop_btn.detect_click()):
panel.play_btn.toggled = False
loop = False
self.reset_nodes()
start_state = None
goal_states = []
return True
else: #$ If click on canvas
node = self.start_goal_states(mouse)
if (node is not None):
if (start_state is None):
message = "Please select at least one GOAL state. nl Then press PLAY SEARCH to begin."
node.color = Node.start_state_color
node.type = "S"
start_state = node
elif(start_state is not node):
node.color = Node.goal_state_color
node.type = "G"
goal_states.append(node)
panel.fill()
self.surface.fill((255, 255, 255))
self.surface.blit(grid_surf, (0,0))
panel.btnDetect_hover(mouse)
panel.draw_btns()
panel.displayMessage(message)
self.draw_edges()
self.draw_nodes(mouse)
self.updateScreen(panel)
def updateScreen(self, panel):
self.screen.blit(self.surface, (0,0))
if (panel != 0):
self.screen.blit(panel.panel_surf, (panel.cordX, panel.cordY))
pygame.display.update()
def BFS(self, start_state, goal_states, speed = 750):
print("BFS Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
root = start_state
fringe = [root]
visited = []
goal = goal_states
current = None
state_fringe = []
while(len(fringe) > 0):
for event in pygame.event.get():
if event.type == speed_event:
state_fringe = list(map(lambda x: x.state, fringe))
print(state_fringe)
current = fringe[0]
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
visited.append(current)
fringe = fringe[1:]
current.color = Node.current_node_color
if current in goal:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
for adj in current.adjacent:
if adj[0] not in visited and adj[0] not in fringe:
adj[0].color = Node.in_fringe_color
if (adj[0] not in fringe):
adj[0].parent = current
fringe.append(adj[0])
self.draw_edges()
self.draw_nodes((0,0))
self.screen.blit(self.surface, (0,0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def DFS(self, start_state, goal_states, speed = 750):
print("DFS Search RUN")
pygame.event.clear()
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
root = start_state
fringe = []
fringe.append(root)
visited = []
while (len(fringe) > 0):
# print(pygame.event.get() )
for event in pygame.event.get():
if event.type == speed_event:
state_fringe = list(map(lambda x: x.state, fringe))
print(state_fringe)
current = fringe.pop()
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
visited.append(current)
current.color = Node.current_node_color
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
for adj in current.adjacent:
if adj[0] not in visited:
adj[0].color = Node.in_fringe_color
if (adj[0] not in fringe):
adj[0].parent = current
fringe.append(adj[0])
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def UCS(self, start_state, goal_states, speed = 750):
print("UCS Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
root = start_state
fringe = PriorityQueue()
fringe.add(root, 0)
visited = []
while not fringe.empty():
for event in pygame.event.get():
if event.type == speed_event:
fringe.display_queue()
current = fringe.pop()
visited.append(current)
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
for adj in current.adjacent:
betterSol = current.total_cost + adj[1].weight < adj[0].total_cost
if (adj[0] not in visited) and not(fringe.inside(adj[0])):
if (adj[0].parent is None):
adj[0].parent = current
adj[0].total_cost = adj[0].parent.total_cost + adj[1].weight
fringe.add(adj[0], adj[0].total_cost)
visited.append(adj[0])
adj[0].color = Node.in_fringe_color
elif fringe.inside(adj[0]) and betterSol:
adj[0].parent = current
adj[0].total_cost = adj[0].parent.total_cost + adj[1].weight
fringe.replace((adj[0], adj[0].total_cost))
fringe.add(adj[0], adj[0].total_cost)
adj[0].color = Node.in_fringe_color
current.color = Node.current_node_color
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def GRDY(self, start_state, goal_states, speed = 750):
print("Greedy Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
root = start_state
fringe = PriorityQueue()
fringe.add(root, root.heuristic) # the counter is used to differentiate between elements with the same weight
visited = []
while not fringe.empty():
for event in pygame.event.get():
if event.type == speed_event:
print(">")
fringe.display_queue()
current = fringe.pop()
visited.append(current)
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
current.color = Node.current_node_color
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
for adj in current.adjacent:
if (adj[0] not in visited) and not(fringe.inside(adj[0])):
adj[0].parent = current
print(">>")
fringe.display_queue()
fringe.add(adj[0], adj[0].heuristic)
print(">>>")
fringe.display_queue()
adj[0].color = Node.in_fringe_color
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def ASRT(self, start_state, goal_states, speed = 750):
print("A* Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
root = start_state
root.update_f_cost()
counter = 0
fringe = PriorityQueue()
fringe.add(root, root.f_cost) # the counter is used to differentiate between elements with the same weight
visited = []
while not fringe.empty():
for event in pygame.event.get():
if event.type == speed_event:
fringe.display_queue(True)
current = fringe.pop()
visited.append(current)
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
for adj in current.adjacent:
betterSol = current.total_cost + adj[1].weight + adj[0].heuristic < adj[0].f_cost
if (adj[0] not in visited) and not(fringe.inside(adj[0])):
if (adj[0].parent is None):
adj[0].parent = current
adj[0].total_cost = adj[0].parent.total_cost + adj[1].weight
adj[0].update_f_cost()
fringe.add(adj[0], adj[0].f_cost)
visited.append(adj[0])
adj[0].color = Node.in_fringe_color
elif fringe.inside(adj[0]) and betterSol:
adj[0].parent = current
adj[0].total_cost = adj[0].parent.total_cost + adj[1].weight
adj[0].update_f_cost()
fringe.add(adj[0], adj[0].f_cost)
adj[0].color = Node.in_fringe_color
current.color = Node.current_node_color
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def ITD(self, start_state, goal_states, speed = 750, cycles = 1):
print("Iterative Deeping Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
max_depth = 1
cycles += 1
while(cycles > 0):
root = start_state
fringe = []
fringe.append(root)
visited = []
current_depth = 0
self.reset_nodes()
while (len(fringe) > 0):
for event in pygame.event.get():
if event.type == speed_event:
state_fringe = list(map(lambda x: x.state, fringe))
print(state_fringe)
current = fringe.pop()
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
visited.append(current)
current.color = Node.current_node_color
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
current_depth = current.get_hight() + 1
if (current_depth < max_depth):
for adj in current.adjacent:
if adj[0] not in visited:
adj[0].color = Node.in_fringe_color
if (adj[0] not in fringe):
adj[0].parent = current
fringe.append(adj[0])
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
cycles -= 1
max_depth += 1
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def DLS(self, start_state, goal_states, speed = 750, cycles = 1):
print("Depth Limited Search RUN")
speed_event = pygame.USEREVENT + 1
pygame.time.set_timer(speed_event, speed)
cycles += 1
max_depth = cycles
print(max_depth)
root = start_state
fringe = []
fringe.append(root)
visited = []
current_depth = 0
self.reset_nodes()
while (len(fringe) > 0):
for event in pygame.event.get():
if event.type == speed_event:
state_fringe = list(map(lambda x: x.state, fringe))
print(state_fringe)
current = fringe.pop()
if (current.parent is not None):
current.getEdgeFromParent().color = (117, 116, 115)
visited.append(current)
current.color = Node.current_node_color
if current in goal_states:
current.color = Node.goal_state_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return self.path_to_goal(current)
current_depth = current.get_hight() + 1
# print(current, current_depth)
if (current_depth < max_depth):
for adj in current.adjacent:
if adj[0] not in visited:
adj[0].color = Node.in_fringe_color
if (adj[0] not in fringe):
adj[0].parent = current
fringe.append(adj[0])
self.draw_edges()
self.draw_nodes((0, 0))
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
current.color = Node.visited_color
pygame.event.clear()
pygame.time.set_timer(speed_event, 0)
return False
def reset_nodes(self):
for node in self.nodes:
node.color = Node.default_color
node.total_cost = 0
node.parent = None
node.type = ""
for edge in self.edges:
edge.color = (0,0,0)