def test_bidirectional_breadth_first_search_vs_breadth_first_graph_search(): eight_puzzle = EightPuzzle(initial=instance_two, goal=goal) eight_puzzle_reversed = EightPuzzle(initial=goal, goal=instance_two) ins_problem = InstrumentedProblem(eight_puzzle) res = instrumented_bidirectional_breadth_first_search(eight_puzzle, eight_puzzle_reversed, True) breadth_first_graph_search(ins_problem) assert (res[1]) <= ins_problem.explored
def test_solve_comparison(): problem_file = "./warehouses/warehouse_35.txt" wh = Warehouse() wh.read_warehouse_file(problem_file) print(wh) bfs = True elem = True macro = True if (bfs): sp = SokobanPuzzle(wh) start = time.time() answer = breadth_first_graph_search(sp).solution() end = time.time() print("BFS Elem took:", end - start, "secs") print(answer) if (elem): start = time.time() answer = solve_sokoban_elem(wh) end = time.time() print("A* elem took:", end - start, "secs") print(answer) if (macro): start = time.time() answer = solve_sokoban_macro(wh) end = time.time() print("A* macro took:", end - start, "secs") print(answer)
def solve_sokoban_elem(warehouse): ''' This function should solve using elementary actions the puzzle defined in a file. @param warehouse: a valid Warehouse object @return A list of strings. If puzzle cannot be solved return ['Impossible'] If a solution was found, return a list of elementary actions that solves the given puzzle coded with 'Left', 'Right', 'Up', 'Down' For example, ['Left', 'Down', Down','Right', 'Up', 'Down'] If the puzzle is already in a goal state, simply return [] ''' puzzle = SokobanPuzzle(warehouse) puzzleGoalState = warehouse.copy() puzzleSolution = breadth_first_graph_search(puzzle) #puzzleSolution = depth_first_graph_search(puzzle) #puzzleSolution = astar_graph_search(puzzle, get_Heuristic) step_move_solution = [] if (puzzle.goal_test(puzzleGoalState)): return step_move_solution elif (puzzleSolution is None or check_action_seq( warehouse, find_action(puzzleSolution)) is "Failure"): return ['Impossible'] else: return find_action(puzzleSolution)
def test_astar_gaschnig_vs_breadth_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 = breadth_first_graph_search(eight_problem1) assert res.state == goal assert res1.state == goal assert eight_problem.explored < eight_problem1.explored
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 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(): '''run the game for each starting position. print solutions for each position''' for start_position in range(15): # setup game game = PegGame(start_position) #print('initial board',game.board) #solved = search.depth_first_graph_search(game) solved = search.breadth_first_graph_search(game) print('\n***************starting position %i******************' % start_position) print('number of solutions: %i\n' % len(solved)) for index, solution in enumerate(solved): index = index + 1 print('solution %i' % index) for action in solution.solution(): print(action) print('\n')
def mainBrain(inistate, goal): #location=find_location(inistate) #print(location) problem = EightPuzzle(inistate, goal) #print(problem[inistate]) #print("---") #goalnode = search.breadth_first_graph_search(problem) goalnode = search.breadth_first_graph_search(problem) #goalnode = search.depth_first_graph_search(problem) #goalnode = search.iterative_deepening_search(problem) # sammud (tegevused, käigud) algolekust lõppolekuni print(goalnode.solution()) print(goalnode.path()) #print(len(goalnode.path())) #print("aa") #print(len(goalnode.solution())) #print("aa") print("----------------------") search.compare_searchers([problem], ["Strategy", "firstState"], searchers=[search.breadth_first_graph_search]) #pakun esimene number tähendab mitmes neuroni ringi. 3 tähendab kokku arvutust
def solveEquation(equation): mp = mathProblem(equation) ap = AlgebraPlan(mp) bfs = search.breadth_first_graph_search(ap) plan = [] for s in bfs.solution(): step = str(s) if 'AddVar' in step: value = step.split('(')[1].rstrip(')') if '-' in value: plan.append('add ' + value.lstrip('-') + 'x') else: plan.append('add -' + value + 'x') elif 'AddConst' in step: value = step.split('(')[1].rstrip(')') if '-' in value: plan.append('add ' + value.lstrip('-')) else: plan.append('add -' + value) elif 'CombVarLeft' in step: terms = s.split('(')[1].rstrip(')').split(', ') result = int(terms[0]) + int(terms[1]) if result >= 0: plan.append('combine LHS variable terms and get positive') elif result < 0: plan.append('combine LHS variable terms and get negative') elif 'CombVarRight' in step: terms = s.split('(')[1].rstrip(')').split(', ') result = int(terms[0]) + int(terms[1]) if result >= 0: plan.append('combine RHS variable terms and get positive') elif result < 0: plan.append('combine RHS variable terms and get negative') elif 'CombConstLeft' in step: plan.append('combine LHS constant terms') elif 'CombConstRight' in step: plan.append('combine RHS constant terms') elif 'Divide' in step: value = step.split('(')[1].rstrip(')') plan.append('divide ' + value) return plan
def can_go_there(warehouse, dst): ''' Determine whether the worker can walk to the cell dst=(row,column) without pushing any box. @param warehouse: a valid Warehouse object @return True if the worker can walk to cell dst=(row,column) without pushing any box False otherwise ''' #checks if the action is valid dst = (dst[1], dst[0]) problem = SokobanCanGoPuzzle(dst, warehouse) node = search.breadth_first_graph_search(problem) if node == None: return False else: warehouse.worker = problem.goal return True
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"]))
def solve_sokoban_elem(warehouse): ''' This function should solve using A* algorithm and elementary actions the puzzle defined in the parameter 'warehouse'. In this scenario, the cost of all (elementary) actions is one unit. @param warehouse: a valid Warehouse object @return If puzzle cannot be solved return the string 'Impossible' If a solution was found, return a list of elementary actions that solves the given puzzle coded with 'Left', 'Right', 'Up', 'Down' For example, ['Left', 'Down', Down','Right', 'Up', 'Down'] If the puzzle is already in a goal state, simply return [] ''' puzzle = SokobanPuzzle(warehouse) puzzleGoalState = warehouse.copy() puzzleSolution = search.breadth_first_graph_search(puzzle) #puzzleSolution = depth_first_graph_search(puzzle) #puzzleSolution = astar_graph_search(puzzle, get_Heuristic) step_move_solution = [] step_move = [] for node in puzzleSolution.path(): step_move.append(node.action) action_seq = step_move[1:] if (puzzle.goal_test(puzzleGoalState)): return step_move_solution elif (puzzleSolution is None or check_elem_action_seq(warehouse, action_seq) == 'Impossible'): return 'Impossible' else: return action_seq
romania_map.locations = dict( Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288), Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449), Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506), Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537), Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410), Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350), Vaslui=(509, 444), Zerind=(108, 531)) romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) #romania map jalur efektif dari state awal ke state akhir romania_locations = romania_map.locations #mau pake bfs a=[node.state for node in breadth_first_graph_search(romania_problem).path()] print(a) #mau pake dfs a=[node.state for node in depth_first_graph_search(romania_problem).path()] print(a) #mau greedy a=[node.state for node in greedy_best_first_graph_search(romania_problem,lambda node: node.path_cost).path()] print(a) #kalo inform kita tau jarak pasti di petanya #kalo uninform hanyak diketahui jarak antar kota
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)
# STACK: 22 (tras quitar la lista cerrada hace un bucle infinito) cf = search.GPSProblem('C', 'F', search.romania) result = [0] * 20 result[0] = search.busqueda_ramificacion_subestimacion(ab) result[1] = search.busqueda_ramificacion_subestimacion(cf) result[2] = search.busqueda_ramificacion_subestimacion(sl) result[3] = search.busqueda_ramificacion_subestimacion(og) result[4] = search.busqueda_ramificacion_costes(ab) result[5] = search.busqueda_ramificacion_costes(cf) result[6] = search.busqueda_ramificacion_costes(sl) result[7] = search.busqueda_ramificacion_costes(og) result[8] = search.breadth_first_graph_search(ab) result[9] = search.breadth_first_graph_search(cf) result[10] = search.breadth_first_graph_search(sl) result[11] = search.breadth_first_graph_search(og) result[12] = search.busqueda_stack(ab) result[13] = search.busqueda_stack(cf) result[14] = search.busqueda_stack(sl) result[15] = search.busqueda_stack(og) print "" print " --------------------------------------------- " print " ------------------> TABLA <------------------ " print " --------------------------------------------- " print ""
# 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 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
# Search methods import search 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)
def solveEquation(equation): initExprL = "" initExpr = "" preCondDivR = "" preCondCombAdd = "" preCondDivL = "" preCondAdd = "" combineConstExprLeft = "" combineVarsExprLeftPos = "" combineVarsExprLeftNeg = "" combineConstExprRight = "" combineVarsExprLeftPos = "" combineVarsExprLeftNeg = "" values = equation.split("=") leftSide = values[0] rightSide = values[1] for terms in leftSide: if terms == "+": termVals = leftSide.split("+") # IF FIRST VALUE IN EQUATION ON LEFT SIDE IS X if termVals[0].__contains__("x"): xVal = termVals[0] coef1 = xVal.split("x") initExpr = "Coef(" + coef1[0] + ", left)" # IF SECOND VALUE AFTER + ALSO CONTAINS AN X (3x+2X) if termVals[1].__contains__("x"): xVal = termVals[1] coef2 = xVal.split("x") initExpr += " & Coef(" + coef2[0] + ", left)" combinedCoef = int(coef1[0]) + int(coef2[0]) #PRECONDITION FOR COMBINING VARIABLES ON LEFT if (combinedCoef > 0): combineVarsExprLeftPos = "CombineVarsLeftPos(" + coef1[ 0] + ", " + coef2[0] + ")" initExpr += " & " + combineVarsExprLeftPos else: combineVarsExprLeftNeg = "CombineVarsLeftNeg(" + coef1[ 0] + ", " + coef2[0] + ")" initExpr += " & " + combineVarsExprLeftNeg #PRECONDITION FOR DIVIDING IS THAT THERE IS A COEFFICIENT ON THE LEFT preCondDivL = "Coef(" + str(combinedCoef) + ", left)" divCond = combinedCoef addCond = 0 # IF SECOND VALUE AFTER + IS A CONSTANT (3x+2) else: const = termVals[1] preCondDivL = "Coef(" + coef1[0] + ", left)" divCond = coef1[0] preCondAdd = "Const(" + const + ", left)" addCond = const initExpr += " & Const(" + const + ", left)" #IF FIRST TERM IS A CONST else: const1 = termVals[0] initExpr = "Const(" + const1 + ", left)" #SECOND TERM IS VARIABLE -- (3+2x) if termVals[1].__contains__("x"): coef = termVals[1].split("x") preCondAdd = "Const(" + const1 + ", left)" addCond = const1 preCondDivL = "Coef(" + coef[0] + ", left)" divCond = coef[0] initExpr += " & Coef(" + coef[0] + ", left)" #SECOND TERM IS ALSO A CONST (3+2) else: const2 = termVals[1] initExpr += " & Const(" + const2 + ", left)" #PRECONDITION FOR COMBINING CONST ON LEFT combineConstExprLeft = "CombineConstExprLeft(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) preCondAdd = "Const(" + const1 + ", left)" addCond = const1 preCondCombAdd = "Const(" + str(combinedConst) + ", left)" combineCondAdd = combinedConst initExpr += " & " + combineConstExprLeft elif terms == "-" and terms != leftSide[0][0]: termVals = leftSide.split("-") # IF FIRST VALUE IN EQUATION ON LEFT SIDE IS A NEG VAR if termVals[0] == "": termVals[0] += "-" #IF FIRST TERM IS A NEG VARIABLE if termVals[1].__contains__("x"): xVal = termVals[1].split("x") coef1 = termVals[0] + xVal[0] initExpr = "Coef(" + coef1 + ", left)" #IF SECOND TERM IS A VARIABLE if termVals[2].__contains__("x"): xVal = termVals[2] co = xVal.split("x") coef2 = "-" + co[0] initExpr += " & Coef(" + coef2 + ", left)" combinedCoef = int(coef1) + int(coef2) #COMBINE THE VARIABLES ON LEFT SIDE if (combinedCoef > 0): combineVarsExprLeftPos = "CombineVarsLeftPos(" + coef1 + ", " + coef2 + ")" initExpr += " & " + combineVarsExprLeftPos else: combineVarsExprLeftNeg = "CombineVarsLeftNeg(" + coef1 + ", " + coef2 + ")" initExpr += " & " + combineVarsExprLeftNeg preCondDivL = "Coef(" + str(combinedCoef) + ", left" divCond = combinedCoef # IF SECOND TERM IS A CONSTANT else: const = "-" + termVals[2] preCondDivL = "Coef(" + coef1 + ", left)" divCond = coef1 preCondAdd = "Const(" + const + ", left)" addCond = const initExpr += " & Const(" + const + ", left)" # IF FIRST TERM IS A NEG CONSTANT else: const1 = "-" + termVals[1] initExpr = "Const(" + const1 + ", left)" # IF SECOND TERM IS A VARIABLE if termVals[2].__contains__("x"): xVal = termVals[2].split("x") coef = "-" + xVal[0] initExpr += " & Coef(" + coef + ", left)" preCondDivL = "Coef(" + coef + ", left" divCond = coef preCondAdd = "Const(" + const1 + ", left" addCond = const1 # IF SECOND TERM IS ALSO A NEGATIVE CONSTANT else: const2 = "-" + termVals[2] initExpr += " & Const(" + const2 + ", left)" combineConstExprLeft = "CombineConstExprLeft(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) combineCondAdd = combinedConst preCondAdd = "Const(" + str(combinedConst) + ", left)" initExpr += " & " + combineConstExprLeft else: if termVals[0].__contains__("x"): xVal = termVals[0].split("x") coef1 = termVals[1] + xVal[0] initExpr = "Coef(" + coef1 + ", left)" # IF SECOND TERM IS A VARIABLE if termVals[1].__contains__("x"): xVal = termVals[1] co = xVal.split("x") coef2 = "-" + co[0] initExpr += " & Coef(" + coef2 + ", left)" combinedCoef = int(coef1) + int(coef2) # COMBINE THE VARIABLES ON LEFT SIDE if (combinedCoef > 0): combineVarsExprLeftPos = "CombineVarsLeftPos(" + coef1 + ", " + coef2 + ")" initExpr += " & " + combineVarsExprLeftPos else: combineVarsExprLeftNeg = "CombineVarsLeftNeg(" + coef1 + ", " + coef2 + ")" initExpr += " & " + combineVarsExprLeftNeg preCondDivL = "Coef(" + str(combinedCoef) + ", left" # IF SECOND TERM IS A CONSTANT else: const = "-" + termVals[1] preCondDivL = "Coef(" + coef1 + ", left)" divCond = coef1 preCondAdd = "Const(" + const + ", left)" addCond = const initExpr += " & Const(" + const + ", left)" # IF FIRST TERM IS A NEG CONSTANT else: const1 = "-" + termVals[0] initExpr = "Const(" + const1 + ", left)" # IF SECOND TERM IS A VARIABLE if termVals[1].__contains__("x"): xVal = terms[1].split("x") coef = "-" + xVal[0] initExpr += " & Coef(" + xVal[0] + ", left)" preCondDivL = "Coef(" + xVal[0] + ", left" divCond = xVal[0] preCondAdd = "Const(" + const1 + ", left" addCond = const1 # IF SECOND TERM IS ALSO A NEGATIVE CONSTANT else: const2 = "-" + termVals[1] initExpr = " & Const(" + const2 + ", left)" combineConstExprLeft = "CombineConstExprLeft(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) preCondAdd = "Const(" + str(combinedConst) + ", left)" initExpr += " & " + combineConstExprLeft else: if len(leftSide) < 4: if leftSide.__contains__("x"): xVal = leftSide.split("x") initExpr = "Coef(" + xVal[0] + ", left) & Const(0, left)" preCondDivL = "Coef(" + xVal[0] + ", left)" preCondAdd = "Const(0, left)" addCond = str(0) divCond = str(xVal[0]) elif leftSide == "x": initExpr = "Coef(1, left)" else: initExpr = "Const(" + leftSide + ", left)" preCondAdd = "Const(" + leftSide + ", left)" for terms in rightSide: if terms == "+": termVals = rightSide.split("+") # IF FIRST VALUE IN EQUATION ON LEFT SIDE IS X if termVals[0].__contains__("x"): xVal = termVals[0] coef1 = xVal.split("x") initExprR = "Coef(" + coef1[0] + ", right)" # IF SECOND VALUE AFTER + ALSO CONTAINS AN X (3x+2X) if termVals[1].__contains__("x"): xVal = termVals[1] coef2 = xVal.split("x") initExpr += " & Coef(" + coef2[0] + ", right)" combinedCoef = int(coef1[0]) + int(coef2[0]) #PRECONDITION FOR COMBINING VARIABLES ON LEFT if (combinedCoef > 0): combineVarsExprRightPos = "CombineVarsRightPos(" + coef1[ 0] + ", " + coef2[0] + ")" initExprR += " & " + combineVarsExprRightPos else: combineVarsExprRightNeg = "CombineVarsRightNeg(" + coef1[ 0] + ", " + coef2[0] + ")" initExprR += " & " + combineVarsExprRightNeg #PRECONDITION FOR DIVIDING IS THAT THERE IS A COEFFICIENT ON THE LEFT preCondDivL = "Coef(" + str(combinedCoef) + ", right)" divCond = combinedCoef # IF SECOND VALUE AFTER + IS A CONSTANT (3x+2) else: const = termVals[1] preCondDivL = "Coef(" + coef1[0] + ", right)" divCond = coef1[0] preCondAdd = "Const(" + const + ", right)" #addCond = const initExprR += " & Const(" + const + ", right)" #IF FIRST TERM IS A CONST else: const1 = termVals[0] initExprR = "Const(" + const1 + ", right)" #SECOND TERM IS VARIABLE -- (3+2x) if termVals[1].__contains__("x"): coef = termVals[1].split("x") preCondAdd = "Const(" + const1 + ", right)" #addCond = const1 preCondDivL = "Coef(" + coef[0] + ", right)" divCond = coef[0] initExprR += " & Coef(" + coef[0] + ", right)" #SECOND TERM IS ALSO A CONST (3+2) else: const2 = termVals[1] initExprR += " & Const(" + const2 + ", right)" #PRECONDITION FOR COMBINING CONST ON LEFT combineConstExprRight = "CombineConstExprRight(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) preCondAdd = "Const(" + const1 + ", right)" #addCond = const1 preCondCombAdd = "Const(" + str(combinedConst) + ", right)" combineCondAdd = combinedConst initExprR += " & " + combineConstExprLeft elif terms == "-": termVals = rightSide.split("-") # IF FIRST VALUE IN EQUATION ON LEFT SIDE IS A NEG VAR if termVals[0] == "": termVals[0] += "-" #IF FIRST TERM IS A NEG VARIABLE if termVals[1].__contains__("x"): xVal = termVals[1].split("x") coef1 = termVals[0] + xVal[0] initExprR = "Coef(" + coef1 + ", right)" #IF SECOND TERM IS A VARIABLE if termVals[2].__contains__("x"): xVal = termVals[2] co = xVal.split("x") coef2 = "-" + co[0] initExprR += " & Coef(" + coef2 + ", right)" combinedCoef = int(coef1) + int(coef2) #COMBINE THE VARIABLES ON LEFT SIDE if (combinedCoef > 0): combineVarsExprRightPos = "CombineVarsRightPos(" + coef1 + ", " + coef2 + ")" initExprR += " & " + combineVarsExprRightPos else: combineVarsExprRightNeg = "CombineVarsRightNeg(" + coef1 + ", " + coef2 + ")" initExprR += " & " + combineVarsExprRightNeg preCondDivL = "Coef(" + str(combinedCoef) + ", right)" divCond = combinedCoef # IF SECOND TERM IS A CONSTANT else: const = "-" + termVals[2] preCondDivL = "Coef(" + coef1 + ", right)" divCond = coef1 preCondAdd = "Const(" + const + ", right)" #addCond = const initExprR += " & Const(" + const + ", right)" # IF FIRST TERM IS A NEG CONSTANT else: const1 = "-" + termVals[1] initExprR = "Const(" + const1 + ", right)" # IF SECOND TERM IS A VARIABLE if termVals[2].__contains__("x"): xVal = termVals[2].split("x") coef = "-" + xVal[0] initExprR += " & Coef(" + coef + ", right)" preCondDivL = "Coef(" + coef + ", right)" divCond = coef preCondAdd = "Const(" + const1 + ", right)" #addCond = const1 # IF SECOND TERM IS ALSO A NEGATIVE CONSTANT else: const2 = "-" + termVals[2] initExprR += " & Const(" + const2 + ", right)" combineConstExprRight = "CombineConstExprRight(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) combineCondAdd = combinedConst preCondAdd = "Const(" + str(combinedConst) + ", right)" initExprR += " & " + combineConstExprRight else: if termVals[0].__contains__("x"): xVal = termVals[0].split("x") coef1 = termVals[1] + xVal[0] initExprR = "Coef(" + coef1 + ", right)" # IF SECOND TERM IS A VARIABLE if termVals[1].__contains__("x"): xVal = termVals[1] co = xVal.split("x") coef2 = "-" + co[0] initExprR += " & Coef(" + coef2 + ", right)" combinedCoef = int(coef1) + int(coef2) # COMBINE THE VARIABLES ON LEFT SIDE if (combinedCoef > 0): combineVarsExprRightPos = "CombineVarsRightPos(" + coef1 + ", " + coef2 + ")" initExprR += " & " + combineVarsExprRightPos else: combineVarsExprRightNeg = "CombineVarsRightNeg(" + coef1 + ", " + coef2 + ")" initExprR += " & " + combineVarsExprRightNeg preCondDivL = "Coef(" + str(combinedCoef) + ", right)" # IF SECOND TERM IS A CONSTANT else: const = "-" + termVals[1] preCondDivL = "Coef(" + coef1 + ", right)" divCond = coef1 preCondAdd = "Const(" + const + ", right)" #addCond = const initExprR += " & Const(" + const + ", right)" # IF FIRST TERM IS A NEG CONSTANT else: const1 = "-" + termVals[0] initExprR = "Const(" + const1 + ", right)" # IF SECOND TERM IS A VARIABLE if termVals[1].__contains__("x"): xVal = terms[1].split("x") coef = "-" + xVal[0] initExprR += " & Coef(" + xVal[0] + ", right)" preCondDivL = "Coef(" + xVal[0] + ", right)" divCond = xVal[0] preCondAdd = "Const(" + const1 + ", right)" #addCond = const1 # IF SECOND TERM IS ALSO A NEGATIVE CONSTANT else: const2 = "-" + termVals[1] initExprR = " & Const(" + const2 + ", right)" combineConstExprRight = "CombineConstExprRight(" + const1 + ", " + const2 + ")" combinedConst = int(const1) + int(const2) preCondAdd = "Const(" + str(combinedConst) + ", right)" initExprR += " & " + combineConstExprRight else: if len(rightSide) < 3: if rightSide.__contains__("x"): xVal = rightSide.split("x") initExprR = "Coef(" + xVal[0] + ", right)" preCondDivL = "Coef(" + str(xVal[0]) + ", right)" divCond = str(xVal[0]) elif rightSide == "x": initExprR = "Coef(1, right)" else: initExprR = "Const(" + rightSide + ", right)" preCondAdd = "Const(" + str(rightSide) + ", right)" #addCond = rightSide divCond = str(1) addCond = str(0) # print(preCondAdd) # print(preCondDivL) # print(addCond) # print(divCond) initExpr += " & " + initExprR initExpr += " & ~Coef(1, left)" # print(initExpr) plan_prob = planning.PlanningProblem( initial=initExpr, goals='Coef(1, left)', actions=[ planning.Action('Add(x)', precond=preCondAdd + " & " + preCondDivL, effect="~" + preCondAdd, domain="addCond(x)"), planning.Action('AddVar(x)', precond="Coef(3, left) & Coef(3, right)", effect="~Coef(3, left) & ~Coef(3, right)", domain="addVarCond(x)"), planning.Action('Divide(x)', precond=preCondDivL + " & ~Coef(1, left) " + " & ~" + preCondAdd, effect="~" + preCondDivL + " & Coef(1, left)", domain="divCond(x)") ], # planning.Action('CombineConst(x, y)', # precond= combineConstExprLeft, # effect= "~" + combineConstExprLeft, # domain='combineCond(x, y)'), # planning.Action('CombineLHSVars2Pos(x, y)', # precond=combineVarsExprLeftPos, # effect="~" + combineVarsExprLeftPos), # planning.Action("CombineLHSVars2Neg(x, y)", # precond=combineVarsExprLeftNeg, # effect="~" + combineVarsExprLeftNeg), # planning.Action("CombineRHSVars2Pos(x, y)", # precond=combineVarsExprRightPos, # effect="~" + combineVarsExprRightPos), # planning.Action("CombineRHSVars2Neg(x, y)", # precond=combineVarsExprRightNeg, # effect="~" + combineVarsExprRightNeg)], domain='addCond(' + addCond + ') & divCond(' + divCond + ') & addVarCond(3)') planning_prob = planning.ForwardPlan(plan_prob) # print(planning_prob.initial) # initial_actions = planning_prob.actions(planning_prob.initial) # print(initial_actions) # state2 = planning_prob.result(planning_prob.initial, initial_actions[0]) # print(planning_prob.actions(state2)) solution = search.breadth_first_graph_search(planning_prob) plan = [] parentNode = solution.parent if combineConstExprLeft: plan.append("combine LHS constant terms") if combineVarsExprLeftNeg: plan.append("combine LHS variable terms to neg") if combineVarsExprLeftPos: plan.append("combine LHS variable terms to pos") if combineConstExprRight: plan.append("combine RHS constant terms") # if combineVarsExprRightNeg: # plan.append("combine RHS variable terms to neg") # if combineVarsExprRightPos: # plan.append("combine RHS variable terms to pos") while (parentNode): #print(solution.parent.action) parentNode = parentNode.parent.parent plan.append(str(solution.parent.action)) plan.append(str(solution.action)) #print(solution.action) #print(plan) return plan
# 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()
return c + 1 # uus cost peale ühe sammu tegemist def get_action_specific_neighbour_index(action, state, zero_place): row_length = int(math.sqrt(len(state))) if action == Constants.up: return zero_place - row_length if action == Constants.down: return zero_place + row_length if action == Constants.right: return zero_place + 1 return zero_place - 1 problem = EightPuzzle(Constants.begin, Constants.Goal) goalnode = search.breadth_first_graph_search(problem) # sammud (tegevused, käigud) algolekust lõppolekuni print(goalnode.solution()) # olekud algolekust lõppolekuni print("path", goalnode.path()) print("path_len", len(goalnode.path())) problem = EightPuzzle(Constants.begin, Constants.Goal) goalnode = search.iterative_deepening_search(problem) # sammud (tegevused, käigud) algolekust lõppolekuni print(goalnode.solution()) # olekud algolekust lõppolekuni print("path", goalnode.path()) print("path_len", len(goalnode.path())) search.compare_searchers([problem], ["name", "result"],
acts.append(State(f2, "4")) if -1 < f3 and (f3 < f1 or f1 == -1): acts.append(State(f3, "1")) if -1 < f3 and (f3 < f2 or f2 == -1): acts.append(State(f3, "2")) if -1 < f3 and (f3 < f4 or f4 == -1): acts.append(State(f3, "4")) if -1 < f4 and (f4 < f1 or f1 == -1): acts.append(State(f4, "1")) if -1 < f4 and (f4 < f2 or f2 == -1): acts.append(State(f4, "2")) if -1 < f4 and (f4 < f3 or f3 == -1): acts.append(State(f4, "3")) return acts def result(self, state, action): """we change the number denoting rod""" disk, char = action return state[0:disk] + char + state[disk + 1:] def value(self, state): """we have no good heuristics""" return self.size - state.count("2") if __name__ == "__main__": hanoi = Hanoi(4) print(breadth_first_graph_search(hanoi).solution())
# 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
print('Robot ', alg, ' found solution in ', e, 's : ', solution.path()) print('path length: ', len(solution.path())) # ======= BFS ====== alg = "BFS" problem = RobotProblemFactory(Robot, alg, width, height, start, goal, walls) plot_tile_map( fix_tile_map_after_solution(problem.tiles, problem.start, problem.goal, None, None, None), False) plt.savefig('./img/{0}.png'.format("map")) plt.cla() e, solution = elapsed(lambda: breadth_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() # ======= DFS ====== alg = "DFS"
# Search methods 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:
def solve(): missionaries_and_cannibals = MissionariesAndCannibals((0, 0, 3, 3, 1)) return breadth_first_graph_search(missionaries_and_cannibals).solution()
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)
# Week 2 import search ab = search.GPSProblem('A', 'B', search.romania) print search.astar_search(ab).path() print search.breadth_first_graph_search(ab).path() #print search.depth_first_graph_search(ab).path() #print search.iterative_deepening_search(ab).path() #print search.depth_limited_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 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
frutas='f' confites='c' masita='m' estado_inicial = ( (dulce,dulce,dulce), (frutas,frutas,frutas), (confites,confites,confites)) estado_objetivo = (('x','x','x'), ('x','x','x'), ('x','x','x')) # Objetivo irreal, para explorar todo el grafo de posibilidades p1 = ProblemaDelMolde(estado_inicial, estado_objetivo) #Busqueda en amplitud r = breadth_first_graph_search(p1) print "Situacion 1. Pasteles ricos: " + str(p1.cantidadPastelesRicos) estado_inicial = ( (masita,dulce,dulce), (frutas,frutas,frutas), (confites,confites,confites)) estado_objetivo = (('x','x','x'), ('x','x','x'), ('x','x','x')) # Objetivo irreal, para explorar todo el grafo de posibilidades p2 = ProblemaDelMolde(estado_inicial, estado_objetivo) #Busqueda en amplitud