def main(): problem = EightPuzzleProblem('164870325', '012345678') print len(astar_search(problem).solution()) problem = EightPuzzleProblem('817456203', '012345678') print len(astar_search(problem).solution()) problem = EightPuzzleProblem('012345678', '000000000') print breadth_first_count_nodes_at_depth(problem)
def run_tsp(difficulty, file_name): t = TicToc() all_cities = my_utils.generate_cities_dict(difficulty) cities_map = cities_visualitation.CitiesMap(all_cities) tsp = TravelingSalesmanProblem(all_cities, (0, ), ()) t.tic() best_known_solution_value = 0.0 if difficulty == 'big': best_known_solution_value = params.big_best_known_solution elif difficulty == 'medium': best_known_solution_value = params.medium_best_known_solution elif difficulty == 'small': best_known_solution_value = params.small_best_known_solution tsp_result, msg = search.astar_search(tsp, best_known_solution_value, display=True) print(msg) t.toc() cities_list = cities_visualitation.get_normalized_cities_identification( tsp_result.state) cities_list_evaluation = (-1) * tsp.value(tsp_result.state) cities_map.show_map(list(tsp_result.state)) cities_map.save_plot(file_name) my_utils.save_results(file_name, cities_list_evaluation, cities_list, msg)
def plan_route(current, heading, goals, allowed): """ Given: current location: tuple (x,y) heading: integer representing direction gaals: list of one or more tuple goal-states allowed: list of locations that can be moved to ... return a list of actions (no time stamps!) that when executed will take the agent from the current location to one of (the closest) goal locations You will need to: (1) Construct a PlanRouteProblem that extends search.Problem (2) Pass the PlanRouteProblem as the argument to astar_search (search.astar_search(Problem)) to find the action sequence. Astar returns a node. You can call node.solution() to exract the list of actions. NOTE: represent a state as a triple: (x, y, heading) where heading will be an integer, as follows: 0='north', 1='west', 2='south', 3='east' """ # Ensure heading is a in integer form if isinstance(heading,str): heading = Explorer.heading_str_to_num[heading] if goals and allowed: prp = PlanRouteProblem((current[0], current[1], heading), goals, allowed) # NOTE: PlanRouteProblem will include a method h() that computes # the heuristic, so no need to provide here to astar_search() node = search.astar_search(prp) if node: return node.solution() # no route can be found, return empty list return []
def distance_shortest_path(self, loc1, loc2): 'calculate shortest path distance using A*' search_prob = AntsSearch(self, loc1, loc2) def manhattan_heurisitic(node): return self.distance_manhattan(node.state,loc2) return astar_search(search_prob, manhattan_heurisitic).depth
def find_discrete_line_points2(self, matching_image, p1, p2, show): if show: print("finding discrete line point between ", p1, p2) mp = MatchingProblem(p1, p2, matching_image) sol = astar_search(mp) path = self.path_states(sol) return path
def solveEquation(equation): sides = equation.split('=') # Initial parsing of equation for i in range(0, len(sides)): minuslocs = reversed( [pos for pos, char in enumerate(sides[i]) if char == '-']) for loc in minuslocs: if loc != 0: sides[i] = sides[i][0:loc] + "+" + sides[i][loc:] left = sides[0].split('+') right = sides[1].split('+') initial = '' # Creating initial clauses for term in left: if term.find('x') != -1: if term == 'x': initial += 'LHV(1) & ' elif term == '-x': initial += 'LHV(-1) & ' else: initial += 'LHV(' + term[0:len(term) - 1] + ') & ' else: initial += 'LHC(' + term + ') & ' for term in right: if term.find('x') != -1: if term == 'x': initial += 'RHV(1) & ' elif term == '-x': initial += 'RHV(-1) & ' else: initial += 'RHV(' + term[0:len(term) - 1] + ') & ' else: initial += 'RHC(' + term + ') & ' if initial.count('LHV') == 1 and initial.find('RHV') == -1: initial += 'LHV(0) & ' if initial.count('RHC') == 1 and initial.find('LHC') == -1: initial += 'RHC(0) & ' if initial.find('LHV') == -1 and initial.count('RHV') != 2: initial += 'LHV(0) & ' if initial.find('RHC') == -1 and initial.count('LHC') != 2: initial += 'RHC(0) & ' initial = initial[:len(initial) - 3] goal = 'LHV({0}) & RHC({0})'.format(-sys.maxsize - 1) # Specifying goal state actions = [action1, action2, action3, action4, action5, action6, action7] problem = planning.PlanningProblem(initial, goal, actions) forward_planning = planning.ForwardPlan(problem) plan = search.astar_search(forward_planning) action_plan = [] while plan.parent is not None: step = plan.action if 0 not in step.args: action_plan.insert(0, plan.action) plan = plan.parent action_plan = parseActionPlan(action_plan, initial) return action_plan
def get_solution(state, dim=3, heurfun='md', stats=False): """ Get a solution for a given possible states. Args: states: a tuple of integers from 1 to dim^2 dim: a positive integer. Either 2, 3 or 4 heurfun: the heuristic function to use in the search stats: should the number of nodes explored or added to the frontier be recorded Return: a single solution node """ goal = tuple(range(1, dim*dim + 1)) npp = NPuzzleProblem(state, goal, dim=dim) nph = NPuzzleHeuristics(hnfun=heurfun, dim=dim) if dim == 2 or dim == 3: solution = astar_search(npp, heurfun=nph.hnfun, stats=stats) elif dim == 4: solution = idastar_search(npp, heurfun=nph.hnfun, stats=stats) if stats: setattr(solution[0], 'hfname', nph.hfname) else: setattr(solution, 'hfname', nph.hfname) return solution
def plan_shot(current, heading, goals, allowed): """ Plan route to nearest location with heading directed toward one of the possible wumpus locations (in goals), then append shoot action. NOTE: This assumes you can shoot through walls!! That's ok for now. """ # print "goals", goals # print "allowed", allowed # print "goals and allowed:", (goals and allowed) if goals and allowed: psp = PlanShotProblem((current[0], current[1], heading), goals, allowed) node = search.astar_search(psp) # print "node", node if node: # print "Hello" plan = node.solution() plan.append(action_shoot_str(None)) # HACK: # since the wumpus_alive axiom asserts that a wumpus is no longer alive # when on the previous round we perceived a scream, we # need to enforce waiting so that itme elapses and knowledge of # "dead wumpus" can then be inferred... plan.append(action_wait_str(None)) return plan # no route can be found, return empty list return []
def construct_solution_from_pddl(pddl_domain, pddl_problem) -> None: initial_kb = PlanningKB(pddl_problem.goals, pddl_problem.initial_state) planning_actions = [STRIPSAction(name, preconds, effects) for name, preconds, effects in pddl_domain.actions] p = PlanningSearchProblem(initial_kb, planning_actions) print('\n{} solution:'.format(pddl_problem.problem_name)) print_solution(astar_search(p))
def a_star_for_tsp(tsp_problem: TSProblem, index: int) -> Node: result_node: Node = astar_search(tsp_problem, display=True) print('tsp sum:' + str(result_node.path_cost)) print('hamilton sum' + str(result_node.parent.path_cost)) print('Result for' + tsp_problem.h_name() + str(result_node.state)) print(result_node.path()) write_results_to_file(output_files_paths[index], result_node.state) return result_node
def __init__(self,p,var): self.p = p self.error = -1 self.var = var self.problem =Problem(self.p,var) self.result = search.astar_search(self.problem, lambda n: dfs_distance_to_equal(n.state, self.var, -1) ).state print "The result of the 1st step is:"+str(self.result) self.result = self.simplifier(self.result) self.outPut()
def flipit_solve(size, initial): """ Solve a flip problem and print the result """ problem = search.InstrumentedProblem( flipit.FlipIt_optimal(size=size, initial=initial)) print("Solving {} => {} optimal".format(problem.initial, problem.goal), flush=True) time0 = time.time() solution = search.astar_search(problem) elapsed = time.time() - time0 show_solution(solution, problem, elapsed) problem = search.InstrumentedProblem( flipit.FlipIt_aggressive(size=size, initial=initial)) print("Solving {} => {} aggressive".format(problem.initial, problem.goal), flush=True) time0 = time.time() solution = search.astar_search(problem) elapsed = time.time() - time0 show_solution(solution, problem, elapsed)
def main(): # ----------------------------------- Water Jug Problem -------------------------------------- # water_jug_prob = P1.WaterJugProblem((0, 0), (2, 0), (4, 3)) t0 = time.time() src1 = search.breadth_first_tree_search(water_jug_prob) t1 = time.time() src2 = search.astar_search(water_jug_prob) dt2 = time.time() - t1 dt1 = t1 - t0 print(src1.solution()) print(src2.solution()) print( "Uninformed search time: {0:.4f} seconds\nInformed search time: {1:.4f} seconds" .format(dt1, dt2)) # -------------------------------------------------------------------------------------------- # # ----------------------------------- N-Puzzle Problem: -------------------------------------- # puzzle_prob = P2.NPuzzleProblem((5, 1, 2, 4, 7, 6, 3, 8, 9, 14, 10, 12, 13, 0, 11, 15), \ (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0), 4) t0 = time.time() src1 = search.astar_search(puzzle_prob, puzzle_prob.h1) t1 = time.time() src2 = search.astar_search(puzzle_prob, puzzle_prob.h2) dt2 = time.time() - t1 dt1 = t1 - t0 print(src1.solution()) print(src2.solution()) print( "Heuristic 1 search time: {0:.4f} seconds\nHeuristic 2 search time: {1:.4f} seconds" .format(dt1, dt2))
def populate_sdac( self, projected_task, vars_maps, actions_maps ) : from itertools import product from search.breadth_first_search import breadth_first_search_sdac from model.generic.planning.task import State var_map, inv_var_map = vars_maps action_map, inv_action_map = actions_maps domains = [ x.domain for x in projected_task.task.state_vars ] value_index = 0 self.unsolvable_count = 0 self.num_non_zero_entries = 0 self.max_value = 0 for valuation in apply(product, map(tuple,domains) ) : value_index += 1 # indexed with the original vars entry_index = tuple([ ( inv_var_map[x], v) for x, v in enumerate(valuation) ]) s0 = State( projected_task.task, [ (x,v) for x,v in enumerate(valuation) ] ) projected_task.set_initial_state( s0 ) projected_task.initial_state.check_valid() if not projected_task.initial_state.valid : self.table[ entry_index ] = Entry( float('inf'), None ) self.unsolvable_count += 1 continue #solution = breadth_first_search_sdac( projected_task, True ) solution = astar_search(projected_task, H_Zero(projected_task)) if solution==None: plan = None final_state = None else: plan, final_state = solution print("plan : ",plan, " final_state : ",final_state) if plan is None : self.table[ entry_index ] = Entry( float('inf'), None ) self.unsolvable_count += 1 continue first_action_in_plan = None if len(plan) > 0 : self.num_non_zero_entries += 1 print("inv_action_map",inv_action_map) print("first_action_in_plan : ",plan[0].name) print("first_action_in_plan : ",inv_action_map[plan[0].index]) first_action_in_plan = inv_action_map[plan[0].index] self.table[ entry_index ] = Entry( final_state.g, first_action_in_plan ) self.max_value = max( self.max_value, len(plan) ) logging.info( '# of infinite entries in pattern: {0}'.format( self.unsolvable_count ) ) logging.info( '# of entries with a value greater than 0: {0}'.format(self.num_non_zero_entries) ) logging.info( 'Maximum value in pattern: {0}'.format( self.max_value ) )
def test4(): # Ler tabuleiro do ficheiro "i1.txt": board = parse_instance("i1.txt") # Criar uma instância de RicochetRobots: problem = RicochetRobots(board) # Obter o nó solução usando a procura A*: solution_node = astar_search(problem) print("done.")
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 dcsolver(initial="dog", goal="cat", cost='steps'): """ solve a dog-cat problem, print the solution, it's cost the the time taken """ problem = DC(initial, goal, cost) start = time.time() solution = astar_search(problem) elapsed = time.time() - start if solution: path = ' '.join([node.state for node in solution.path()]) path_cost = int(round(solution.path_cost)) else: path = "NO SOLUTION" path_cost = -1 print(f"{problem} cost:{path_cost}; time:{elapsed: .3f}; solution:{path}")
def optimal_search( task, h ) : from search import astar_search from search.a_star import ordered_node_astar h.enable_preferred_ops = False def heuristic_adapter( node ) : _, inv_var_map = vars_maps node.state.primary.unprojected = [ (inv_var_map[X],v) for X,v in node.state.primary.iter_values() ] return h(node) return astar_search( task, heuristic_adapter, make_open_entry=ordered_node_astar, use_relaxed_plan=False, mute=True )
def test_astar_gaschnig_vs_bidirectional_breadth_first(): eight_problem = InstrumentedProblem( EightPuzzle(initial=instance_one, goal=goal)) eight_problem1 = EightPuzzle(initial=instance_one, goal=goal) inversed_eight_problem = EightPuzzle(initial=goal, goal=instance_one) res = astar_search(eight_problem, EightPuzzleExtended(eight_problem).gaschnig_index) res1 = instrumented_bidirectional_breadth_first_search( eight_problem1, inversed_eight_problem, True) assert res.state == goal n = res1[0] assert n.state == goal assert eight_problem.explored > res1[1]
def init(): statoIniziale = ((0, 0), (1, 0), (2, 'a'), (3, 'b'), (4, 'c'), (5, 0), (6, 0)) problema = NailBox(statoIniziale) alg = astar_search(problema) #o in caso breadth_first_graph_search oppure depth_first_graph_search pp = alg.path() soluzione = alg.solution() for i in range(1, len(pp)): stato = pp[i].state costo = pp[i].path_cost azione = soluzione[i - 1] print(str(azione) + "\t\t\t" + str(stato) + "\t\t\t" + str(costo))
def findPosAndChar(array, returnSorted, invertSort=False): """ this function will find the differents characters in the array and put them into chars array by the same time it'll put the position of the found characters into another array named startEnd so with the index of a given character in chars, we'll be able to know where are the two characters in the whole array (at the beginning) for instance, with easy.in, it gives chars = ['A', 'B', 'C', 'D'] startEnd = [[[0, 0], [0, 4]], [[1, 0], [1, 4]], [[2, 0], [2, 4]], [[3, 0], [3, 4]]] the index of A in chars is 0, so with startEnd at the index 0, we have the two position of 'A' which are [[0, 0], [0, 4]] then it'll sort the arrays in the way that the firsts indexes of sortedChars and sortedStartEnd are the one with the smallest path between start and end if invertSort = true, then the biggest path is returned first and the smallest last """ #find chars = [] startEnd = [] for i in range(len(array)): for j in range(len(array[0])): char = array[i][j] if char != '.' and char not in chars: chars.append(char) startEnd.append([[i, j]]) elif char != '.' and char in chars: startEnd[chars.index(char)].append([i, j]) if not returnSorted: return chars, startEnd #sort costs = [] for i in range(len(chars)): state = State(array, startEnd[i][0], startEnd[i][1], chars[i]) shortestPath = ShortestRoute(state) path = search.astar_search(shortestPath).path() cost = len(path) costs.append([cost, chars[i]]) costs = sorted(costs) sortedChars = ['0' for _ in range(len(costs))] sortedStartEnd = [[[0, 0], [0, 0]] for _ in range(len(costs))] for i in range(len(costs)): if invertSort: index = len(costs) - 1 - i else: index = i sortedChars[index] = costs[i][1] sortedStartEnd[index] = startEnd[chars.index(costs[i][1])] return sortedChars, sortedStartEnd
def main(): """Default function to be called when the program executes.""" # Create an instance of the Search class with arguments from argparse searcher = Search(start, stop, args.grid) # Return the correct searching algorithm for a given specification if args.alg == 'bfs': search = aima.breadth_first_search(searcher) elif args.alg == 'ucs': search = aima.uniform_cost_search(searcher) else: search = aima.astar_search(searcher) return search.path()
def main(): global default_cube global goal scrambled = scrambler(default, 3) cube = Rubiks(scrambled, goal) startTime = time.time() result = astar_search(cube) endTime = time.time() print('solution is', Node.solution(result)) print('path is', Node.path(result)) print('걸린 시간 :', endTime - startTime)
def main(): gridSize = generateGridSize() initialState = generateInitialState(gridSize) goalState = generateGoalState(gridSize, initialState) print("The size of the grid is:", gridSize, "\n") print("The initial state:", initialState, "\n") print("The goal state:", goalState, "\n") problem_p4VehicleRoads = VehicleRoads(gridSize, initialState, goalState) t1 = time.time() problem_p4VehicleRoadsSol = search.astar_search(problem_p4VehicleRoads, problem_p4VehicleRoads.h) t2 = time.time() print("Path:", problem_p4VehicleRoadsSol.solution(), "\nTime:", t2 - t1, "\n")
def main(): timer = time.time() state1 = State({}) asar = ASARProblem(state1) asar.load('examples/simple8.txt', state1) final = astar_search(asar) if final is None: print('Infeasible') asar.save('solutions/simp1.txt', None) else: final.path()[-1].state.set_profit(asar.get_max_profit() - asar.profit) asar.save('solutions/simp1.txt', final.path()[-1].state) print("--- %s seconds ---" % (time.time() - timer))
def test_from(start_state, heuristic): hp = HuarongPass() hp.set_initial_state(start_state) acts = search.astar_search(hp, heuristic).solution() print time.asctime() print 'Required actions: ', len(acts) print 'Number expanded nodes:', hp.goal_tests hp.reset_nodes_expanded() audit_state(hp.state_given(start_state, acts))
def test_forwardPlan(): spare_tire_solution = astar_search(ForwardPlan(spare_tire())).solution() spare_tire_solution = list( map(lambda action: Expr(action.name, *action.args), spare_tire_solution)) assert expr('Remove(Flat, Axle)') in spare_tire_solution assert expr('Remove(Spare, Trunk)') in spare_tire_solution assert expr('PutOn(Spare, Axle)') in spare_tire_solution cake_solution = astar_search(ForwardPlan( have_cake_and_eat_cake_too())).solution() cake_solution = list( map(lambda action: Expr(action.name, *action.args), cake_solution)) assert expr('Eat(Cake)') in cake_solution assert expr('Bake(Cake)') in cake_solution air_cargo_solution = astar_search(ForwardPlan(air_cargo())).solution() air_cargo_solution = list( map(lambda action: Expr(action.name, *action.args), air_cargo_solution)) assert expr('Load(C2, P2, JFK)') in air_cargo_solution assert expr('Fly(P2, JFK, SFO)') in air_cargo_solution assert expr('Unload(C2, P2, SFO)') in air_cargo_solution assert expr('Load(C1, P2, SFO)') in air_cargo_solution assert expr('Fly(P2, SFO, JFK)') in air_cargo_solution assert expr('Unload(C1, P2, JFK)') in air_cargo_solution sussman_anomaly_solution = astar_search(ForwardPlan( three_block_tower())).solution() sussman_anomaly_solution = list( map(lambda action: Expr(action.name, *action.args), sussman_anomaly_solution)) assert expr('MoveToTable(C, A)') in sussman_anomaly_solution assert expr('Move(B, Table, C)') in sussman_anomaly_solution assert expr('Move(A, Table, B)') in sussman_anomaly_solution blocks_world_solution = astar_search(ForwardPlan( simple_blocks_world())).solution() blocks_world_solution = list( map(lambda action: Expr(action.name, *action.args), blocks_world_solution)) assert expr('ToTable(A, B)') in blocks_world_solution assert expr('FromTable(B, A)') in blocks_world_solution assert expr('FromTable(C, B)') in blocks_world_solution shopping_problem_solution = astar_search(ForwardPlan( shopping_problem())).solution() shopping_problem_solution = list( map(lambda action: Expr(action.name, *action.args), shopping_problem_solution)) assert expr('Go(Home, SM)') in shopping_problem_solution assert expr('Buy(Banana, SM)') in shopping_problem_solution assert expr('Buy(Milk, SM)') in shopping_problem_solution assert expr('Go(SM, HW)') in shopping_problem_solution assert expr('Buy(Drill, HW)') in shopping_problem_solution
def solve(initial, goal, heur, debug=0): ''' 8 puzzle using A* search using misplaced and cityblock heuristics ''' # return a list that indicates the sequence of steps that are needed to reach the goal state # if no solution exists, return 'None' # list to be returned results = list() if valid_input(initial, goal, heur, debug): # Valid inputs, convert to tuples init_node = tuple(initial) goal_node = tuple(goal) heuristic = (heur == 'cityblock') ################################################## # Debug tuple conversion if debug >= 1: print("Node Initial: ", init_node) print("Node Goal: ", goal_node) if heuristic: print("CityBlock Heuristic") else: print("Misplaced Heuristic") ################################################## # astar problem and result astar_problem = Puzzle(init_node, goal_node, heuristic, debug) astar_results = astar_search(astar_problem) if isinstance(astar_results, (Node) ): results = astar_results.solution() if debug == 0: if len(results) == 0: print ("None") else: print results else: print("None") ################################################## if debug >= 1: print("Solve returning: ", results) ################################################## return results
def main(): gridSize = 6 weight = 2 endSimTime = 2 carsLoc = ((1, 1), (0, 0)) numEvents = 6 locX = gridSize / 2 scaleX = gridSize / 3 locY = gridSize / 2 scaleY = gridSize / 3 # randomize event times eventTimes = unifromRandomEvents(0, endSimTime, numEvents) eventPosX = truncnorm.rvs((0 - locX) / scaleX, (gridSize - locX) / scaleX, loc=locX, scale=scaleX, size=numEvents).astype(np.int64) eventPosY = truncnorm.rvs((0 - locY) / scaleY, (gridSize - locY) / scaleY, loc=locY, scale=scaleY, size=numEvents).astype(np.int64) eventsLoc = tuple([(x, y) for x, y in zip(eventPosX, eventPosY)]) eventsTime = tuple(eventTimes) maxTime = np.max(eventsTime) + 3 flagActions = 0 initial = createInitialState(carsLoc, eventsTime, eventsLoc, flagActions) iterStart = time.clock() solver = SolveCars2EventsAstar(initial=initial, gridSize=gridSize, maxTime=maxTime, weight=weight) # solver = pickle.load(open('solver4Test2.p', 'rb')) astarSolution = astar_search(solver) iterEnd = time.clock() print('time to calc=' + str(round(iterEnd - iterStart, 3))) CarShortestPath = PrintShortestPath(astarSolution) # dump logs with open( 'aStarResult_' + str(weight) + 'weight_' + str(len(carsLoc)) + 'numCars_' + str(numEvents) + 'numEvents_' + str(gridSize) + 'gridSize.p', 'wb') as out: pickle.dump( { 'shortestPath': CarShortestPath, 'aimaSolution': astarSolution }, out)
def missionary_problem(): print("*" * 80) print("Missionary problem, the encoding is a set of tuples") print( "Encoding: (nBoat, nMissionaries, nCannibals, nBoats2, nMissionaries2, nCannibals2) eg. (1, 3, 3, 0, 0, 0)" ) print( "The first three numbers denote the numbers of boats, missionaries, cannibals on the first side" ) print( "The second three numbers denote the numbers of boats, missionaries, cannibals on the other side" ) print("The solution is displayed as the state after executing every move") srch = astar_search(MissionariesProblem(), my_heuristic) print('-' * 80) [print("%3d" % (i + 1), ". ", j) for i, j in enumerate(srch.solution())] print("*" * 80)
def sample_astar_search(): nodes = list(G.nodes()) ids = np.random.randint(0, len(nodes)) idg = np.random.randint(0, len(nodes)) s = nodes[ids] g = nodes[idg] print(s, g) def h(s1, s2): return abs(s1[0] - s2[0]) + abs(s1[1] - s2[1]) for W in [0, 1, 2, 3]: t_start = time.time() cost, path = astar_search(G, s, g, heuristic=h, W=W) t_search = time.time() - t_start print(W, cost, t_search) print(">", path)
def main(): timer = time.time() inFile = sys.argv[-2] outFile = sys.argv[-1] state1 = State({}) asar = ASARProblem(state1) asar.load(inFile, state1) final = astar_search(asar) if final is None: print('Infeasible') asar.save(outFile, None) else: final.path()[-1].state.set_profit(asar.get_max_profit() - asar.profit) asar.save(outFile, final.path()[-1].state) print("--- %s seconds ---" % (time.time() - timer))
def sample_bidirectional_mm_search(): nodes = list(G.nodes()) ids = np.random.randint(0, len(nodes)) idg = np.random.randint(0, len(nodes)) while ids == idg: idg = np.random.randint(0, len(nodes)) s = nodes[ids] g = nodes[idg] print(s, g) def h(s1, s2): return abs(s1[0] - s2[0]) + abs(s1[1] - s2[1]) cost, path = astar_search(G, s, g, heuristic=h, W=W) print(cost, path) cost, path = bidirectional_mm_search(G, s, g, heuristic=None) print(cost, path)
def plan_shot(current, heading, goals, allowed): """ Plan route to nearest location with heading directed toward one of the possible wumpus locations (in goals), then append shoot action. NOTE: This assumes you can shoot through walls!! That's ok for now. """ if goals and allowed: psp = PlanShotProblem((current[0], current[1], heading), goals, allowed) node = search.astar_search(psp) if node: plan = node.solution() plan.append(action_shoot_str(None)) # HACK: # since the wumpus_alive axiom asserts that a wumpus is no longer alive # when on the previous round we perceived a scream, we # need to enforce waiting so that itme elapses and knowledge of # "dead wumpus" can then be inferred... plan.append(action_wait_str(None)) return plan # no route can be found, return empty list return []
def get_random_solutions(num=1, dim=3, heurfun='md', stats=False): """ Generate num of random initial states and get solutions Args: num: positive integer indicating the number of states you want to solve for dim: dimension of the n-puzzle. 2, 3 or 4 heurfun: heuristic function to use for the search algorithm. See search.py and NPuzzleHeuristics.py """ random_states = gi_states(num, dim) solutions = [] for state in random_states: # NPuzzleProblem takes inital state, goal and optional dim npp = NPuzzleProblem(state, tuple(range(1, len(state) + 1)),\ dim=dim) nph = NPuzzleHeuristics(hnfun=heurfun) solutions.append(astar_search(npp, heurfun=nph.hnfun,\ stats=stats)) return solutions
print print '-' * 50 print "Running GREEDY-BEST-FIRST-TREE-SEARCH" print '-' * 50 gbfs = greedy_best_first_search(travel_problem, city_h, search_type=best_first_tree_search) print "Solution", gbfs.solution() print print '-' * 50 print "Running A*-TREE-SEARCH" print '-' * 50 asts = astar_search(travel_problem, city_h, search_type=best_first_tree_search) print "Solution", asts.solution() print print '=' * 50 print '=' * 50 print "HW2 ROMANIA" print '=' * 50 print '=' * 50 city_map2 = CityMap() city_map2.add_road('AR', 'ZE', 75) city_map2.add_road('AR', 'SI', 140) city_map2.add_road('AR', 'TI', 118)
12,14,15,1],4)) print a.solution() print a.depth if check_solvable(Puzzle_15,4): t = search.astar_search(game_15(Puzzle_15,4)) else: print "Puzzle is unsolvable, please change" """ if check_solvable(Puzzle_8,3): p = search.InstrumentedProblem(game_15(Puzzle_8,3)) #t = search.astar_search(p) time1 = time.time() t = search.astar_search(p) #t = search.recursive_best_first_search(p) time2 = time.time() print p #search.compare_searchers(problems = [game_15(Puzzle_8,3)],header=['Searcher', 'Puzzle 8']) print t.solution() print t.depth print "time taken is:" print time2 - time1 else: print "Sorry the puzzle is not feasible" """ count = 0 # Count all the inversions in the puzzle puzzle = [15,14,13,12,\ 11,10,9,8,\
def solve(initial, goal, method): """ Setup a new EightPuzzle object and then get the solution to it. """ x = EightPuzzle(tuple(initial), tuple(goal), method) return search.astar_search(x, x.value).solution()
for j in range(n): if node.state[i][j] != goal[i][j]: res += 1 return res class NPuzzle(search.Problem): """Subclass of the general Problem class, for modeling the NPuzzle""" def successor(self, state): """Returns a sequence of (action, state) reachable from this state. An action consists of moving the empty tile to an adjacent square.""" n = len(state) for i in range(n): for j in range(n): if state[i][j] == 0: zrow = i zcol = j for action in actions: mrow = zrow+action[0]; mcol = zcol+action[1] if is_within(mrow, mcol, n): tempState = [[state[i][j] for j in range(n)] for i in range(n)] tempState[zrow][zcol] = tempState[mrow][mcol] tempState[mrow][mcol] = 0 newState = tuple(tuple(el) for el in tempState) yield ((labels[action], newState)) search.astar_search(NPuzzle(board, goal), lambda n : sumManhattan(n) + misplacedTiles(n)).print_path()
def run_huarong_pass(): # buffer that gets written to the output file after all searching is complete report = [] start_state = initial_state start_state = step_59_state ######### REMOVE BEFORE TURN-IN ########### hp = HuarongPass() hp.set_initial_state(start_state) h1 = hp.h1 h2 = hp.h2 f = open(fn_hp_results, 'w') if not f: print "HuarongPass: error opeing file:", fn_hp_results else: report.append('Testing Huarong Pass Heuristics...') report.append('') ######## RUN H1 ############### report.append("Running A* Huarong Pass --- Heuristic: " + h1.__name__ + " @ " + time.asctime()) print report[-1] t0 = time.time() acts1 = search.astar_search(hp, h1).solution() td1 = time.time() - t0 report.append('Time : ' + str(td1) + ' seconds') report.append('Actions : ' + str(len(acts1))) report.append('Expanded nodes : ' + str(hp.goal_tests)) report.append('') hp.reset_goal_tests() ######## RUN H2 ############### report.append("Running A* Huarong Pass --- Heuristic: " + h2.__name__ + " @ " + time.asctime()) print report[-1] t0 = time.time() acts2 = search.astar_search(hp, h2).solution() td2 = time.time() - t0 report.append('Time : ' + str(td2) + ' seconds') report.append('Actions : ' + str(len(acts2))) report.append('Expanded nodes : ' + str(hp.goal_tests)) report.append('') hp.reset_goal_tests() # Determine better heuristic action_delta = abs(len(acts1) - len(acts2)) time_delta = abs(td1 - td2) if (len(acts1) < len(acts2)): not_optimal = h2.__name__ elif (len(acts2) < len(acts1)): not_optimal = h1.__name__ else: not_optimal = 'Neither' if (td1 > td2): fastest = h2.__name__ else: fastest = h1.__name__ # Report better heuristic sdom = str(not_optimal) + ' was less than optimal with ' + str(action_delta) + ' more actions.' sfast = str(fastest) + ' was the faster heuristic, running for ' + str(time_delta) + ' fewer seconds.' # print sdom # print sfast report.append(sdom) report.append(sfast) for line in report: f.write(line + EOL) f.close() print 'Testing complete!' return None
def goal_test(self, state): if(state.type == 'EQUALS' and state.children[0].leaf == self.goal): return True else: return False def path_cost(self, c, state1, action, state2): return c + 1 def value(self, state): return 0 while 1: try: s = raw_input('eq > ') # use input() on Python 3 var = raw_input('var > ') except EOFError: print break p = eqparser.parse(s) problem =Problem(p,var) result = search.astar_search(problem, lambda n: HFunction(n.state, var, -1) ).state s = segment(result) print s #print "In infix form: " + str(p)
def astar_search(problem): return search.astar_search(problem, problem.h)
print print '-' * 50 print "Running GREEDY-BEST-FIRST-TREE-SEARCH USING # MISPLACED TILES HEURISTIC" print '-' * 50 gbfts = greedy_best_first_search(ep, misplaced_tiles_heuristic, search_type=best_first_tree_search) print "Solution", gbfts.solution() print print '-' * 50 print "Running A*-TREE-SEARCH USING # MISPLACED TILES HEURISTIC" print '-' * 50 asts = astar_search(ep, misplaced_tiles_heuristic, search_type=best_first_tree_search) print "Solution", asts.solution() print print '=' * 50 print '=' * 50 print "HW1 MAP" print '=' * 50 print '=' * 50 city_map = CityMap() city_map.add_road('F', 'S', 5) city_map.add_road('S', 'C', 6)
# 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
def solve(): """ Solves the puzzle using astar_search """ return astar_search(puzzle).solution()
def main(): dp = DomainProblem('domain-03.pddl', 'problem-03.pddl') print(astar_search(PlanningProblem(dp)).solution())
""" python run_A_Star.py heuristicNo size steps """ arg = sys.argv heuristic = int(arg[1]) p = puzzle(None, True, "inputState.txt", False, None) startTime = time.time() if heuristic == 0 : solution = breadth_first_search(p) elif heuristic == 1 : solution = astar_search(p, lambda x : h1(x, p.goal)) elif heuristic == 2 : solution = astar_search(p, lambda x : h2(x, p.goal)) elif heuristic == 3 : solution = astar_search(p, lambda x : h3(x, p.goal)) elif heuristic == 4 : solution = astar_search(p, lambda x : h4(x, p.goal)) solution = solution.solution() if solution != None: print "Actions made : ", len(solution) print "Time elapsed : %.3f" % (time.time() - startTime)
def plan_route(self, current, goals, allowed): problem = PlanRoute(current, goals, allowed, self.dimrow) return astar_search(problem).solution()