def test_bfs(): with open('/home/douglascorrea/FIA/BFS.csv', 'wb') as file: for i in range(len(shuffle_number)): times = [] memory = [] average_time = 0 average_memory = 0 print("Moves: " + str(shuffle_number[i])) file.write(str(shuffle_number[i]) + '\n') for j in range(test_number): print(j) print(boards[i][j]) bfs_alg = bfs.BFS(boards[i][j], board_size) start = time.time() bfs_alg.BFS_algorithm() end = time.time() times.append(end - start) memory.append(bfs_alg.get_memory_usage()) file.write(' ' + ',') for t in times: file.write(str(t) + ',') average_time += t file.write(str(average_time / 10) + '\n' + ' ,') for m in memory: file.write(str(m) + ',') average_memory += m file.write(str(average_memory / 10) + '\n')
def test_BFS_len_2(self): G = nx.Graph() G.add_nodes_from([0, 1]) G.add_edge(0, 1) expected = {0: {0}, 1: {1}} result = bfs.BFS(G, 0) self.assertEqual(result, expected)
def main(): # validate the params if len(sys.argv) != 2: print("Usage: python3 main.py <NETWORK_FILE>") sys.exit(-1) # read in the network from file net = network.readFromFile(sys.argv[1]) # create the problem model model = problem.Problem(net) # search using BFS bfsSearcher = bfs.BFS(model) bfsSearcher.search() # search using dijkstra dijkstraSearcher = dijkstra.Dijkstra(model) dijkstraSearcher.search() # search using A* astarSearcher = astar.AStar(model) astarSearcher.search() # search using beam search beamSearcher = beams.Beams(model) beamSearcher.search() # search using Iterative Deepening idSearcher = iterativedeepening.IterDeep(model) idSearcher.search()
def test_BFS_len_6_depth_4(self): G = nx.Graph() G.add_nodes_from(range(6)) H = nx.path_graph(6) G.add_edges_from(H.edges) expected = {0: {0}, 1: {1}, 2: {2}, 3: {3}, 4: {4}} result = bfs.BFS(G, 0, depth=4) self.assertEqual(result, expected)
def calculate_path(self): if len(self.visited_points) != len(self.checkpoints): next_point = self.checkpoints[len(self.visited_points)] next_point = (next_point.x, next_point.y) print(self.pos[0]) print("punkt") print(self.pos, next_point, self.start_position) path_to_point = bfs.BFS(self.pos, next_point, self.map) path_to_battery = bfs.BFS(next_point, self.start_position, self.map) if len(path_to_battery) + len(path_to_point) < self.battery: print("tutaj") self.current_path = path_to_point else: print("tam") self.current_path = bfs.BFS(self.pos, self.start_position, map)
def longest_path(): bfs = bfe.BFS(floor.get_rooms()) bfs.bfs(starting_room) distances = { len(bfs.traverse(room)): room for room in list(rooms.values()) } while type(distances[max(distances)]) == Labirynth.Shop: del distances[max(distances)] return distances[max(distances)]
def executa_BFS(board, tam): with open('BFS.csv', 'a') as file: counter = 1 print(board) file.write(str(tam) + '\n') bfs_alg = bfs.BFS(board, 3) start = time.time() bfs_alg.BFS_algorithm() end = time.time() times = end - start file.write(str(times) + ',') file.write(str(bfs_alg.get_memory_usage()) + ',') file.write('\n')
def bfs_init(self): current = copy.deepcopy(self.m) for y in range(37): for x in range(37): if self.m[x][y] == 0: bfs = Search.BFS() r = bfs.bfs_init(copy.deepcopy(self.m), 37, (x, y), (30, 30)) # print r[1] # print r[1][-2:-1] st = r[1][-1] if st == (30, 30): current[x][y] = -1 continue nt = r[1][-2] d = -1 if st[0] == nt[0]: # row if st[1] < nt[1]: # col # right d = 1 else: d = 3 else: if st[0] < nt[0]: # col # down d = 2 else: d = 0 current[x][y] = d for x in range(37): for y in range(37): if current[x][y] == -1: print '\033[1;35m\033[0m' + "B", else: print '\033[0m' + str(current[x][y]), print '\n', self.d = current
def traverse_graph(self): # Creating new graph traverser if self.rbSelectedValue.get() == "DFS": if self.dfs_query == "yes": self.graph_traverser = dfs_iterative.DFSIterative(self.grp) else: self.graph_traverser = dfs_recursive.DFSRecursive(self.grp) elif self.rbSelectedValue.get() == "BFS": self.graph_traverser = bfs.BFS(self.grp) elif self.rbSelectedValue.get() == "Dijkstra": self.graph_traverser = dijkstra.Dijkstra(self.grp, None) elif self.rbSelectedValue.get() == "Astar": self.graph_traverser = astar.AStar(self.grp, self.rb_heuristic_value.get()) # Traversing the graph and getting traverse node path self.traverse_time_start = time.time() self.path, self.steps = self.graph_traverser.traverse() if self.path == []: tkMessageBox.showerror("Error", "Graph traversing failed") self.traverse_time_end = time.time()
def test_BFS_random_graph(self): n = 16 m = 25 G = nx.gnm_random_graph(n, m) result = bfs.BFS(G, 0, depth=4)
def confirmAllPuzzlesRunOnAllSearches(self): # MODEL PANCAKES pancake_puzzle = Pancakes.BurntPancakes() pancake_puzzle.parseInput("small_pancakes.config") init_state = pancake_puzzle.initial_state successor_states = pancake_puzzle.getSuccessorStates(init_state) successor_state_costs = [] for elem in successor_states: cost = pancake_puzzle.getPathCost(init_state, elem) successor_state_costs.append(cost) successor_state_heuristics = [] for elem in successor_states: heuristic = pancake_puzzle.getHeuristic(init_state, elem) successor_state_heuristics.append(heuristic) # MODEL WATERJUGS # parse the water jugs data jug_puzzle = WJ.WaterJugs() jug_puzzle.parseInput("jugs.config") #print jug_puzzle.getHeuristic((0,0),(4,2)) #wj_tests.WaterJugsTests() print "\n============ BREADTH FIRST SEARCH ============" print "\n ---- WATER JUG BFS ----" bfs = bread_first_search.BFS(jug_puzzle) bfs.bfs() # MODEL PATH-PLANNING path_puzzle = PATH.PathPlanning() path_puzzle.parseInput("cities.config") print "\n --- PATH PLANNING BFS ---" arlington_successors = path_puzzle.getSuccessorStates('Arlington') berkshire_successors = path_puzzle.getSuccessorStates('Berkshire') chelmsford_successors = path_puzzle.getSuccessorStates('Chelmsford') print path_puzzle.getHeuristic(('Berkshire', 4), ('Chelmsford', 10)) bfs_paths = bread_first_search.BFS(path_puzzle) bfs_paths.bfs() print "\n ---- PANCAKES BFS ----" pancake_bfs = bread_first_search.BFS(pancake_puzzle) pancake_bfs.bfs() print "\n\n\n ============ DEPTH FIRST SEARCH ============" print "\n ---- WATER JUG DFS ----" dfs_jugs = depth_first_search.DFS(jug_puzzle) dfs_jugs.dfs() print "\n --- PATH PLANNING DFS ---" dfs_paths = depth_first_search.DFS(path_puzzle) dfs_paths.dfs() print "\n --- BURNT PANCAKES DFS ---" dfs_pancakes = depth_first_search.DFS(pancake_puzzle) dfs_pancakes.dfs() print "\n\n\n ============ ITERATIVE-DEEPENING DEPTH FIRST SEARCH ============" print "\n ---- WATER JUG IDDFS ----" iddfs_jugs = iterative_deepening_dfs.IDDFS(jug_puzzle, max_depth=1, deepening_constant=1) iddfs_jugs.iddfs() print "\n --- PATH PLANNING IDDFS ---" iddfs_paths = iterative_deepening_dfs.IDDFS(path_puzzle, max_depth=1, deepening_constant=1) iddfs_paths.iddfs() print "\n --- BURNT PANCAKES IDDFS ---" iddfs_pancakes = iterative_deepening_dfs.IDDFS(pancake_puzzle, max_depth=1, deepening_constant=1) iddfs_pancakes.iddfs() print "\n\n\n ============ UNICOST SEARCH ============" print "\n ---- WATER JUG UNICOST ----" unicost_jugs = UC.Unicost(jug_puzzle) unicost_jugs.unicost() print "\n --- PATH PLANNING UNICOST ---" unicost_paths = UC.Unicost(path_puzzle) unicost_paths.unicost() print "\n --- BURNT PANCAKES UNICOST ---" unicost_pancakes = UC.Unicost(pancake_puzzle) unicost_pancakes.unicost() print "\n\n\n ============ GREEDY SEARCH ============" print "\n ---- WATER JUG GREEDY ----" greedy_jugs = greedy_search.Greedy(jug_puzzle) greedy_jugs.greedy() print "\n --- PATH PLANNING GREEDY ---" greedy_paths = greedy_search.Greedy(path_puzzle) greedy_paths.greedy() print "\n --- BURNT PANCAKES GREEDY ---" greedy_pancakes = greedy_search.Greedy(pancake_puzzle) greedy_pancakes.greedy() print "\n\n\n ============ A* SEARCH ============" print "\n ---- WATER JUG A* ----" astar_jugs = astar_search.AStar(jug_puzzle) astar_jugs.astar() print "\n --- PATH PLANNING A* ---" astar_paths = astar_search.AStar(path_puzzle) astar_paths.astar() print "\n --- BURNT PANCAKES A* ---" astar_pancakes = astar_search.AStar(pancake_puzzle) astar_pancakes.astar() print "\n\n\n ============ Iterative Deepening A* SEARCH ============" print "\n ---- WATER JUG Iterative Deepening A* ----" idastar_jugs = iterative_deepening_astar.IDAStar(jug_puzzle, max_depth=4, deepening_constant=4) idastar_jugs.idastar() print "\n --- PATH PLANNING Iterative Deepening A* ---" idastar_paths = iterative_deepening_astar.IDAStar(path_puzzle, max_depth=5, deepening_constant=5) idastar_paths.idastar() print "\n --- BURNT PANCAKES Iterative Deepening A* ---" idastar_pancakes = iterative_deepening_astar.IDAStar(pancake_puzzle, max_depth=5, deepening_constant=5) idastar_pancakes.idastar()
def wj_bfs(self): bfs = breadth_first_search.BFS(self.waterjugs_puzzle) bfs.bfs() return
def explore(G): print("components") for i in range(G.V): if G.visited[i] == 0: bfs.BFS(G, i)
import bfs import dfs import iddfs import astar """ main.py declares a start state, a goal state and a size of a board. It then creates 4 objects, one of each class of 4 different searches, declaring their arguments, as stated above. It then calls methods in within these classes to perform the searches. """ if __name__ == "__main__": start_state = [(4, 1), (4, 2), (4, 3), (4, 4)] goal_state = [(2, 2), (3, 2), (4, 2), (1, 1)] board_size = (4, 4) breadth = bfs.BFS(start_state, goal_state, board_size) #breadth.bfs_graph() #breadth.bfs_tree() depth = dfs.DFS(start_state, goal_state, board_size) depth.dfs_graph() #depth.dfs_tree_not_randomised() #depth.dfs_tree_randomised() iddfs = iddfs.IDDFS(start_state, goal_state, board_size) #iddfs.iddfs() astar = astar.AStar(start_state, goal_state, board_size) #astar.astar('distance')
for x in range(0, number_of_runs): startTime = time.time() method(board) total_time += (time.time() - startTime) return str(total_time / number_of_runs) if __name__ == '__main__': PATH_TO_TEST_FILES = "../TestBoards/" simpleFlow = utils.load_game(PATH_TO_TEST_FILES + "simpleBoard.txt") mediumFlow = utils.load_game(PATH_TO_TEST_FILES + "mediumBoard.txt") firstFlow = utils.load_game(PATH_TO_TEST_FILES + "easy5x5.txt") hardFlow = utils.load_game(PATH_TO_TEST_FILES + "7x7board.txt") hardestFlow = utils.load_game(PATH_TO_TEST_FILES + "9x9board.txt") bfsAI = bfs.BFS() astarAI = astar.AStarNick() backtrackingAI = back_tracking.BackTrackSolver() print "3x3 2 colors" print "bfs:", time_run(bfsAI.solve_single_gp, simpleFlow, 100) print "astar:", time_run(astarAI.solve, simpleFlow, 100) print "backtracking:", time_run(backtrackingAI.solve, simpleFlow, 100) print bfsAI = bfs.BFS() astarAI = astar.AStarNick() backtrackingAI = back_tracking.BackTrackSolver() print "5x3 3 colors" print "bfs:", time_run(bfsAI.solve_single_gp, mediumFlow, 100) print "astar:", time_run(astarAI.solve, mediumFlow, 100)
def main(): # get number of args passed in via command line num_args = len(sys.argv) # ensure we have valid input if num_args == 1: print "Usage: 'python puzzlesolver.py [config_filename] [search_algorithm_name] [optional: heuristic] " print " to run test suite: 'python puzzlesolver.py -t'" return # check if we are running the test suite if sys.argv[1] == "-t": # run the test suite runTests() return # if we get this far, then we are running a specific algorithm if num_args < 3 or num_args > 4: print "Usage: 'python puzzlesolver.py [config_filename] [search_algorithm_name] [optional: heuristic] " print " to run test suite: 'python puzzlesolver.py -t'" # otherwise, parse the args, and # take 2 input args... plus an optional one.... # FIRST ARG --> a configuration file config_file = sys.argv[1] # SECOND ARG --> Keyword to specify which algorithm to use: bfs, dfs, iddfs, unicost, greedy, astar, diastar algorithm = sys.argv[2] # THIRD ARG --> Heuristic if num_args == 4: heuristic = sys.argv[3] """ parse the config file based on what's in the first line""" # do that here.... need to write a function just to get first line and then call the appropriate # parse based on what's sent in # grab all the data and store it as a single string with open(config_file, 'r') as f: data_as_string = f.read() # split the data we've just read on newline, so we can index into it data_array = data_as_string.split("\n") # ensure that we actually have pancake data puzzle_name = data_array[0] puzzle = None # check which puzzle we have and open the correct file for it if "jugs" in puzzle_name: # then it's the jug puzzle puzzle = jugs.WaterJugs() puzzle.parseInput(config_file) elif "pancake" in puzzle_name: # then it's burnt pancakes puzzle puzzle = pancakes.BurntPancakes() puzzle.parseInput(config_file) elif "cities" in puzzle_name: # then it's path planning puzzle = paths.PathPlanning() puzzle.parseInput(config_file) else: # else it's nothing, and we have an invalid file print "Invalid data file. Please make sure your file has the correct format." return # determine which algorithm to initialize if algorithm == "bfs": print "---- START BFS ----" search = breadth_first_search.BFS(puzzle) search.bfs() print "---- END BFS ----" elif algorithm == "dfs": print "---- START DFS ----" search = depth_first_search.DFS(puzzle) search.dfs() print "---- END DFS ----" elif algorithm == "iddfs": print "---- START IDDFS ----" search = iterative_deepending_dfs.IDDFS(puzzle, 1, 1) search.iddfs() print "---- END IDDFS ----" elif algorithm == "unicost": print "----- START UNICOST ----" search = unicost_search.Unicost(puzzle) search.unicost() print "----- END UNICOST ----" elif algorithm == "greedy": print "----- START GREEDY -----" search = greedy_search.Greedy(puzzle) search.greedy() print "----- END GREEDY -----" elif algorithm == "astar": print "----- START ASTAR -----" search = astar_search.AStar(puzzle) search.astar() print "----- END ASTAR -----" elif algorithm == "idastar": print "----- START IDASTAR -----" search = idastar_search.IDAStar(puzzle, 5) search.idastar() print "----- END IDASTAR -----" else: print "Invalid algorithm name." return
def run(self): # RODA ATE A TECLA ESC SER PRESSIONADA keys = pygame.key.get_pressed() current_time = pygame.time.get_ticks() waittime = 0 while not keys[pygame.K_ESCAPE]: current_time = pygame.time.get_ticks() if current_time > waittime: pygame.event.clear() keys = pygame.key.get_pressed() waittime += 20 # Incrementa Iteracoes if pyf.spriteClicked(self.plus): if not self.mouse_state_plus: self.mouse_state_plus = True if c.IT >= 1000: c.IT += 1000 elif c.IT >= 100: c.IT += 100 elif c.IT >= 10: c.IT += 10 else: c.IT += 1 pyf.changeLabel(self.number_shuffler_label, str(c.IT)) else: self.mouse_state_plus = False # Decrementa Iteracoes if pyf.spriteClicked(self.minus): if not self.mouse_state_minus: self.mouse_state_minus = True if c.IT > 1000: c.IT -= 1000 elif c.IT > 100: c.IT -= 100 elif c.IT > 10: c.IT -= 10 elif c.IT > 0: c.IT -= 1 pyf.changeLabel(self.number_shuffler_label, str(c.IT)) else: self.mouse_state_minus = False # Botao Shuffle if pyf.spriteClicked( self.shuffle_button ): # ao clicar o sprite do shuffler chama o metodo para embaralhar self.initial_position() self.shuffler_method(c.IT) # Botoes Algoritmos move_list = [] # BFS if pyf.spriteClicked(self.BFS_button): bfs_alg = bfs.BFS(self.shuffler.get_matrix(), self.nmax) start = time.time() bfs_alg.BFS_algorithm() end = time.time() if end - start < 1: pyf.changeLabel( self.text_time2, "{0:.3f}".format( (end - start) * 1000) + "ms") else: pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s") pyf.changeLabel( self.text_memory2, "{0:.0f}".format(bfs_alg.get_memory_usage()) + " bytes") move_list = bfs_alg.get_solution_path() self.move_numbers(move_list, True) self.shuffler.reset_matrix() # DFS if pyf.spriteClicked(self.DFS_button): dfs_alg = dfs.DFS(self.shuffler.get_matrix(), self.nmax) start = time.time() dfs_alg.DFS_algorithm() end = time.time() if end - start < 1: pyf.changeLabel( self.text_time2, "{0:.3f}".format( (end - start) * 1000) + "ms") else: pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s") pyf.changeLabel( self.text_memory2, "{0:.0f}".format(dfs_alg.get_memory_usage()) + "bytes") move_list = dfs_alg.get_solution_path() self.move_numbers(move_list, True) self.shuffler.reset_matrix() # DFS_IT if pyf.spriteClicked(self.DFS_IT_button): # modificar manualmente a profundidade máxima inicial dfs_it_alg = it_dfs.IT_DFS(self.shuffler.get_matrix(), self.nmax) start = time.time() dfs_it_alg.IT_DFS_algorithm() end = time.time() if end - start < 1: pyf.changeLabel( self.text_time2, "{0:.3f}".format( (end - start) * 1000) + "ms") else: pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s") pyf.changeLabel( self.text_memory2, "{0:.0f}".format(dfs_it_alg.get_memory_usage()) + "bytes") move_list = dfs_it_alg.get_solution_path() self.move_numbers(move_list, True) self.shuffler.reset_matrix() # A_STAR H1 if pyf.spriteClicked(self.A1_button): astar_alg = a_star.A_STAR(self.shuffler.get_matrix(), self.nmax) start = time.time() astar_alg.a_star_algorithm(utils.chessboard_heuristic) end = time.time() if end - start < 1: pyf.changeLabel( self.text_time2, "{0:.3f}".format( (end - start) * 1000) + "ms") else: pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s") pyf.changeLabel( self.text_memory2, "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes") move_list = astar_alg.get_solution_path() self.move_numbers(move_list, True) self.shuffler.reset_matrix() # A_STAR H2 if pyf.spriteClicked(self.A2_button): astar_alg = a_star.A_STAR(self.shuffler.get_matrix(), self.nmax) start = time.time() astar_alg.a_star_algorithm(utils.manhattan_heuristic) end = time.time() if end - start < 1: pyf.changeLabel( self.text_time2, "{0:.3f}".format( (end - start) * 1000) + "ms") else: pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s") pyf.changeLabel( self.text_memory2, "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes") move_list = astar_alg.get_solution_path() self.move_numbers(move_list, True) self.shuffler.reset_matrix() pyf.endWait()