-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
2399 lines (1961 loc) · 87.3 KB
/
main.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# python 2.7
from __future__ import print_function
import os
import sys
# Python 2.7
import time
import random
from copy import deepcopy, copy
from os import listdir
from os.path import isfile,join
import subprocess # alternate for command line calls
import shutil # for copying helpers.py to helpers.pyx
import filecmp # to check if helpers.py == helpers.pyx (if exists)
from math import sqrt
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import heapq # for priority queue implementation
# set to true to disable Cython, if you don't have a Cython
# installation that doesnt mean you need to change this, should
# be used only for debugging and testing purposes.
TURN_OFF_CYTHON = False # False
USE_UCS_MULTITHREADED = False # False
TURN_OFF_DIAGONAL_MULTIPLIER = True # True
TURN_OFF_HIGHWAY_HEURISTIC = True # True
# this can be set to a lower number to reduce the amount of grids
# that are used when benchmarking, normally set to 50
MAX_GRIDS_TO_BENCHMARK = 50 # 50
# this is the value that is used by all of the search algoritms, it
# denotes the maximum amount of time between grid updates while
# the search is proceeding. Normally set to 0.1, trying out higher
# values to see if it increases performance
GLOBAL_REFRESH_RATE = 0.1 # 0.1
# during benchmarking, the GLOBAL_REFRESH_RATE is swapped out with this value
BENCHMARK_REFRESH_RATE = 10 # 10
# weights used for Sequential and Integrated A* benchmarks
W1_BENCHMARK_WEIGHTS = [1.0,1.25,2.0,4.0]
W2_BENCHMARK_WEIGHTS = [1.0,1.25,2.0,4.0]
# weights used for A* benchmarks
ASTAR_BENCHMARK_WEIGHTS = [1.0,1.25,2.0]#,2.0,4.0]
try:
import Cython # test to see if Cython is installed
using_cython = True # need to compile helpers.pyx and import it
except:
using_cython = False # need to import lib/helpers.py to take the place of helpers.pyx
if TURN_OFF_CYTHON: using_cython = False
if using_cython:
print("Found Cython installation, copying helpers.py to helpers.pyx...")
if os.path.exists("helpers.pyx"):
if filecmp.cmp("lib/helpers.py","helpers.pyx")==False: # if they are not the same already
shutil.copyfile("lib/helpers.py","helpers.pyx")
else:
shutil.copyfile("lib/helpers.py","helpers.pyx")
print("Building C code (if error here change python2 to python in main.py)...")
try:
val = subprocess.Popen('python2 setup.py build_ext --inplace', shell=True).wait()
print("Compilation return code: "+str(val))
tried_python2=True
except:
print("python2.exe is not in environment, trying python.exe...")
val = subprocess.Popen('python setup.py build_ext --inplace', shell=True).wait()
print("Compilation return code: "+str(val))
tried_python2=False
if tried_python2==True and val!=0:
print("python2 is not in environment, trying Python.exe...")
val = subprocess.Popen('python setup.py build_ext --inplace', shell=True).wait()
print("Compilation return code: "+str(val))
if val!=0:
using_cython=False
print("Could not compile Cython using python.exe or python2.exe")
choice = raw_input("Would you like to run without Cython? [y/n]: ")
if choice in ["N","n"]:
print("Exiting.")
sys.exit()
else:
sys.path.insert(0,"lib/")
from helpers import PriorityQueue,get_neighbors,cell_in_list,uniform_cost_search,message
from helpers import get_transition_cost,rectify_path,eight_neighbor_grid, get_cell_index, get_path_cost
from helpers import non_gui_eight_neighbor_grid, cell
else:
print("Could not find Cython installation, using Python version of helpers.py")
lib_folder = "lib/"
sys.path.insert(0, lib_folder)
from helpers import PriorityQueue,get_neighbors,cell_in_list,uniform_cost_search,message
from helpers import get_transition_cost,rectify_path,eight_neighbor_grid, get_cell_index, get_path_cost
from helpers import non_gui_eight_neighbor_grid, cell
pyqt_app = ""
class attrib_value_window(QWidget):
# small window that opens if the user wants to change an attribute value
def __init__(self):
# constructor
super(attrib_value_window,self).__init__()
self.init_vars()
self.init_ui()
def init_vars(self):
# initialize to default settings
self.attribs = ["Solution Swarm Density","Solution Path Width","Solution Trace Width","Highway Width"]
# default widths
self.values = [1.00,5.00,1.00,2.00]
if os.name == "nt": # better for windows
self.values[0] = 2.0
self.lines = ["Highway","Solution Path","Solution Trace","Solution Swarm"]
self.current_line_types = ["SolidLine","SolidLine","DotLine","DashLine"]
self.all_line_types = ["SolidLine","DashLine","DotLine","DashDotLine","DashDotDotLine"]
self.is_valid = True # if false, user closed out of window
def init_ui(self):
# set up ui elements
self.layout = QVBoxLayout(self)
first_row = QHBoxLayout()
second_row = QHBoxLayout()
save_row = QHBoxLayout()
row_divider = QFrame(self) # dividing line between save button an top row
row_divider.setFrameShape(QFrame.HLine)
divider = QHBoxLayout()
divider.addSpacing(40)
divider.addWidget(row_divider)
divider.addSpacing(40)
self.layout.addLayout(first_row)
self.layout.addLayout(second_row)
self.layout.addSpacing(10)
self.layout.addLayout(divider) # add dividing line
self.layout.addSpacing(10)
self.layout.addLayout(save_row)
self.setWindowTitle("Set Value Preferences")
# selection box
self.selection_box = QComboBox(self)
self.selection_box.addItems(self.attribs)
self.selection_box.currentIndexChanged.connect(self.attrib_changed)
first_row.addStretch()
selection_box_layout = QVBoxLayout()
first_row.addLayout(selection_box_layout)
#selection_box_layout.addSpacing(5)
selection_box_layout.addWidget(self.selection_box)
# color elements
self.value_input = QDoubleSpinBox(self)
self.value_input.setDecimals(1)
self.value_input.setSingleStep(0.1)
self.value_input.setMaximum(10.0)
self.value_input.setMinimum(0.1)
self.value_input.valueChanged.connect(self.value_changed)
first_row.addSpacing(10)
first_row.addWidget(self.value_input)
first_row.addSpacing(37)
first_row.addStretch(1)
# line selection box
self.line_selection_box = QComboBox(self)
self.line_selection_box.addItems(self.lines)
self.line_selection_box.currentIndexChanged.connect(self.line_changed)
second_row.addStretch()
line_selection_layout = QVBoxLayout()
second_row.addLayout(line_selection_layout)
#line_selection_layout.addSpacing(5)
line_selection_layout.addWidget(self.line_selection_box)
self.line_type_input = QComboBox(self)
self.line_type_input.addItems(self.all_line_types)
self.line_type_input.currentIndexChanged.connect(self.line_type_changed)
second_row.addSpacing(48)
second_row.addWidget(self.line_type_input)
second_row.addSpacing(37)
second_row.addStretch(1)
# save prefs and return button
self.return_button = QPushButton("Save",self)
self.return_button.clicked.connect(self.save)
save_row.addStretch()
save_row.addWidget(self.return_button)
save_row.addStretch()
self.value_input.setValue(self.values[0])
self.selection_box.setCurrentIndex(0)
def line_changed(self):
# called when the user changes the current line in the second row
self.line_type_input.setCurrentIndex(self.line_selection_box.currentIndex())
def line_type_changed(self):
# called when the user changes the current line type
self.current_line_types[self.line_selection_box.currentIndex()] = str(self.line_type_input.currentText())
def save(self):
# fetches the current colors and sends a signal back to the main_window
self.emit(SIGNAL("return_value_prefs()"))
self.hide()
def attrib_changed(self):
# function called by pyqt when user changes the selection box attribute
self.value_input.setValue(self.values[self.selection_box.currentIndex()])
def value_changed(self):
# called by pyqt when one of the rgb boxes is changed
self.values[self.selection_box.currentIndex()] = self.value_input.value()
def open_window(self):
# called from the main_window
self.is_valid = True
self.show()
def hide_window(self):
# called from the main_window
self.hide()
def closeEvent(self,e):
self.is_valid = False
self.emit(SIGNAL("return_value_prefs()"))
class attrib_color_window(QWidget):
# small window that opens if the user wants to change an attribute color
def __init__(self):
# constructor
super(attrib_color_window,self).__init__()
self.init_vars()
self.init_ui()
def init_vars(self):
# initialize to default settings
self.attribs = ["free","highway","fully blocked","partially blocked","start","end","solution_swarm","solution","start_gradient","end_gradient","path_trace"]
# default colors
self.colors = [[255,255,255],[0,0,255],[0,0,0],[128,128,128],[0,255,0],[255,0,0],[0,255,255],[0,255,0],[255,0,0],[0,255,50],[128,128,128]]
# default element being shown
self.attrib_index = 0
# current attribute value
self.attrib_value = self.colors[self.attrib_index]
self.backend = False # if we are changing something backend, dont record it as user changed value
self.is_valid = True # if false, user closed out of window instead of accepting changes
def init_ui(self):
# set up ui elements
self.layout = QVBoxLayout(self)
first_row = QHBoxLayout()
second_row = QHBoxLayout()
row_divider = QFrame(self) # dividing line between save button an top row
row_divider.setFrameShape(QFrame.HLine)
divider = QHBoxLayout()
divider.addSpacing(40)
divider.addWidget(row_divider)
divider.addSpacing(40)
self.layout.addLayout(first_row) # add color selection line
self.layout.addSpacing(10)
self.layout.addLayout(divider) # add dividing line
self.layout.addSpacing(10)
self.layout.addLayout(second_row) # add save button row
self.setWindowTitle("Set Color Preferences")
# selection box
self.selection_box = QComboBox(self)
self.selection_box.addItems(self.attribs)
self.selection_box.currentIndexChanged.connect(self.attrib_changed)
first_row.addStretch()
selection_box_layout = QVBoxLayout()
first_row.addLayout(selection_box_layout)
selection_box_layout.addSpacing(5)
selection_box_layout.addWidget(self.selection_box)
# color elements
self.red = QLineEdit("",self)
self.red.textChanged.connect(self.value_changed)
validator = QIntValidator(0,255)
self.red.setValidator(validator)
self.red.setFixedWidth(30)
self.red_label = QLabel(" R",self)
red_layout = QVBoxLayout()
red_layout.addWidget(self.red_label)
red_layout.addWidget(self.red)
self.green = QLineEdit("",self)
self.green.textChanged.connect(self.value_changed)
validator = QIntValidator(0,255)
self.green.setValidator(validator)
self.green.setFixedWidth(30)
self.green_label = QLabel(" G",self)
green_layout = QVBoxLayout()
green_layout.addWidget(self.green_label)
green_layout.addWidget(self.green)
self.blue = QLineEdit("",self)
self.blue.textChanged.connect(self.value_changed)
validator = QIntValidator(0,255)
self.blue.setValidator(validator)
self.blue.setFixedWidth(30)
self.blue_label = QLabel(" B",self)
blue_layout = QVBoxLayout()
blue_layout.addWidget(self.blue_label)
blue_layout.addWidget(self.blue)
first_row.addSpacing(10)
first_row.addLayout(red_layout)
first_row.addLayout(green_layout)
first_row.addLayout(blue_layout)
first_row.addSpacing(37)
first_row.addStretch(1)
# save prefs and return button
self.return_button = QPushButton("Save",self)
self.return_button.clicked.connect(self.save)
second_row.addStretch()
second_row.addWidget(self.return_button)
second_row.addStretch()
self.set_color_boxes(self.colors[0])
if os.name == "nt": # these dimensions fit Windows better
self.sample_square_top_left = (240,25) # (x,y) coordinates of top left
self.sample_square_bottom_right = (267,52) # (x,y) coordinates of bottom right
self.sample_square_size = 27 # width and height of sample square
else: # and these are better for osx
self.sample_square_top_left = (315,35)
self.sample_square_bottom_right = (342,62)
self.sample_square_size = 27
def mousePressEvent(self,e):
# catch when the user clicks and see if its in the sample area, if so,
# open up the default PyQt color picker
x = e.x() # get x coordinate of click
y = e.y() # get y coordinate of click
if x <=self.sample_square_bottom_right[0] and x>= self.sample_square_top_left[0]:
if y>= self.sample_square_top_left[1] and y<= self.sample_square_bottom_right[1]:
# click was within the sample area
color = QColorDialog.getColor() # open QColor dialog
if color.isValid(): # if a value was returned
color = color.getRgb() # conver to rgb
color = list(color) # convert 3 length tuple to list
self.set_color_boxes(color) # set the color
self.value_changed() # record the change
def draw_sample_event(self,qp,color):
# function called when the sample color window needs to be redrawn, colors
# in the square with the current color
qp.setPen(QColor(0,0,0))
qp.setBrush(QColor(color[0],color[1],color[2]))
qp.drawRect( # draw the square
self.sample_square_top_left[0],
self.sample_square_top_left[1],
self.sample_square_size,
self.sample_square_size)
def paintEvent(self,e):
# calls the draw_sample_event function to re-color the sample square
cur_color = self.get_current_color()
qp = QPainter()
qp.begin(self)
self.draw_sample_event(qp,cur_color)
qp.end()
def save(self):
# fetches the current colors and sends a signal back to the main_window
self.emit(SIGNAL("return_color_prefs()"))
self.hide()
def attrib_changed(self):
# function called by pyqt when user changes the selection box attribute
self.set_color_boxes(self.colors[self.selection_box.currentIndex()])
def set_color_boxes(self,color):
# sets the rgb boxes to the input color
self.backend = True
try:
self.red.setText(str(color[0]))
self.green.setText(str(color[1]))
self.blue.setText(str(color[2]))
self.attrib_value = color
except:
pass
self.backend = False
def get_current_color(self):
# parse the current color from the ui boxes
current = []
try:
current.append(int(self.red.text()))
current.append(int(self.green.text()))
current.append(int(self.blue.text()))
return current
except:
return [-1,-1,-1]
def value_changed(self):
# called by pyqt when one of the rgb boxes is changed
if self.backend==False:
color = self.get_current_color()
if color!=[-1,-1,-1]:
self.colors[self.selection_box.currentIndex()] = color
self.repaint()
def open_window(self):
# called from the main_window
self.is_valid = True
self.show()
def hide_window(self):
# called from the main_window
self.hide()
def closeEvent(self,e):
self.is_valid = False
self.emit(SIGNAL("return_color_prefs()"))
class benchmark_t(object):
def __init__(self,destination_filename,grid_filenames):
self.destination_filename = destination_filename # filename to save the data at
self.grid_filenames = grid_filenames # list of names like "grids/1-0.grid"
self.times = [] # list of time data
self.costs = [] # list of cost data
self.frontiers = [] # list of frontier lengths
self.explored = [] # list of explored lengths
self.header_info = "" # information to write at top of file
def save(self):
# saves the current data to the self.destination_filename file
f = open(self.destination_filename,"w")
f.write(self.header_info+"\n\n")
total_time = 0
total_explored = 0
total_cost = 0
total_frontier = 0
source_string = "sources: ["
for g in self.grid_filenames:
source_string += str(g)
if self.grid_filenames.index(g)!=(len(self.grid_filenames)-1):
# if not the last element
source_string += ","
source_string += "]\n"
f.write(source_string)
time_string = "times: ["
for t in self.times:
total_time += t
time_string += str(t)
if self.times.index(t)!=(len(self.times)-1):
# if not the last time
time_string += ","
time_string += "]\n"
f.write(time_string)
cost_string = "costs: ["
for item in self.costs:
total_cost += item
cost_string += str(item)
if self.costs.index(item)!=(len(self.costs)-1):
cost_string += ","
cost_string += "]\n"
f.write(cost_string)
frontier_string = "frontiers: ["
for item in self.frontiers:
total_frontier += item
frontier_string += str(item)
if self.frontiers.index(item)!=(len(self.frontiers)-1):
frontier_string += ","
frontier_string += "]\n"
f.write(frontier_string)
explored_string = "explored: ["
for item in self.explored:
total_explored += item
explored_string += str(item)
if self.explored.index(item)!=(len(self.explored)-1):
explored_string += ","
explored_string += "]\n"
f.write(explored_string)
f.write("\n")
f.write("Average Time: "+str(total_time/len(self.times))+" seconds\n")
f.write("Average Cost: "+str(total_cost/len(self.costs))+"\n")
f.write("Average Frontier: "+str(total_frontier/len(self.frontiers))+" cells\n")
f.write("Average Explored: "+str(total_explored/len(self.explored))+" cells\n")
f.write("Total Time: "+str(total_time)+" seconds\n")
f.close()
class main_window(QWidget):
# Initializations...
def __init__(self,parent=None,code=None):
# constructor
super(main_window,self).__init__()
self.parent = parent
self.init_vars()
self.init_ui()
if code=="profile":
# if we are running a cProfile
self.grid.load("grids/0-9.grid")
self.snap_to_small()
global GLOBAL_REFRESH_RATE
GLOBAL_REFRESH_RATE = 10
self.integrated_astar()
sys.exit()
def init_vars(self):
# initialize all class variables here
self.grids = [] # list of all grid elements
self.click = None # save click info
self.host_os = os.name # "nt" for windows distrubitions
print("Running Host OS: "+str(self.host_os))
self.show_grid_lines = False # true by default
self.show_solution_swarm = True # true by default
self.use_gradient = True # False by default
self.show_trace = True # true by default
self.updating_already = False
self.stop_executing = False # set to true if user cancels search algo execution
self.stop_benchmark = False # set to true if user cancels benchmark execution
self.mouse_tracking = True
self.trace_highlighting = False
self.is_benchmark = False # true if benchmarking right now
self.child_windows = [] # to hold any extra windows opened by user
self.color_preferences_window = attrib_color_window()
self.value_preferences_window = attrib_value_window()
if USE_UCS_MULTITHREADED: self.ucs_agent = uniform_cost_search() # separate thread for ucs execution
if os.name=="nt": # good sizes for windows
self.small_size = [822,673]
self.medium_size = [984,793]
self.large_size = [1462,1156]
self.xl_size = [1623,1278]
else:
self.small_size = [840,552]
self.medium_size = [1001,673]
self.large_size = [1161,791]
self.xl_size = [1623,1278]
def init_ui(self):
# initialize ui elements here
self.layout = QVBoxLayout(self) # layout for window
self.setWindowTitle("AI Project 1")
# if windows, need to make room for menubar, on OSX the menubar
# is kept in the top OS menu bar instead
if os.name == "nt":
self.layout.addSpacing(25)
# creating UI elements to show current cell state
top_row_layout = QHBoxLayout() # layout to hold top row
self.layout.addLayout(top_row_layout) # add layout to overall layout
title_label = QLabel("Cell Information",self)
top_row_layout.addWidget(title_label)
# make spacing between "Cell Information" label and details
if self.host_os == "nt":
top_row_layout.addSpacing(20) # 40
else:
top_row_layout.addSpacing(20)
if self.host_os == "nt":
top_row_space = 10 # 20
else:
top_row_space = 10
coordinates_label = QLabel("Coordinate:",self)
top_row_layout.addWidget(coordinates_label)
self.coordinates_value = QLineEdit("(0,0)",self)
self.coordinates_value.setEnabled(False)
top_row_layout.addWidget(self.coordinates_value)
top_row_layout.addSpacing(top_row_space)
state_label = QLabel("State:",self)
top_row_layout.addWidget(state_label)
self.state_value = QLineEdit("FREE",self)
self.state_value.setEnabled(False)
top_row_layout.addWidget(self.state_value)
top_row_layout.addSpacing(top_row_space)
f_label = QLabel("f:",self)
top_row_layout.addWidget(f_label)
self.f_value = QLineEdit("0",self)
self.f_value.setEnabled(False)
top_row_layout.addWidget(self.f_value)
top_row_layout.addSpacing(top_row_space)
g_label = QLabel("g:",self)
top_row_layout.addWidget(g_label)
self.g_value = QLineEdit("0",self)
self.g_value.setEnabled(False)
top_row_layout.addWidget(self.g_value)
top_row_layout.addSpacing(top_row_space)
h_label = QLabel("h:",self)
top_row_layout.addWidget(h_label)
self.h_value = QLineEdit("0",self)
self.h_value.setEnabled(False)
# setting the element sizes for the top row...
if self.host_os=="nt":
label_width = 75 # 100
else:
label_width = 75
self.coordinates_value.setFixedWidth(label_width)
self.state_value.setFixedWidth(label_width)
self.f_value.setFixedWidth(label_width)
self.g_value.setFixedWidth(label_width)
self.h_value.setFixedWidth(label_width)
top_row_layout.addWidget(self.h_value)
top_row_layout.addSpacing(20)
top_row_layout.addStretch()
self.grid = eight_neighbor_grid(160,120,pyqt_app)
self.grid.setContextMenuPolicy(Qt.CustomContextMenu)
self.grid.customContextMenuRequested.connect(self.on_context_menu_request)
self.layout.addWidget(self.grid,2)
# context menu stuff, opens on right click
self.context_menu = QMenu(self)
self.context_menu.addAction("Set as Starting Point",self.set_start)
self.context_menu.addAction("Set as Ending Point",self.set_end)
self.context_menu.addSeparator()
self.context_menu.addAction("Set Cell as Free",self.set_free)
self.context_menu.addAction("Set Cell as Partially Blocked",self.set_partial)
self.context_menu.addAction("Set Cell as Fully Blocked",self.set_full)
# Creating menubar and menu items
self.menu_bar = QMenuBar(self)
self.menu_bar.setMinimumWidth(310)
self.file_menu = self.menu_bar.addMenu("File")
self.algo_menu = self.menu_bar.addMenu("Algorithm")
self.tools_menu = self.menu_bar.addMenu("Tools")
self.view_menu = self.menu_bar.addMenu("View")
self.benchmark_menu = self.menu_bar.addMenu("Benchmark")
# View menu actions
self.view_menu.addSeparator()
menu_label = self.view_menu.addAction("Snap To...")
menu_label.setEnabled(False)
self.view_menu.addSeparator()
self.view_menu.addAction("Small ("+str(self.small_size[0])+","+str(self.small_size[1])+")",self.snap_to_small)
self.view_menu.addAction("Medium ("+str(self.medium_size[0])+","+str(self.medium_size[1])+")",self.snap_to_medium)
self.view_menu.addAction("Large ("+str(self.large_size[0])+","+str(self.large_size[1])+")",self.snap_to_large)
self.view_menu.addAction("X-Large ("+str(self.xl_size[0])+","+str(self.xl_size[1])+")",self.snap_to_xl)
self.view_menu.addSeparator()
# Benchmark menu actions
astar_benchmark_action = self.benchmark_menu.addAction("Benchmark A* Search",self.a_star_benchmark)
astar_benchmark_action.setEnabled(False)
weighted_benchmark_action = self.benchmark_menu.addAction("Benchmark Weighted A* Search",self.weighted_a_star_benchmark_wrapper)
weighted_benchmark_action.setEnabled(False)
self.benchmark_menu.addAction("Benchmark Uniform-Cost Search",self.uniform_cost_benchmark)
self.benchmark_menu.addSeparator()
astar_weighted_benchmark_action = self.benchmark_menu.addAction("Benchmark A*, All Heuristics",self.astar_heuristic_wrapper)
astar_weighted_benchmark_action.setEnabled(False)
self.benchmark_menu.addAction("Benchmark A*, All Heuristics, Multiple Weights",self.astar_heuristic_weight_wrapper)
self.benchmark_menu.addSeparator()
self.benchmark_menu.addAction("Benchmark Sequential A*, Multiple Weights",self.sequential_astar_benchmark_wrapper)
self.benchmark_menu.addAction("Benchmark Integrated A*, Multiple Weights",self.integrated_astar_benchmark_wrapper)
self.benchmark_menu.addSeparator()
self.benchmark_menu.addAction("Benchmark All",self.all_benchmark)
self.benchmark_menu.addSeparator()
self.benchmark_menu.addAction("Benchmark Custom",self.custom_benchmark_wrapper)
self.benchmark_menu.addSeparator()
self.benchmark_menu.addAction("Stop Benchmark",self.cancel_benchmark,QKeySequence("Ctrl+B"))
# File menu actions
self.file_menu.addAction("Load...",self.load,QKeySequence("Ctrl+L"))
self.file_menu.addAction("Save As...",self.save_as,QKeySequence("Ctrl+S"))
self.file_menu.addSeparator()
self.file_menu.addAction("Save Screenshot...",self.save_screenshot,QKeySequence("Ctrl+Shift+S"))
self.file_menu.addSeparator()
self.file_menu.addAction("Clear Grid",self.clear,QKeySequence("Ctrl+C"))
self.file_menu.addAction("Clear Search Path", self.clear_path,"Ctrl+P")
self.file_menu.addAction("Generate New Grid",self.create,QKeySequence("Ctrl+N"))
self.file_menu.addSeparator()
self.file_menu.addAction("Open New Window...",self.open_new_window,QKeySequence("Ctrl+Shift+N"))
self.file_menu.addSeparator()
self.file_menu.addAction("Quit", self.quit, QKeySequence("Ctrl+Q"))
# Tools menu actions
self.toggle_grid_lines_action = self.tools_menu.addAction("Turn On Grid Lines",self.toggle_grid_lines,QKeySequence("Ctrl+G"))
self.toggle_solution_swarm_action = self.tools_menu.addAction("Turn Off Solution Swarm",self.toggle_solution_swarm,QKeySequence("Ctrl+T"))
self.toggle_gradient_action = self.tools_menu.addAction("Turn Off Swarm Gradient",self.toggle_gradient)
self.tools_menu.addSeparator()
self.toggle_trace_action = self.tools_menu.addAction("Turn On Path Trace",self.toggle_trace)
self.toggle_trace_highlighting_action = self.tools_menu.addAction("Turn On Trace Highlighting",self.toggle_trace_highlighting)
self.tools_menu.addSeparator()
self.toggle_mouse_tracking_action = self.tools_menu.addAction("Turn Off Mouse Tracking",self.toggle_mouse_tracking)
self.tools_menu.addSeparator()
self.tools_menu.addAction("Color Preferences...",self.change_attrib_color,QKeySequence("Ctrl+M"))
self.tools_menu.addAction("Value Preferences...",self.change_attrib_value,QKeySequence("Ctrl+V"))
self.tools_menu.addSeparator()
self.tools_menu.addAction("New Start/End Cells...",self.regenerate_start_end)
# Algorithm menu actions
self.algo_menu.addAction("Run A*",self.a_star,QKeySequence("Ctrl+1"))
self.algo_menu.addAction("Run Weighted A*",self.weighted_astar_wrapper_default_heuristic,QKeySequence("Ctrl+2"))
self.algo_menu.addAction("Run Uniform-Cost Search",self.uniform_cost,QKeySequence("Ctrl+3"))
self.algo_menu.addSeparator()
self.algo_menu.addAction("Run A*, Custom Heuristic",self.astar_wrapper)
self.algo_menu.addAction("Run Weighted A*, Custom Heuristic",self.weighted_astar_wrapper)
self.algo_menu.addSeparator()
self.algo_menu.addAction("Run Sequential Heuristic A*",self.sequential_astar,QKeySequence("Ctrl+8"))
self.algo_menu.addAction("Run Integrated Heuristic A*",self.integrated_astar,QKeySequence("Ctrl+9"))
self.algo_menu.addSeparator()
self.algo_menu.addAction("Run Sequential Heuristic A*, Custom Parameters",self.sequential_astar_wrapper)
self.algo_menu.addAction("Run Integrated Heuristic A*, Custom Parameters",self.integrated_astar_wrapper)
self.algo_menu.addSeparator()
self.algo_menu.addAction("Stop Algorithm",self.stop_algorithm,QKeySequence("Ctrl+0"))
if os.name == "nt":
#self.resize(1623,1249) # large monitor size
self.resize(1623,1278) # large monitor size
else:
self.resize(1323,793) # fits my macbook well
QtCore.QObject.connect(self.color_preferences_window, QtCore.SIGNAL("return_color_prefs()"), self.finished_changing_colors)
QtCore.QObject.connect(self.value_preferences_window, QtCore.SIGNAL("return_value_prefs()"), self.finished_changing_values)
QtCore.QObject.connect(self.grid, QtCore.SIGNAL("return_current_cell_attributes(PyQt_PyObject)"), self.update_current_cell_info)
self.show()
# Algorithms...
def sequential_astar_wrapper(self):
self.w1_w2_input_dialog("sequential_astar")
def integrated_astar_wrapper(self):
self.w1_w2_input_dialog("integrated_astar")
def w1_w2_input_dialog(self,target):
inputw1, ok = QInputDialog.getText(self, "Input Dialog", "Enter W1 value (>=1.0): ")
if ok:
try:
inputw1 = float(inputw1)
if inputw1>=1.0:
inputw2, ok = QInputDialog.getText(self, "Input Dialog", "Enter W2 value (>=1.0): ")
if ok:
try:
inputw2 = float(inputw2)
if inputw2>=1.0:
if target=="integrated_astar":
self.integrated_astar(inputw1,inputw2)
elif target=="sequential_astar":
self.sequential_astar(inputw1,inputw2)
else:
print("ERROR: W1, W2 input dialog function.")
#self.integrated_astar(w1,w2)
else:
print("ERROR: W2 input must be whole number greater than or equal to 1.0")
except:
print("ERROR: W2 input must be whole number greater than or equal to 1.0")
else:
print("ERROR: W1 input must be whole number greater than or equal to 1.0")
except:
print("ERROR: W1 input must be whole number greater than or equal to 1.0")
def sequential_astar(self,w1=1.25,w2=1.25):
num_heuristics = 5
if self.is_benchmark==False: print("Performing Sequential A* Search with "+str(num_heuristics)+" heuristics using w1="+str(w1)+", w2="+str(w2))
self.fetch_current_grid_state()
self.set_ui_interaction(enabled=False)
inf = sys.maxint
#get start index
#start_index = get_cell_index(self.start_cell, self.cells)
start_index = self.start_cell.index
#get goal index
#goal_index = get_cell_index(self.end_cell_t, self.cells)
goal_index = self.end_cell_t.index
#initialize 5 explored sets for each heuristics
self.explored_set_list = [[] for i in range(num_heuristics)]
#initialize 5 empty cost sets for each heuristics
self.cost_set_list = [{} for i in range(num_heuristics)]
#initialize closed lists
self.closed_set_lists = [ [] for i in range(num_heuristics)]
#initialize visited arrays for each heuristics
self.visited_lists = [[False] * len(self.cells) for i in range(num_heuristics)]
#Mark the start nodes as visited (NOTE: might need to fuse loops later)
for i in range(num_heuristics):
self.visited_lists[i][start_index] = True
#populate the sets with values for start and end node_neigbors
for i in range(num_heuristics):
self.cost_set_list[i][start_index] = 0
self.cost_set_list[i][goal_index] = inf
#initialize 5 frontiers for each of the 5 heuristics
self.frontier_list = []
for i in range(num_heuristics):
temp = PriorityQueue(max_len=len(self.cells))
temp.push(item=self.start_cell, cost=self.sequential_astar_key(i, w1, self.start_cell, start_index), parent=None)
self.frontier_list.append(temp)
done = False #boolean used to break out of while loop
result_code = 0
last_cell = None # to hold the last node expanded (for updating ui)
start_time = time.time()
step_time = time.time()
refresh_rate = GLOBAL_REFRESH_RATE if self.is_benchmark==False else BENCHMARK_REFRESH_RATE
self.explored = [] # to hold all cells visited
num_iterations = 0 # number of times while loop is run
self.stop_executing = False
last_heuristic = 0
self.render_time = 0 # amount of time used to render during this execution
while self.frontier_list[0].Minkey() < inf and done==False:
# if user cancelled execution
if (self.stop_executing):
self.set_ui_interaction(enabled=True)
return
# update the ui window
if ((time.time()-step_time) > refresh_rate) and last_cell!=None:
render_start = time.time()
self.grid.solution_path = self.explored_set_list[last_heuristic]
self.grid.shortest_path = rectify_path(last_cell)
self.grid.update()
pyqt_app.processEvents()
step_time = time.time()
self.render_time += (time.time()-render_start)
print(" ",end="\r")
print("explored: "+str(len(self.explored_set_list[last_heuristic]))+", num_iterations: "+str(num_iterations)+", time: "+str(time.time()-start_time)[:5], end="\r")
num_iterations += 1
for i in range(1, num_heuristics):
if self.frontier_list[i].Minkey() <= ( w2 * self.frontier_list[0].Minkey() ):
if self.cost_set_list[i][goal_index] <= self.frontier_list[i].Minkey():
if self.cost_set_list[i][goal_index] < inf:
done = True #exit out of the loop
result_code = i
break
else:
s = self.frontier_list[i].top()
last_cell = s
last_heuristic = i
#if cell_in_list(s,self.explored)==False: self.explored.append(s)
self.sequential_astar_expand(i, w1, s)
self.explored_set_list[i].append(s)
self.closed_set_lists[i].append(s)
else:
if self.cost_set_list[0][goal_index] <= self.frontier_list[0].Minkey():
if self.cost_set_list[0][goal_index] < sys.maxint:
done = True
result_code = 0
break
else:
s = self.frontier_list[0].top()
last_cell = s
last_heuristic = 0
#if cell_in_list(s,self.explored)==False: self.explored.append(s)
self.sequential_astar_expand(0, w1, s)
self.explored_set_list[0].append(s)
self.closed_set_lists[0].append(s)
render_start = time.time()
# convert the dictionary cost_set_list into a list called self.last_cost_list
self.last_cost_list = ["None"] * len(self.cells)
for index,cost in self.cost_set_list[result_code].items():
self.last_cost_list[int(index)] = float(cost)
# combine all queues to create the overall solution swarm
total_solution_swarm = []
longest_queue = -1
for queue in self.explored_set_list:
if len(queue)>=longest_queue:
longest_queue = len(queue)
for i in range(longest_queue):
for queue in self.explored_set_list:
if len(queue)>i:
if queue[i] not in total_solution_swarm:
total_solution_swarm.append(queue[i])
self.grid.solution_path = total_solution_swarm
final_solution_cost = self.cost_set_list[result_code][goal_index]
# locate the goal cell at the end of the linked list for the best path
self.path_end = None
for item in self.frontier_list[result_code]._queue:
cell = item[-1]
if cell.index==self.end_cell_t.index:
self.path_end = cell
break
# if we could not locate the goal cell
if self.path_end==None:
print("\nERROR: Sequential A* Search self.path_end could not be located.")
self.grid.shortest_path = []
else:
self.grid.shortest_path = rectify_path(self.path_end)
# update the grid
self.grid.update()
pyqt_app.processEvents()
self.set_ui_interaction(enabled=True)
self.latest_search_cost = final_solution_cost
frontier_length = 0
for i in range(len(self.frontier_list)):
frontier_length+=self.frontier_list[i].length()
self.latest_frontier_length = frontier_length
total_explored=0
for i in range(len(self.closed_set_lists)):
total_explored+=len(self.closed_set_lists[i])
self.latest_num_explored = total_explored
print("\nFinished Sequential A* search in "+str(time.time()-start_time)[:6]+" seconds, final cost: "+str(final_solution_cost)+", checked "+str(self.latest_num_explored)+" cells")
self.render_time += (time.time()-render_start)
def sequential_astar_key(self, h_index, w1, cell_obj, cell_index):
if h_index == 0:
return self.cost_set_list[h_index][cell_index] + (w1 * float(self.grid.heuristic_manager(cell_obj, self.end_cell_t, h_index)) / 4.0)
else:
return self.cost_set_list[h_index][cell_index] + (w1 * float(self.grid.heuristic_manager(cell_obj, self.end_cell_t, h_index)))
def sequential_astar_expand(self, h_index, w1, cell_obj):
#Remove s from frontier
self.frontier_list[h_index].remove(cell_obj)
#get neighbors
neighbors = cell_obj.neighbors
#c_index = get_cell_index(cell_obj, self.cells)
c_index = cell_obj.index
self.visited_lists[h_index][c_index] = True
for neighbor in neighbors:
neighbor = copy(neighbor)
#neighbor_index = get_cell_index(neighbor, self.cells)
neighbor_index = neighbor.index
if neighbor_index==c_index:
continue
if self.visited_lists[h_index][neighbor_index] == False:
self.cost_set_list[h_index][neighbor_index] = sys.maxint
neighbor.parent = None