def run_dfs(p): results = init_results() i = 0 progress = len(p) * 8 for puzzle in p: # for puzzle in ["4x4_01_00001.txt", "4x4_02_00001.txt", "4x4_03_00001.txt", "4x4_04_00001.txt", "4x4_05_00001.txt", "4x4_06_00001.txt", "4x4_07_00001.txt"]: for order in orders: dfs = DFS(search_order=order) dim, lay = load_config(os.path.join("puzzles", puzzle)) dfs.model.load_layout(dim, lay) t = time() path = dfs.run() t = round((time() - t) * 1000, 3) depth = int(puzzle.split('_')[1]) # print(r, puzzle, order) if path == -1: continue result = { "path_length": len(path), "frontier": len(dfs.frontier) + len(dfs.explored), "explored": len(dfs.explored), "depth": dfs.deepest, "time": t } results["DFS"][order][depth].append(result) print("DFS progress: {}%".format(round((i / progress) * 100, 2)), end='\r', flush=True) i += 1 return results
def main(): g = MyGraph(100) graph = g.generate() # graph = g.static() d = DFS() v = d.dfs(g.graph, 1) print v g.render()
def setUp(self): self.dfs = DFS() self.graph = Graph() self.graph.insert_edge(create_edge(0, 1, 10)) self.graph.insert_edge(create_edge(1, 3, 10)) self.graph.insert_edge(create_edge(0, 2, 20)) self.graph.insert_edge(create_edge(0, 3, 30)) self.graph.insert_edge(create_edge(2, 3, 60)) self.graph.insert_edge(create_edge(3, 4, 120))
class TestDepthFirstSearch(unittest.TestCase): def setUp(self): self.dfs = DFS(ROMENIA, start="Arad") def test_dfs_search_success(self): self.assertEqual("Bucharest", self.dfs.search("Bucharest")) def test_dfs_search_failure(self): target = "Catalao" expected = "{0} Not Found".format(target) self.assertEqual(expected, self.dfs.search(target)) def test_get_path_success(self): path_expected = [ "Arad", "Sibiu", "Rimnicu Vilcea", "Pitesti", "Craiova", "Dobreta", "Mehadia", "Lugoj", "Timisoara", ] self.dfs.search("Bucharest") self.assertEqual(path_expected, self.dfs.get_path()) def test_get_cost_success(self): self.dfs.search("Bucharest") self.assertEqual(9, self.dfs.cost())
def scc(self): # calcola i tempi di completamento per ciascun vertice dfs = DFS(self.matrice_adiacenza) # memorizzo i vertici in una variabile locale vertici = dfs.vertici # calcolo il grafo trasposto formato dagli archi del grafo originale con direzioni invertite matrice_trasposta = self.trasposta(self.matrice_adiacenza) # chiamo DFS su grafo trasposto passando i vertici calcolati in precedenza dfs_t = DFS(matrice_trasposta, vertici) return dfs_t.numero_di_scc, dfs_t.dizionario_scc
def solve(): """ Solve the puzzle by getting the required parameters from the request args. """ algorithm = request.args['algorithm'] arr = list(map(int, request.args['input[]'][1:-1].split(','))) print(algorithm) agent = None if algorithm == "BFS": agent = BFS() elif algorithm == "DFS": agent = DFS() elif algorithm == "A start (Euclidean)": agent = AStar(Euclidean) elif algorithm == "A start (Manhatten)": agent = AStar(Manhatten) else: return arr start = timeit.default_timer() res = agent.search(arr) end = timeit.default_timer() res['time'] = end - start ret = jsonify(res) return ret
def main(): # python driver.py bfs 0,8,7,6,5,4,3,2,1 arguments = sys.argv search_type = arguments[1] # create a list of initial states from arguments[2] initial_state_list = [int(x) for x in arguments[2].split(',')] # now use this list to create initial_state object from State class initial_state = State(initial_state_list) # let's use time var to time execution start_time = time.time() # create output Object from Output class output = Output() if search_type == 'bfs': output = BFS(initial_state) elif search_type == 'dfs': output = DFS(initial_state) # elif search_type == 'ast': # output = solve_ast(initial_state) else: print('Invalid search_type: {}'.format(search_type)) # Let's add max ram uage and running time to output object output.max_ram_usage = resource.getrusage( resource.RUSAGE_SELF).ru_maxrss / 1024 output.running_time = time.time() - start_time f = open('output.txt', 'w') f.write(str(output)) f.close()
def measure_dfs_recurrent(): dfs = DFS(Graph(0)) avg_memory_consumption = [] for i in range(START_COUNTING_FROM_NODE, NUM_OF_NODES): print(f"Measuring DFS Recurrent for {i} nodes.") graph = Graph(i) dfs.graph = graph starting_node = next(iter(graph.graph)) mem_usage = memory_usage((dfs.depth_first_search, (), { 'start_node': starting_node })) avg_memory_consumption.append(mem_usage[-1]) return avg_memory_consumption
def topological_sort(graph): finishing_list = [] def pos_function(vertex): finishing_list.append(vertex) DFS(graph, pos_function=pos_function) finishing_list.reverse() return finishing_list
def test_connectedness(self, v): dfs = DFS(self, v) for i in range(self.V): if dfs.marked[i]: print(str(i) + " ", end="") if dfs.count != self.V: print("NOT ", end="") print("connected")
def main(): coppie = [(1, 3), (1, 2), (1, 4), (3, 7), (3, 10), (4, 5), (5, 9), (5, 8), (6, 10), (6, 8), (7, 6), (7, 2), (9, 10)] V, E = init_grapho(10, coppie) G = Grafo(V, E) DFS(G) print(G)
def test_random(): """ Test all approaches on random graph. """ num_of_nodes = 7 graph = Graph(num_of_nodes) starting_node = next(iter(graph.graph)) print("{:-^100}".format(" TESTING RANDOM PATH ")) dfs = DFS(graph) paths_dfs = dfs.depth_first_search(starting_node) print("DEPTH FIRST SEARCH") print("Number of Hamilton Cycles found:", len(paths_dfs)) print("Shortest path:", graph.get_shortest_path(paths_dfs), end="\n\n") bfs = BFS(graph) paths_bfs = bfs.breadth_first_search(starting_node) print("BREADTH FIRST SEARCH") print("Number of Hamilton Cycles found:", len(paths_bfs)) print("Shortest path:", graph.get_shortest_path(paths_bfs), end="\n\n") greedy = Greedy(graph) path_greedy = greedy.greedy_approach(starting_node) print("GREEDY APPROACH") print("Path length:", (path_greedy, graph.calculate_path_length(path_greedy)), end="\n\n") a_star_custom = AStarCustom(graph) path_a_star = a_star_custom.a_star(starting_node) print("A* APPROACH") print("Path length:", (path_a_star, graph.calculate_path_length(path_a_star)), end="\n") print("{:-^100}".format(" END OF TEST "), end="\n\n")
def find_path(source, target, graph): def target_check(u, v): return v == target parent = DFS(graph=graph, root=source, check_terminate=target_check) print("Parent: ", parent) path = [target] cur_country = target while parent[cur_country] is not None: parent_country = parent[cur_country] path.append(parent_country) cur_country = parent_country path.reverse() return path
class TestDFS(unittest.TestCase): def setUp(self): self.dfs = DFS() self.graph = Graph() self.graph.insert_edge(create_edge(0, 1, 10)) self.graph.insert_edge(create_edge(1, 3, 10)) self.graph.insert_edge(create_edge(0, 2, 20)) self.graph.insert_edge(create_edge(0, 3, 30)) self.graph.insert_edge(create_edge(2, 3, 60)) self.graph.insert_edge(create_edge(3, 4, 120)) def test_dfs(self): result = self.dfs.dfs(0, self.graph) expected = [0, 1, 3, 2, 4] self.assertEqual(expected, result)
def correr_busqueda(tipo_busqueda=0): tablero = CMP(get_mapa_caracteres()) if tipo_busqueda == 1: resultados, tablero = BFS(tablero) elif tipo_busqueda == 2: resultados, tablero = DFS(tablero) elif tipo_busqueda == 3: resultados, tablero = IDS(tablero) elif tipo_busqueda == 0: print("No se envio el parametro tipo de busqueda") exit() else: print("No se envio un tipo de busqueda correcto") exit() return resultados, tablero
def next_direction(data, board, destination, current_pos, health_flag): # print 'data:' , data print('turn: ', data['turn']) print('current pos: ', current_pos) # direction = data['turn'] health = data['you']['health'] direction = 'up' next_pos = DFS(current_pos, destination, board, health_flag) if (next_pos is None): return None print('next pos: ', next_pos) if next_pos[0] == current_pos[0]: direction = ('up' if next_pos[1] < current_pos[1] else 'down') if next_pos[1] == current_pos[1]: direction = ('left' if next_pos[0] < current_pos[0] else 'right') return direction
def run(self): if self.algorithm == "DFS": self.solution = DFS.run(self.source, self.destinations) if self.solution is not None: self.end_time = self.start_time + len(self.solution) - 1 self.end_time = self.end_time % 24 elif self.algorithm == "BFS": self.solution = BFS.run(self.source, self.destinations) if self.solution is not None: self.end_time = self.start_time + len(self.solution) - 1 self.end_time = self.end_time % 24 elif self.algorithm == "UCS": self.solution = UCS.run(self.start_time, self.source, self.destinations) if self.solution is not None: self.end_time = self.solution.pop(0) else: raise Exception("Unexpected Algorithm = " + self.algorithm)
class TestDepthFirstSearch(unittest.TestCase): def setUp(self): self.dfs = DFS(ROMENIA, start='Arad') def test_dfs_search_success(self): self.assertEqual('Bucharest', self.dfs.search('Bucharest')) def test_dfs_search_failure(self): target = 'Catalao' expected = '{0} Not Found'.format(target) self.assertEqual(expected, self.dfs.search(target)) def test_get_path_success(self): path_expected = ['Arad', 'Sibiu', 'Rimnicu Vilcea', 'Pitesti', 'Craiova', 'Dobreta', 'Mehadia', 'Lugoj', 'Timisoara'] self.dfs.search('Bucharest') self.assertEqual(path_expected, self.dfs.get_path()) def test_get_cost_success(self): self.dfs.search('Bucharest') self.assertEqual(9, self.dfs.cost())
def run(): label_find_the_result.config(text="Result:") label_time.config(text="Time:") label_steps.config(text="Steps:") btn_run.config(state=tk.DISABLED) btn_reset.config(state=tk.DISABLED) radio_dfs.config(state=tk.DISABLED) radio_bfs.config(state=tk.DISABLED) radio_bestfs.config(state=tk.DISABLED) radio_hc.config(state=tk.DISABLED) algorithm = alg.get() res = "" steps = 0 time_start = time.time() if algorithm == 1: res = DFS.solve(puzzle_in, window) print("DFS: ", res) elif algorithm == 2: res = BFS.solve(puzzle_in, window) print("BFS: ", res) elif algorithm == 3: res = BestFirstSearch.solve(puzzle_in, window) print("Best First Search: ", res) elif algorithm == 4: res = HillClimbing.solve(puzzle_in, window) print("Hill Climbing: ", res) time_end = time.time() if res is None: solution = "No!" else: solution = "Yes!" steps = len(res) output(solution, time_end - time_start, steps) btn_run.config(state=tk.NORMAL) btn_reset.config(state=tk.NORMAL) radio_dfs.config(state=tk.NORMAL) radio_bfs.config(state=tk.NORMAL) radio_bestfs.config(state=tk.NORMAL) radio_hc.config(state=tk.NORMAL)
# row = int(input('Enter number of Rows (Must be > 1): ')) row = 2 # col int(input('Enter number of Columns (Must be > 1): ')) col = 3 puzzel = GameController.create_puzzle(row, col) puzzel = GameController.scramble(puzzel) # puzzel = [[' 0 ', ' 0 ', ' 0 '], [' 1 ', ' 0 ', ' 1 ']] puzzelorg = deepcopy(puzzel) puzzeldfs = deepcopy(puzzel) # ------------------------------------------------------------------------- # uncomment this block to use the dfs_ai search algorithm moves = DFS.perform(puzzel, row, col) # uncomment to use the A* search # moves = AStar.perform(puzzel, row,col) # uncomment to use the BFS # moves = BFS.perform(puzzel, row, col) # ------------------------------------------------------------------------- print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") for r in puzzelorg: print("".join(r)) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") for move in moves:
__author__ = 'muneeb' from node import Node from ids import IDS from dfs import DFS from bfs import BFS from graph_generator import Graph_Generator import copy start = "1" goal = "15" g = Graph_Generator(8000) graph = g.generate_graph() ids = IDS(copy.deepcopy(graph), start, goal) bfs = BFS(copy.deepcopy(graph), start, goal) dfs = DFS(copy.deepcopy(graph), start, goal) ids.walk() bfs.walk() dfs.walk()
def try_all_approaches(num_of_samples: int, num_of_nodes: int): """ Execute all approaches on the same graphs for given number of nodes and samples (the more samples the more statistically accurate results). Returns: Achieved path lengths and execution times for all approaches. """ graph = Graph(0) dfs = DFS(graph) dfs_path_lengths = [] dfs_execution_times = [] bfs = BFS(graph) bfs_path_lengths = [] bfs_execution_times = [] greedy = Greedy(graph) greedy_path_lengths = [] greedy_execution_times = [] a_star_custom = AStarCustom(graph) a_star_path_lengths = [] a_star_execution_times = [] for i in range(a_star_custom.num_of_heuristics): a_star_path_lengths.append([]) a_star_execution_times.append([]) for j in range(num_of_samples): graph = Graph(num_of_nodes) starting_node = next(iter(graph.graph)) start = time.time() dfs.graph = graph paths_dfs = dfs.depth_first_search(starting_node) dfs_path_lengths.append(Graph.get_shortest_path(paths_dfs)[1]) execution_time = time.time() - start dfs_execution_times.append(execution_time) start = time.time() bfs.graph = graph paths_bfs = bfs.breadth_first_search(starting_node) bfs_path_lengths.append(Graph.get_shortest_path(paths_bfs)[1]) execution_time = time.time() - start bfs_execution_times.append(execution_time) start = time.time() greedy.graph = graph path_greedy = greedy.greedy_approach(starting_node) greedy_path_lengths.append(Graph.calculate_path_length(path_greedy)) execution_time = time.time() - start greedy_execution_times.append(execution_time) for i in range(a_star_custom.num_of_heuristics): start = time.time() a_star_custom.graph = graph a_star_custom.heuristic_choice = i path_a_star = a_star_custom.a_star(starting_node) execution_time = time.time() - start a_star_path_lengths[i].append( Graph.calculate_path_length(path_a_star)) a_star_execution_times[i].append(execution_time) dfs_avg_results = sum(dfs_path_lengths) / num_of_samples, sum( dfs_execution_times) / num_of_nodes, "DFS Recurrent" bfs_avg_results = sum(bfs_path_lengths) / num_of_samples, sum( bfs_execution_times) / num_of_nodes, "BFS" greedy_avg_results = sum(greedy_path_lengths) / num_of_samples, sum( greedy_execution_times) / num_of_nodes, "Greedy" a_star_avg_results = [] for i in range(a_star_custom.num_of_heuristics): label = "A* heuristic " + str(i) a_star_avg_results.append( (sum(a_star_path_lengths[i]) / num_of_samples, sum(a_star_execution_times[i]) / num_of_samples, label)) data = [dfs_avg_results, bfs_avg_results, greedy_avg_results] data.extend(a_star_avg_results) return data
from state import State from bfs import BFS from dfs import DFS SEARCH_TYPE = sys.argv[1] INITIAL_STATE = map(int, sys.argv[2].split(',')) game = State(INITIAL_STATE); search = None if SEARCH_TYPE == 'bfs': search = BFS(game) if SEARCH_TYPE == 'dfs': search = DFS(game) result = search.perform_search() goal_pos = result.position res = resource.getrusage(resource.RUSAGE_SELF) def trace_path(goal_pos): pos = goal_pos path = [] while pos != None: if (pos.node.action != None): path.append(pos.node.action) pos = pos.prev
from bestfirst import BestFirstSearch from astar import AStarSearch from board import heuristicOption import time """ Project 1.1: Indonesian Dot Puzzle Board Class COMP 472 NN DUE: Feb 9th, 2020 Samantha Yuen (40033121), Andrew Marcos (40011252), Michael Gagnon (40030481) This file is responsible for starting all three searches on the board test file. """ filename = input("Enter filename with board setup:") listOfBoards = returnBoards(filename) dfs = DFS() bfs = BestFirstSearch() afs = AStarSearch() for board in listOfBoards: #input('enter to continue') start_time = time.time() dfs.dfsSearch(board) print("--- Board #%s finished in %s seconds for dfs ---" % (board.num, time.time() - start_time)) start_time = time.time() bfs.bestFirstSearch(board) print( "--- Board #%s finished in %s seconds for bfs with heuristic %s ---" % (board.num, time.time() - start_time, heuristicOption)) start_time = time.time()
# row = int(input('Enter number of Rows (Must be > 1): ')) row = 2 # col int(input('Enter number of Columns (Must be > 1): ')) col = 3 puzzel = GameController.create_puzzle(row, col) puzzel = GameController.scramble(puzzel) # puzzel = [[' 0 ', ' 0 ', ' 0 '], [' 1 ', ' 0 ', ' 1 ']] puzzelorg = deepcopy(puzzel) puzzeldfs = deepcopy(puzzel) # ------------------------------------------------------------------------- # uncomment this block to use the dfs_ai search algorithm moves = DFS.perform(puzzel, row, col) # uncomment to use the A* search # moves = AStar.perform(puzzel, row,col) # uncomment to use the BFS # moves = BFS.perform(puzzel, row, col) # ------------------------------------------------------------------------- print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") for r in puzzelorg: print("".join(r)) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def solveDFS(rubik): aux = time.time() solution_DFS = DFS.search(rubik, lambda x: x == RubikPuzzle()) time["DFS: "](time.time() - aux) * 1000 aux = 0 return solution_DFS
def test_dfs(self): agent = DFS() steps = agent.search([1, 2, 5, 3, 4, 0, 6, 7, 8]) print("Solved in {} steps".format(len(steps))) print(steps)
for line in txtFile.splitlines(): try: if line[1] == ',': if len(playerPositions) == 0: playerPositions.append(int(line[0])) playerPositions.append(int(line[2])) else: boxPositions.append([int(line[0]), int(line[2])]) else: j = 0 temp = [] for a in line.replace('\n', ''): temp.append(a) if a == 'X': goals.append([i, j]) j += 1 gameTable.append(temp) i += 1 except IndexError: pass readLevel(sys.argv[1]) print(BFS(gameTable, playerPositions, goals, boxPositions)) print(DFS(gameTable, playerPositions, goals, boxPositions)) print(IDFS(gameTable, playerPositions, goals, boxPositions))
def setUp(self): self.dfs = DFS(ROMENIA, start="Arad")
from dfs import DFS from bfs import BFS def print_steps(steps_sol): for s in steps_sol: print("================================") for i in range(0, 9, 3): print(s[i:i + 3]) agent = DFS() steps = agent.search([1, 2, 5, 3, 4, 0, 6, 7, 8]) print_steps(steps) agent = BFS() steps = agent.search([1, 2, 0, 3, 4, 5, 6, 7, 8]) print_steps(steps)
import balloon_manager import read_input_file from cell import Cell from dfs import DFS from graph2 import Graph2, Vertex2 config = read_input_file.load_configuration('test_input') selected_targets = balloon_manager.select_targets(config) balloons = balloon_manager.assign_balloons(config, selected_targets) g = Graph2(config) dfs = DFS(g, config) for balloon in balloons: target_vertex = Vertex2(balloon.target_cell, 1) dfs.search(dfs.start_vertex, target_vertex) print "start_vertex: %s, target_vertex: %s" % (dfs.start_vertex, target_vertex) print "path found: %s" % dfs.path_found print "path: %s" % dfs.get_path(target_vertex) if False: for r in range(config['R']): # For all rows for c in range(config['C']): # For all columns v = Vertex2(Cell(r, c), 2) adj = g.adj(v) print "Adjacent cells for vertex %s are: %s" % (v, adj)
def iter_dfs(self, start_node): return DFS(self, start_node)
def run_tests(filepath): """ runs all the tests for the program """ generator = GraphGenerator(filepath) graph = generator.graph_from_text_file() # test for object references in original graph print "TEST: Testing object reference on original graph" print object_references(graph) dfs_1 = DFS(graph) dfs_1.dfs() # graph after first run of dfs with vertices ordered by increasing # finishing time. dfs_1.dfs_graph_from_call_stack() # test for object reference after first dfs run print "TEST: Testing object reference on dfs 1 graph" print object_references(dfs_1.dfs_graph) print "Printing DFS 1 Graph" print dfs_1.dfs_graph print "*****************************************" # graph after transpose of the original graph dfs_1_trans_graph = dfs_1.dfs_graph.transpose() print "Printing transpose of DFS 1 Graph" print dfs_1_trans_graph print "*****************************************" # # Second run of dfs on transposed graph dfs_2 = DFS(dfs_1_trans_graph) dfs_2.dfs() dfs_2.dfs_graph_from_call_stack() # test for object reference after first dfs run print "TEST: Testing object reference on dfs 2 graph" print object_references(dfs_2.dfs_graph) print "Printing DFS 2 Graph" print dfs_2.dfs_graph print "*****************************************" print "Printing DFS components" print "*****************************************" print_dfs_components(dfs_2.dfs_forest)
print("Iterator po krawedziach") for i in dGraph.iteredges(): print(i) print('BFS \n') bfs = BFS(dGraph, 2) iter_bfs = iter(bfs) for i in iter_bfs: print(i) for i in dGraph.iter_bfs(2): print(i) print("DFS \n") dfs = DFS(dGraph, 2) iter_dfs = iter(dfs) for i in iter_dfs: print(i) for i in dGraph.iter_dfs(2): print(i) for node in dGraph: # iterator po wierzchołkach print("wierzchołek", node) for node in uGraph: # iterator po wierzchołkach print("wierzchołek ", node) print("stopien ", len(uGraph[node])) uGraph.__repr__()
from json import loads from bfs import BFS from dfs import DFS from ids import IDS from hc import HC # Load tree data from file filePath = open('./data.json') data = filePath.read() dataJson = loads(data) tree = dataJson['tree'] # list of goals of DFS, DFS, IDS algorithms goals = dataJson['goals'] hill_climb = dataJson['hill-climb'] # list of goals of HC algorithm goals_HC = dataJson['hill-climb']['goals'] # root node root = dataJson['root'] if __name__ == '__main__': DFS(tree, root, goals) BFS(tree, root, goals) IDS(tree, root, goals, 2) HC(hill_climb, root, goals_HC)
print "\nBFS - Map2" world = World(Util.read_file(map2), b_map2) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nBFS - Map3" world = World(Util.read_file(map3), b_map3) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nDFS - Map1" world = World(Util.read_file(map1), d_map1) dfs_search = DFS(world) dfs_search.search() print timeit.Timer(dfs_search.search).timeit(1) print "\nDFS - Map2" world = World(Util.read_file(map2), d_map2) dfs_search = DFS(world) dfs_search.search() print timeit.Timer(dfs_search.search).timeit(1) print "\nDFS - Map3" world = World(Util.read_file(map3), d_map3) dfs_search = DFS(world) dfs_search.search() print timeit.Timer(dfs_search.search).timeit(1)