def strongly_connected_components(filepath): """ Method to calculate the strongly connected components in the graph and write it in an output file Expects: filepath (filename is sufficient if file is in the same directory else absolute file path is required) Effects: Generates the output file with name output_filename in the same directory """ generator = GraphGenerator(filepath) graph = generator.graph_from_text_file() 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() # graph after transpose of the original graph dfs_1_trans_graph = dfs_1.dfs_graph.transpose() # # Second run of dfs on transposed graph dfs_2 = DFS(dfs_1_trans_graph) dfs_2.dfs() dfs_2.dfs_graph_from_call_stack() filename = filepath.split("/")[-1] file_obj = open("output_" + filename, "w") write_dfs_components(file_obj, dfs_2.dfs_forest) file_obj.close()
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)
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 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 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 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(): g = MyGraph(100) graph = g.generate() # graph = g.static() d = DFS() v = d.dfs(g.graph, 1) print v g.render()
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 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_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 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
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 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 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 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")
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)
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)
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
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 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()
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)
def setUp(self): self.dfs = DFS(ROMENIA, start='Arad')
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 iter_dfs(self, start_node): return DFS(self, start_node)
def test_dfs(): adj = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) graph = from_numpy_array(adj) dfs = DFS() dfs.search(graph)
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__()