def test_bidirectional_breadth_first_search_vs_depth_first_graph_search(): eight_puzzle = EightPuzzle(initial=instance_three, goal=goal) eight_puzzle_reversed = EightPuzzle(initial=goal, goal=instance_three) ins_problem = InstrumentedProblem(eight_puzzle) res = instrumented_bidirectional_breadth_first_search(eight_puzzle, eight_puzzle_reversed, True) depth_first_graph_search(ins_problem) assert (res[1]) <= ins_problem.explored
def huarong_pass_search(search_name): goal_actions = [] hp = HuarongPass() if search_name == 'BFS': # print "Breadth first search...good choice. ", time.asctime() goal_actions = search.breadth_first_search(hp).solution() elif search_name == 'DFS': # print "Depth first search...really?", time.asctime() goal_actions = search.depth_first_graph_search(hp).solution() elif search_name == 'IDS': # print "Iterative deepening search...great choice!", time.asctime() goal_actions = search.iterative_deepening_search(hp).solution() elif search_name == 'BID': # print "Bidirectional search...not required...using BFS instead..." goal_actions = huarong_pass_search('BFS') elif search_name == 'DLS': # print "Depth limited search...", time.asctime() goal_actions = search.depth_limited_search(hp, DEPTH_LIMIT).solution() else: print "Invalid search_name given. Exiting..." return goal_actions
def test_astar_gaschnig_vs_depth_first(): eight_problem = InstrumentedProblem( EightPuzzle(initial=instance_one, goal=goal)) eight_problem1 = InstrumentedProblem( EightPuzzle(initial=instance_one, goal=goal)) res = astar_search(eight_problem, EightPuzzleExtended(eight_problem).gaschnig_index) res1 = depth_first_graph_search(eight_problem1) assert res.state == goal assert res1.state == goal assert eight_problem.explored < eight_problem1.explored
def huarong_pass_search(desired_search_strategy): """The function returns a list of actions that when applied to the initial state lead to the goal state.""" initTime = datetime.datetime.now() problem = HuarongPass() if desired_search_strategy == "BFS": s = search.breadth_first_tree_search(problem) elif desired_search_strategy == "DFS": s = search.depth_first_graph_search(problem) elif desired_search_strategy == "IDS": s = search.iterative_deepening_search(problem) else: print "Desired search strategy not found!" endTime = datetime.datetime.now() print "Time taken", endTime - initTime return s.solution()
def main(): """ to run: python main.py <method> <input file> <output file> """ if (len(sys.argv) != 4): print("Wrong number of arguments. Use correct syntax:") syntax_msg() return -1 methods = {'breadth': 1, 'depth': 2, 'best': 3, 'astar': 4} if sys.argv[1] in methods: method = methods[sys.argv[1]] else: print("Wrong method. Use correct syntax:") syntax_msg() return -1 # method = 3 # stacks = readInput("inputfiles/inputN6-2.txt") stacks = readInput(sys.argv[2]) board = Board(stacks) problem = Problem(board) t0 = time.perf_counter() if method == 1: result = breadth_first_graph_search(problem) elif method == 2: result = depth_first_graph_search(problem) # result = profile.runctx( # "depth_first_graph_search(problem)", globals(), locals()) elif method == 3: result = best_first_graph_search(problem, lambda n: n.h_cost) # result = profile.runctx( # "best_first_graph_search(problem, lambda n: n.h_cost)", globals(), locals()) elif method == 4: result = astar_search(problem) t1 = time.perf_counter() print("Time: ", t1 - t0) if result: writeToFile(sys.argv[3], result.solution()) # writeToFile("output.txt", result.solution()) else: print("Could not solve problem")
def main(): args = parser.parse_args() bounds, ghosts, pacman, goal = mapPositions(args.layout) print('Barreiras:', bounds) print('Fantasmas:', ghosts) print('Pacman:', pacman) print('Gol:', goal) print() #Problema e algoritmos problem = PacmanProblem(obstacles=bounds | ghosts, initial=pacman, goal=goal) gfsProblem = greedy_best_first_search(problem) astarProblem = astar_search(problem) bfsProblem = breadth_first_graph_search(problem) dfsProblem = depth_first_graph_search(problem) print('Greedy Best First Search:') print('Caminho:', gfsProblem.path()) print('Gol:', gfsProblem) print('A* Search:') print('Caminho:', astarProblem.path()) print('Gol:', astarProblem) print('Breadth-First Search:') print('Caminho:', bfsProblem.path()) print('Gol:', dfsProblem) print('Depth-First Search:') print('Caminho:', dfsProblem.path()) print('Gol:', dfsProblem) print() print('Gerando saídas...') generateOutput(gfsProblem.path(), args.layout, 'gfs') generateOutput(astarProblem.path(), args.layout, 'astar') generateOutput(dfsProblem.path(), args.layout, 'bfs') generateOutput(dfsProblem.path(), args.layout, 'dfs') print() print('Desempenho:') report([ greedy_best_first_search, astar_search, breadth_first_graph_search, depth_first_graph_search ], [problem])
def run(algorithm, grid, start, stop): """Verify that the start and stop locations are valid then run the indicated search algorithms and return the final node. If no algorithm is indicated it will default to A_star search :param algorithm: The search algorithm to use :param grid: grid to find a path through :param start: starting location :param stop: goal location :return: The path taken """ # Verify start and stop position are valid if not valid_position(grid, start): try: if grid[start] == 0: print(start, 'Is not a valid start position, it is in an obstacle.') except IndexError: print( start, 'Is not a valid start position. Start position must be within the grid: ', grid.shape) exit() if not valid_position(grid, stop): try: if grid[stop] == 0: print(stop, 'Is not a valid stop position, it is an obstacle.') except IndexError: print( stop, 'Is not a valid stop position. Stop position must be within the range of the grid shape:', grid.shape) exit() my_problem = PathingProblem(start, stop, grid) # Creating instance of PathingProblem if algorithm == 'breadth_first_search' or algorithm == 'b': return breadth_first_search(my_problem) elif algorithm == 'depth_first_graph_search' or algorithm == 'd': return depth_first_graph_search(my_problem) else: # Defaults to a_star search return astar_search(my_problem)
def busca(a, b): ab = search.GPSProblem(a, b, search.romania) sol = search.breadth_first_graph_search(ab) print "\nAnchura: nodos exapndidos = " + str(sol[1]) print sol[0].path() sol = search.depth_first_graph_search(ab) print "\nProfundidad: nodos exapndidos = " + str(sol[1]) print sol[0].path() sol = search.branch_and_bound(ab) print "\nRamificacion y acotacion: nodos exapndidos = " + str(sol[1]) print sol[0].path() sol = search.branch_and_bound_sub(ab) print "\nRamificacion y acotacion con subestimacion: nodos exapndidos = " + str( sol[1]) print sol[0].path() print '==================================================================================='
def solve_and_print(problem): depth_first = search.depth_first_graph_search(problem) breadth_first = search.breadth_first_graph_search(problem) branch_and_bound = search.bab(problem) subestimation = search.subBAB(problem) print("==================== %s ====================" % (problem.problem_title())) print('Busqueda en profundidad: \n', depth_first["solution"].path()) print('- Nodos visitados: %d\n- Nodos generados %d' % (depth_first["visited_nodes"], depth_first["generated_nodes"])) print('Busqueda en anchura: \n', breadth_first["solution"].path()) print('- Nodos visitados: %d\n- Nodos generados %d' % (breadth_first["visited_nodes"], breadth_first["generated_nodes"])) print('Branch & Bound: \n', branch_and_bound["solution"].path()) print('- Nodos visitados: %d\n- Nodos generados %d' % (branch_and_bound["visited_nodes"], branch_and_bound["generated_nodes"])) print('Branch & Bound (subestimation): \n', subestimation["solution"].path()) print('- Nodos visitados: %d\n- Nodos generados %d' % (subestimation["visited_nodes"], subestimation["generated_nodes"]))
# Search methods import search #ab = search.GPSProblem('SA', 'NT' , search.australia) ab = search.GPSProblem('A', 'B', search.romania) ro = search.GPSProblem('R', 'O', search.romania) sb = search.GPSProblem('S', 'B', search.romania) tp = search.GPSProblem('T', 'P', search.romania) vc = search.GPSProblem('V', 'C', search.romania) zu = search.GPSProblem('Z', 'U', search.romania) print("------ RECORRIDO ARAD - BUCHAREST ------") print("Búsqueda en anchura: " + str(search.breadth_first_graph_search(ab).path())) #Anchura print("Búsqueda en Profundidad" +str(search.depth_first_graph_search(ab).path())) #Profundidad print("Búsqueda ramificación y acotación" +str(search.ramificacion_acotacion(ab).path())) #ramificacion y acotacion. print("Búsqueda ramificación y acotación con subestimación" + str(search.ramificacion_subestimacion(ab).path())) print("\n------ RECORRIDO ORADEA - RIMNICU VILCEA ------") print("Búsqueda en anchura: " + str(search.breadth_first_graph_search(ro).path())) #Anchura print("Búsqueda en Profundidad" +str(search.depth_first_graph_search(ro).path())) #Profundidad print("Búsqueda ramificación y acotación" +str(search.ramificacion_acotacion(ro).path())) #ramificacion y acotacion. print("Búsqueda ramificación y acotación con subestimación" + str(search.ramificacion_subestimacion(ro).path())) print("\n------ RECORRIDO SIBIU - BUCHAREST ------") print("Búsqueda en anchura: " + str(search.breadth_first_graph_search(sb).path())) #Anchura print("Búsqueda en Profundidad" +str(search.depth_first_graph_search(sb).path())) #Profundidad print("Búsqueda ramificación y acotación" +str(search.ramificacion_acotacion(sb).path())) #ramificacion y acotacion. print("Búsqueda ramificación y acotación con subestimación" + str(search.ramificacion_subestimacion(sb).path())) print("\n------ RECORRIDO TIMISOARA - PITESTI ------")
import search mi_problema = search.GPSRoutes('A', 'F', search.romania) print "Breadth search:" search.breadth_first_graph_search(mi_problema) print "\nDepth search:" search.depth_first_graph_search(mi_problema)
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print "Anchura" , search.breadth_first_graph_search(ab).path() print "Profundidad" , search.depth_first_graph_search(ab).path() print "Rama coste y acotacion" , search.branch_first_graph_search(ab).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_search(ab).path() #print search.astar_search(ab).path() # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
ab = search.GPSProblem('A', 'B', search.romania) oc = search.GPSProblem('O', 'C', search.romania) sd = search.GPSProblem('S', 'D', search.romania) tf = search.GPSProblem('T', 'F', search.romania) lp = search.GPSProblem('L', 'P', search.romania) nm = search.GPSProblem('N', 'M', search.romania) print("Ejecuciones con Busqueda en Anchura") node, count = search.breadth_first_graph_search(ab) print(node.path(), end='') print(" Nº de nodos visitados: ", end='') print(count) print("Ejecuciones con Busqueda en Profundidad") node, count = search.depth_first_graph_search(ab) print(node.path(), end='') print(" Nº de nodos visitados: ", end='') print(count) print("-----------------------------------------------") print("Ejecuciones con Nodos A-B") print("Ramificacion y Acotacion -> ", end='') node, count = search.ra_graph_search(ab) print(node.path(), end='') print(" Nº de nodos visitados: ", end='') print(count) print("Ramificacion y Acotacion con Subestimacion -> ", end='') node, count = search.ra_sub_graph_search(ab)
''' from search import romania_map, GraphProblem, breadth_first_tree_search,\ depth_first_graph_search, iterative_deepening_search,\ recursive_best_first_search, breadth_first_search, uniform_cost_search,\ depth_limited_search print("Romania Locations:") print("==================") print(romania_map.locations) print("Romania Map:") print("=============") print(romania_map.dict) romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) print("Search Algorithms Results:") print("==========================") print(breadth_first_search(romania_problem).solution()) #print(breadth_first_search(romania_problem).path_cost) print(uniform_cost_search(romania_problem).solution()) #print(uniform_cost_search(romania_problem).path_cost) print(depth_first_graph_search(romania_problem).solution()) print(depth_first_graph_search(romania_problem).path_cost)
import search ab = search.GPSProblem('A', 'B', search.romania) on = search.GPSProblem('O', 'N', search.romania) lr = search.GPSProblem('L', 'R', search.romania) hz = search.GPSProblem('H', 'Z', search.romania) do = search.GPSProblem('D', 'O', search.romania) lista = [ab, on, lr, hz, do] while len(lista) > 0: x = lista.pop() print "\n-----------------------------------------------------------------------" print "\nnivel-anchura, FIFO" print search.breadth_first_graph_search(x).path() print "\nprofundidad-altura, LIFO-pila-stack" print search.depth_first_graph_search(x).path() #print search.best_first_graph_search(ab,2).path() print "\nramificacion y acotacion" print search.ramificacionacotacion_first_graph_search(x).path() print "\nramificacion y acotacion con subestimacion" print search.ramificacionacotacionconsubestimacion_first_graph_search( x).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_search(ab).path() #print search.astar_search(ab).path() # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418
CA LO AL RA; IF: NH PI CA BO CE; LI: PC CE AU MP AQ; LO: CA AL FC; LR: MP AU RA PA; MP: AQ LI AU LR; NB: NH CE PL BR; NH: PI IF CE NB; NO: PI; PA: LR RA; PC: PL CE LI AQ; PI: NH NO CA IF; PL: BR NB CE PC; RA: AU BO FC PA LR""") #______________________________________________________________________________ # if __name__ == "__main__": import time ## country = australia # one of the map colouring CSP's ## country = france # one of the map colouring CSP's country = usa # one of the map colouring CSP's t0 = time.time() sol = depth_first_graph_search(country) t1 = time.time() print("DFS solution -> ", sol) print("DFS Solver took ", t1 - t0, ' seconds') t0 = time.time() sol = min_conflicts(country) t1 = time.time() print("Min-conflict solver found -> ", sol) print("Min-conflict Solver took ", t1 - t0, ' seconds') ## print min_conflicts(france) ## {'WA': 'B', 'Q': 'B', 'T': 'G', 'V': 'B', 'SA': 'R', 'NT': 'G', 'NSW': 'G'}
# 1. Set up the puzzle. # Examples from the textbook solved_fig64b = Sudoku('483921657967345821251876493548132976729564138136798245372689514814253769695417382') easy_fig64a = Sudoku('..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..') # Example from the AIMA csp.py library harder_aima_csp = Sudoku('4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......') # Example from http://zonkedyak.blogspot.com/2006/11/worlds-hardest-sudoku-puzzle-al.html hardest_escargot = Sudoku('1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..') puzzle = solved_fig64b print('\nStart:') puzzle.display(puzzle.infer_assignment()) # 2. Solve the puzzle. depth_first_graph_search(puzzle) # AC3(puzzle) # backtracking_search(puzzle) # Consider adding: select_unassigned_variable=mrv & inference=forward_checking # min_conflicts(puzzle) # 3. Print the results. if puzzle.goal_test(puzzle.infer_assignment()): print('\nSolution:') puzzle.display(puzzle.infer_assignment()) else: print('\nFailed - domains: ' + str(puzzle.curr_domains)) puzzle.display(puzzle.infer_assignment())
display) if __name__ == "__main__": input_file = sys.argv[1] algo = sys.argv[2] map_dict, heuristic, start, goal = parse(input_file) problem = MapProblem(start, goal, map_dict, heuristic) if algo == 'BFTS': goal_node = breadth_first_tree_search(problem) elif algo == 'DFTS': goal_node = depth_first_tree_search(problem) elif algo == 'DFGS': goal_node = depth_first_graph_search(problem) elif algo == 'BFGS': goal_node = breadth_first_graph_search(problem) elif algo == 'UCTS': goal_node = uniform_cost_tree_search(problem) elif algo == 'UCGS': goal_node = uniform_cost_search(problem) elif algo == 'GBFTS': goal_node = greedy_best_first_tree_search(problem) elif algo == 'GBFGS': goal_node = greedy_best_first_graph_search(problem, problem.h) elif algo == 'ASTS': goal_node = astar_tree_search(problem, h=problem.h) elif algo == 'ASGS': goal_node = astar_search(problem, h=problem.h) else:
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print "Breadth Search : " path, expansion = search.breadth_first_graph_search(ab) path = [x for x in reversed(path.path())] print "Ruta : %s --> %d Expansiones" % (path, expansion) print "\nDepth Search : " path, expansion = search.depth_first_graph_search(ab) path = [x for x in reversed(path.path())] print "Ruta : %s --> %d Expansiones" % (path, expansion) print "\nBranch and Bound : " path, expansion = search.branch_and_bound_graph_search(ab) print path.path() path = [x for x in reversed(path.path())] print "Ruta : %s --> %d Expansiones" % (path, expansion) print "\nSubestimated Branch and Bound : " path, expansion = search.subestimated_branch_and_bound_graph_search(ab) path = [x for x in reversed(path.path())] print "Ruta : %s --> %d Expansiones" % (path, expansion) # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print("Busqueda en anchura") A = search.breadth_first_graph_search(ab) print("Recorrido:", A.path()) print("Coste:", A.path_cost) print("\n") print("Busqueda en profundidad") B = search.depth_first_graph_search(ab) print("Recorrido:", B.path()) print("Coste:", B.path_cost) print("\n") print("Busqueda ramificacion y acotacion") C = search.ram_graph_search(ab) print("Recorrido:", C.path()) print("Coste:", C.path_cost) print("\n") print("Busqueda ramificacion y acotacion con heuristica") D = search.ram_with_h_graph_search(ab) print("Recorrido:", D.path()) print("Coste:", D.path_cost) # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
''' Created on Oct 2, 2016 @author: farida ''' from search import romania_map, GraphProblem, breadth_first_tree_search,\ depth_first_graph_search, iterative_deepening_search,\ recursive_best_first_search, breadth_first_search, uniform_cost_search,\ depth_limited_search print("Romania Locations:") print("==================") print(romania_map.locations) print("Romania Map:") print("=============") print(romania_map.dict) romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) print("Search Algorithms Results:") print("==========================") print(breadth_first_search(romania_problem).solution()) #print(breadth_first_search(romania_problem).path_cost) print(uniform_cost_search(romania_problem).solution()) #print(uniform_cost_search(romania_problem).path_cost) print(depth_first_graph_search(romania_problem).solution()) print(depth_first_graph_search(romania_problem).path_cost)
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) an = search.GPSProblem('A', 'N', search.romania) no = search.GPSProblem('N', 'O', search.romania) print "Trayecto A-B:" print "Busqueda en anchura: ",search.breadth_first_graph_search(ab).path() print "Busqueda en profundidad: ",search.depth_first_graph_search(ab).path() print "Busqueda por Ramificacion y Acotacion: ",search.ram_acot_graph_search(ab).path() print "Busqueda por Ramificacion y Acotacion con subestimacion: ",search.ram_acot_sub_graph_search(ab).path() print "\nTrayecto A-N:" print "Busqueda en anchura: ", search.breadth_first_graph_search(an).path() print "Busqueda en profundidad: ",search.depth_first_graph_search(an).path() print "Busqueda por Ramificacion y Acotacion: ",search.ram_acot_graph_search(an).path() print "Busqueda por Ramificacion y Acotacion con subestimacion: ",search.ram_acot_sub_graph_search(an).path() print "\nTrayecto N-O:" print "Busqueda en anchura: ",search.breadth_first_graph_search(no).path() print "Busqueda en profundidad: ",search.depth_first_graph_search(no).path() print "Busqueda por Ramificacion y Acotacion: ",search.ram_acot_graph_search(no).path() print "Busqueda por Ramificacion y Acotacion con subestimacion: ",search.ram_acot_sub_graph_search(no).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_search(ab).path() #print search.astar_search(ab).path()
print('goal checks: ', problem.instance.goal_tests) print('states explored: ', problem.instance.succs) print('actions executed: ', problem.instance.states) plot_tile_map( fix_tile_map_after_solution(problem.tiles, problem.start, problem.goal, solution), False) plt.savefig('./img/{0}/{0}__solution.png'.format(alg)) plt.cla() # ======= DFS ====== alg = "DFS" problem = RobotProblemFactory(Robot, alg, width, height, start, goal, walls) e, solution = elapsed(lambda: depth_first_graph_search(problem.instance)) print('Robot ', alg, ' found solution in ', e, 's : ', solution.path()) print('path length: ', len(solution.path())) print('path cost: ', solution.path_cost) print('goal checks: ', problem.instance.goal_tests) print('states explored: ', problem.instance.succs) print('actions executed: ', problem.instance.states) plot_tile_map( fix_tile_map_after_solution(problem.tiles, problem.start, problem.goal, solution), False) plt.savefig('./img/{0}/{0}__solution.png'.format(alg)) plt.cla() # ======= A* + H1 (Manhattan Distance) ====== alg = "A_star_manhattan"
# Search methods import search print("Prueba 1 de A a B") ab = search.GPSProblem('A', 'B', search.romania) print("Breadth_First:", search.breadth_first_graph_search(ab).path()) print("Depth_First: ", search.depth_first_graph_search(ab).path()) print("Recorrido y profundidad: ", search.recorrido_y_profundidad(ab).path()) print("Recorrido y profundidad con subestimación: ", search.recorrido_y_profundidad_subestimacion(ab).path()) # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450 print("\nPrueba 2 de I a B") ib = search.GPSProblem('I', 'B', search.romania) print("Breadth_First:", search.breadth_first_graph_search(ib).path()) print("Depth_First: ", search.depth_first_graph_search(ib).path()) print("Recorrido y profundidad: ", search.recorrido_y_profundidad(ib).path()) print("Recorrido y profundidad con subestimación: ", search.recorrido_y_profundidad_subestimacion(ib).path()) print("\nPrueba 3 de C a B") cb = search.GPSProblem('C', 'B', search.romania) print("Breadth_First:", search.breadth_first_graph_search(cb).path()) print("Depth_First: ", search.depth_first_graph_search(cb).path()) print("Recorrido y profundidad: ", search.recorrido_y_profundidad(cb).path()) print("Recorrido y profundidad con subestimación: ",
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) fr = search.GPSProblem('F', 'R', search.romania) co = search.GPSProblem('C', 'O', search.romania) print("||||||||||||||||||||-De B a A-||||||||||||||||||||") print("-------Busqueda no informada por anchura---------") print search.breadth_first_graph_search(ab).path() print("-------Busqueda no informada por profundidad---------") print search.depth_first_graph_search(ab).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_search(ab).path() print("-------Busqueda no informada por coste de camino---------") print search.search_fring(ab).path() print("-------Busqueda informada---------") print search.search_fring_h(ab).path() print("||||||||||||||||||||-De R a F-||||||||||||||||||||") print("-------Busqueda no informada por anchura---------") print search.breadth_first_graph_search(fr).path() print("-------Busqueda no informada por profundidad---------") print search.depth_first_graph_search(fr).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_search(ab).path() print("-------Busqueda no informada por coste de camino---------") print search.search_fring(fr).path()
def printAllSolutions(problem): printSolution("Breadth First", search.breadth_first_graph_search(problem)) printSolution("Depth First", search.depth_first_graph_search(problem)) printSolution("Branch and bound", search.branch_and_bound_search(problem)) printSolution("Branch and bound with subestimation", search.branch_and_bound_subestimation_search(problem))
# Search methods import search routes = [['A', 'O', 'T', 'A', 'V'], ['B', 'S', 'N', 'E', 'L']] for i in range(0, 5): currentProblem = search.GPSProblem(routes[0][i], routes[1][i], search.romania) print ("%s -> %s method tests: " % (routes[0][i], routes[1][i])) print("Anchura: ", search.breadth_first_graph_search(currentProblem).path()) print("Profundidad: ", search.depth_first_graph_search(currentProblem).path()) print ("B&B: ", search.branch_and_bound_tree_search(currentProblem).path()) print ("B&B Heuristic: ", search.branch_and_bound_with_underestimation_tree_search(currentProblem).path()) print ("") #print search.iterative_deepening_search(currentProblem).path() #print search.depth_limited_search(currentProblem).path() #print search.astar_search(ab).path() # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
# Search methods import search print('#' * 15) print('# A - B #') print('#' * 15) ab = search.GPSProblem('A', 'B', search.romania) print("Busqueda en anchura") finalNode = search.breadth_first_graph_search(ab) print('{} {}'.format(finalNode.path(), finalNode.path_cost)) print('-' * 15) print("Busqueda en profundid") finalNode = search.depth_first_graph_search(ab) print('{} {}'.format(finalNode.path(), finalNode.path_cost)) print('-' * 15) print("Branch and Bound") finalNode = search.bnb(ab) print('{} {}'.format(finalNode.path(), finalNode.path_cost)) print('-' * 15) print("Branch and Bound con subestimacion") finalNode = search.bnb_subestimation(ab) print('{} {}'.format(finalNode.path(), finalNode.path_cost)) print('-' * 15) print('#' * 15) print('# T - R #') print('#' * 15) tr = search.GPSProblem('T', 'R', search.romania) print("Busqueda en anchura") finalNode = search.breadth_first_graph_search(tr)
import search mi_problema = search.GPSProblem('A', 'B', search.romania) print search.breadth_first_graph_search(mi_problema) print search.depth_first_graph_search(mi_problema)
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print(" _______ANCHURA______") print(search.breadth_first_graph_search(ab).path()) print() print("________PROFUNDIDAD___") print(search.depth_first_graph_search(ab).path()) print() print("________RAMIFICACIÓN Y ACOTACIÓN______") print(search.branchAndBound(ab).path()) print() print("______RAMIFICACIÓN Y ACOTACIÓN CON SUBESTIMACIÓN____") print(search.branchAndBoundSubestimation(ab).path()) """ Result: [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450 """ print("\nTraza del camino AC") ac = search.GPSProblem('A', 'C', search.romania) print(search.breadth_first_graph_search(ac).path()) ## anchura print(search.depth_first_graph_search(ac).path()) ## profundidad print(search.branchAndBound(ac).path()) print(search.branchAndBoundSubestimation(ac).path()) # Coste+h print("\nTraza del camino GZ")
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print("A - B") print("Breadth first") print(search.breadth_first_graph_search(ab)) print("Depth first") print(search.depth_first_graph_search(ab)) print("Branch and Bound") print(search.bab(ab)) print("Branch and Bound (subestimation)") print(search.ras(ab)) print() oe = search.GPSProblem('O', 'E', search.romania) print("O - E") print("Breadth first") print(search.breadth_first_graph_search(oe)) print("Depth first") print(search.depth_first_graph_search(oe)) print("Branch and Bound") print(search.bab(oe)) print("Branch and Bound (subestimation)") print(search.ras(oe)) print() pz = search.GPSProblem('P', 'Z', search.romania) print("P - Z") print("Breadth first")
# Search methods import search ab = search.GPSProblem('A', 'G', search.romania) print("Breadth first graph search result\n", "Visited Nodes:", search.breadth_first_graph_search(ab)[1], "\n", search.breadth_first_graph_search(ab)[0].path(), "\n") print("Depth first graph search result\n", "Visited Nodes:", search.depth_first_graph_search(ab)[1], "\n", search.depth_first_graph_search(ab)[0].path(), "\n") print("Branch and bound result\n", "Visited Nodes:", search.branch_and_bounding(ab)[1], "\n", search.branch_and_bounding(ab)[0].path(), "\n") print("Heuristic branch and bound result\n", "Visited Nodes:", search.heuristic_branch_and_bound(ab)[1], "\n", search.heuristic_branch_and_bound(ab)[0].path(), "\n") # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
# Search methods import search ab = search.GPSProblem('A', 'B', search.romania) print(search.breadth_first_graph_search(ab).path()) print(search.depth_first_graph_search(ab).path()) print(search.cost_graph_search(ab).path()) #Nuevo orden por path_cost print(search.heuristica_graph_search(ab).path()) # Result: # [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418 # [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
return True return False def checkRowsOf4(self, a, b, c, d, completeCheck): if (a == 0 or b == 0 or c == 0 or d == 0): if completeCheck: return False else: return True if a + b + c + d == 38: return True return False def checkRowsOf5(self, a, b, c, d, e, completeCheck): if (a == 0 or b == 0 or c == 0 or d == 0 or e == 0): if completeCheck: return False else: return True if a + b + c + d + e == 38: return True return False nq1 = MagicHexagonProblem(); start_time = time.time() print(search.depth_first_graph_search(nq1).solution()) print("--- %s seconds ---" % (time.time() - start_time))