def aStarSearch(problem, heuristic=nullHeuristic): priorityFunc = lambda state: problem.getCostOfActions(state[1]) + heuristic(state[0], problem) queue = PriorityQueueWithFunction(priorityFunc) current_state = problem.getStartState() actions = [] visited = [] # state depends on problem now but actions list is independent thus priorityFunc should work on every problem # queue of pairs -> (state, [actions]) queue.push((current_state, actions)) while queue: current_state, actions = queue.pop() #successor: # coords: (x, y) # Direction: game.Directions # cost: int if current_state not in visited: visited.append(current_state) if problem.isGoalState(current_state): return actions for successor in problem.getSuccessors(current_state): state, action, _ = successor newActions = actions + [action] queue.push((state, newActions)) return []
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction def cost(fringe): total_cost = 0 for n in fringe: total_cost += n[2] return total_cost search_tree = PriorityQueueWithFunction(cost) expanded = [] search_tree.push([(problem.getStartState(), None, 0)]) while not search_tree.isEmpty(): fringe_to_expand = search_tree.pop() node_to_expand = fringe_to_expand[0][0] if node_to_expand in expanded: continue if problem.isGoalState(node_to_expand): directions = [] for node in fringe_to_expand: if None != node[1]: directions.append(node[1]) directions.reverse() return directions expanded.append(node_to_expand) for state in problem.getSuccessors(node_to_expand): if state[0] not in expanded: to_add = fringe_to_expand.copy() to_add.insert(0, state) search_tree.push(to_add) util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" """*** YOUR CODE HERE ***""" from util import PriorityQueueWithFunction return graphSearch(problem, PriorityQueueWithFunction(lambda x: x[2] + heuristic(x[0], problem)))
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction frontier = PriorityQueueWithFunction(heuristic) visited = set() start_node = problem.getStartState() action = [] cost = 0 frontier.push((start_node, action, cost)) while not frontier.isEmpty(): current_state, current_action, current_cost = frontier.pop() if problem.isGoalState(current_state): return current_action visited.add(current_state) for successor, new_action, new_cost in problem.getSuccessors( current_state): if successor not in visited: cost = current_cost + new_cost action = current_action + [new_action] frontier.push((successor, action, cost))
def oldAStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" # i is state = ((x, y), dir, cost) priorityFunc = lambda item: sum(i[2] for i in item) + heuristic(item[len(item) - 1][0], problem) # queue is queue of states queue = PriorityQueueWithFunction(priorityFunc) #pathsQueue = PriorityQueueWithFunction(priorityFunc) current_state = [] # array of arrays current_state.append((problem.getStartState(), Directions.STOP, 0)) queue.push(current_state) while True: # current_state is an array of states current_state = queue.pop() #successor(state): # coords: (x, y) # Direction: game.Directions # cost: int for successor in problem.getSuccessors(current_state[len(current_state) - 1][0]): state_copy = copy.deepcopy(current_state) if successor[0] not in list(map(lambda item: item[0], state_copy)): state_copy.append(successor) queue.push(state_copy) if problem.isGoalState(successor[0]): # from coord to dirs return list(map(lambda item: item[1], state_copy))
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" # Factory creating appropriate Nodes given parent-Node and successor (state, action, cost) nodeFactory = lambda parentNode, successor: Node(parentNode, successor) # fringe is for DFS, i.e. Nodes with HIGHER depth have lower priority-value and will be popped of the fringe first. fringeDFS = PriorityQueueWithFunction(lambda node: -node.depth) # Strategy: Already using a DFS fringe; no extra strategy needed, just pop from fringe. strategyDFS = lambda fringe: fringe.pop() result = genericGraphSearch(problem, fringeDFS, strategyDFS, nodeFactory, True) return getActionsToThisNode(result)
def aStarSearch(problem, heuristic=nullHeuristic): from util import PriorityQueueWithFunction "Search the node that has the lowest combined cost and heuristic first." return graphSearch( problem, PriorityQueueWithFunction( lambda item: item.pathCost + heuristic(item.state, problem)))
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction q = PriorityQueueWithFunction(lambda x: x[2]) visited = [] if (problem.getStartState()): q.push((problem.getStartState(), [], 0)) else: return "error" while not q.isEmpty(): cur, res, cost = q.pop() if (problem.isGoalState(cur)): return res if (cur not in visited): visited.append(cur) tmp = problem.getSuccessors(cur) for x in tmp: action = res + [x[1]] curcost = problem.getCostOfActions(action) + heuristic( x[0], problem) q.push((x[0], res + [x[1]], curcost)) return 0 util.raiseNotDefined() util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." frontier = PriorityQueueWithFunction(heuristic, problem) startNode = Node((problem.getStartState(), None, None)) #Check if start node is goal if problem.isGoalState(startNode.state): return [] for successors in problem.getSuccessors(problem.getStartState()): newNode = Node(successors, startNode) frontier.push(newNode) explored = list() explored.append(startNode.state) while not frontier.isEmpty(): leafNode = frontier.pop() if problem.isGoalState(leafNode.state): return leafNode.getPath() explored.append(leafNode.state) for successor in problem.getSuccessors(leafNode.state): newNode = Node(successor, leafNode) if newNode.state not in frontier.stateList and newNode.state not in explored: frontier.push(newNode) return []
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction StartState = (problem.getStartState(), 'NULL', 0) gCost = {} gCost[StartState[0]] = 0 queue = PriorityQueueWithFunction( lambda x: gCost[x[0]] + heuristic(x[0], problem)) queue.push(StartState) visitednode = {} fathernode = {} while not queue.isEmpty(): state = queue.pop() visitednode[state[0]] = True if problem.isGoalState(state[0]): path = [] while (True): if state[1] == "NULL": break path.append(state[1]) state = fathernode[state] path.reverse() return path for successor in problem.getSuccessors(state[0]): if not visitednode.has_key(successor[0]) or gCost[ successor[0]] > gCost[state[0]] + successor[2]: visitednode[successor[0]] = True gCost[successor[0]] = gCost[state[0]] + successor[2] queue.push(successor) fathernode[successor] = state return []
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction def functionAStar((state, actions, cost)): return cost frontier = PriorityQueueWithFunction(functionAStar) actions = [] frontier.push((problem.getStartState(), actions, 0)) visited = [] while not frontier.isEmpty(): cur, actions, cost = frontier.pop() if problem.isGoalState(cur): return actions if cur not in visited: visited.append(cur) s = problem.getSuccessors(cur) for nextnode, action, cost in s: tmp = actions + [action] nextcost = problem.getCostOfActions(tmp) + heuristic( nextnode, problem) if nextnode not in visited: frontier.push((nextnode, tmp, nextcost)) util.raiseNotDefined()
def uniformCostSearch(problem): """Search the node of least total cost first.""" cost = lambda path: problem.getCostOfActions([x[1] for x in path][1:]) from util import PriorityQueueWithFunction structure = PriorityQueueWithFunction(cost) return generalSearch(problem, structure)
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" fun = lambda path: problem.getCostOfActions([x[1] for x in path][1:]) + heuristic(path[-1][0], problem) from util import PriorityQueueWithFunction structure = PriorityQueueWithFunction(fun) return generalSearch(problem, structure)
def aStarPath(): def priorityFunction(node): state, actions_sequence, path_cost = node heuristic_cost = heuristic(state, problem) return path_cost + heuristic_cost frontier = PriorityQueueWithFunction(priorityFunction) return commonSearch(frontier)
def aStarSearch(problem, heuristic=nullHeuristic): def getCostAstar((pos, ActionList)): cost = problem.getCostOfActions(ActionList) hCost = heuristic(pos, problem) return cost + hCost queue = PriorityQueueWithFunction(getCostAstar) return universeSearch(queue, problem)
def depthFirstSearch(problem): """Performs DFS in order to find a path for the solution""" def dfsFunction(item): global dfsCount dfsCount -= 1 return dfsCount frontier = PriorityQueueWithFunction(dfsFunction) return genericSearch(problem, frontier)
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." node = Node(problem.getStartState(), None, 0, None) if problem.isGoalState(node.state): return node.get_path() def wrapper(node): return heuristic(node.state, problem) frontier = PriorityQueueWithFunction(wrapper) frontier.push(node) return graph_search(problem, frontier)
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" node = problem.getStartState() if (problem.isGoalState(node)): return [] # no need to make any moves of the start state is goal start = node heuristic_costFn = lambda x: heuristic(x, problem) + problem.costFn( x) + problem.getCostOfActions(x) frontier_queue = PriorityQueueWithFunction( heuristic_costFn) # queue for frontier frontier_queue.push(start) # frontier consists of only the start state explored_nodes = set() explored_track = { start: None } # keep a track of parent, parent of root node is None # explored_track = {} # keep a track of parent, parent of root node is None while not frontier_queue.isEmpty(): state = frontier_queue.pop() # pop the top element from the queue explored_nodes.add(state) if problem.isGoalState(state): return get_track(explored_track, state) neighbors_state = problem.getSuccessors(state) for neighbor in neighbors_state: # neighbor will be something like this ((34, 15), 'South', 1). if neighbor[0] not in frontier_queue.heap and neighbor[ 0] not in explored_nodes: frontier_queue.push(neighbor[0]) if state == start: explored_track[neighbor] = start else: explored_track[neighbor] = state def get_track(explored_track, state): from game import Directions track_history = [] final_move = [j for j in explored_track.keys() if j[0] == state] move = final_move while explored_track[move[0]] != start: move = [j for j in explored_track.keys() if j[0] == state] track_history.append(move[0][1]) state = explored_track[move[0]] return track_history[::-1]
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" # Factory creating appropriate Nodes given parent-Node and successor (state, action, cost) nodeFactory = lambda parentNode, successor: Node(parentNode, successor) # fringe is for BFS, i.e. Nodes with LOWER depth have lower priority-value and will be popped of the fringe first. fringeBFS = PriorityQueueWithFunction(lambda node: node.depth) # Strategy: Already using a BFS fringe; no extra strategy needed, just pop from fringe. strategyBFS = lambda fringe: fringe.pop() result = genericGraphSearch(problem, fringeBFS, strategyBFS, nodeFactory, True) return getActionsToThisNode(result)
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" # Factory creating appropriate Nodes given parent-Node and successor (state, action, cost) nodeFactory = lambda parentNode, successor: UCSNode(parentNode, successor) # fringe is for UCS, i.e. Nodes with LOWER total-path-cost have lower priority-value and will be popped of the fringe first. fringeUCS = PriorityQueueWithFunction(lambda node: node.totalPathCost) # Strategy: Already using a BFS fringe; no extra strategy needed, just pop from fringe. strategyUCS = lambda fringe: fringe.pop() result = genericGraphSearch(problem, fringeUCS, strategyUCS, nodeFactory, True) return getActionsToThisNode(result)
def uniformCostSearch(problem): """ Search the node of least total cost first. """ from util import PriorityQueueWithFunction # construct a function g: # param : node - a node that contains a state in the state space of the problem # returns : the cost of the path from a start state to node (in searchAgents.py) g = lambda node: node[PATH_COST] priorityQueue = PriorityQueueWithFunction(g) return graphSearch(problem, priorityQueue)
def graph_search(problem, priority_func, heuristic=None): # start fringe (state, actions, cost) """ :param problem: problem :param priority_func: func(Fringe) returns int :param heuristic: func(state, problem) :return: actions for the problem :rtype: list """ goal_fringe = fringe = Fringe(problem.getStartState(), [], 0, 0) # closed set closed = Set() # all possible states from util import PriorityQueueWithFunction fringe_queue = PriorityQueueWithFunction(priority_func) fringe_queue.push(fringe) while not fringe_queue.isEmpty(): # pop fringe = fringe_queue.pop() # goal test if problem.isGoalState(fringe.state): goal_fringe = fringe break # closed set if contains(closed, fringe.state): continue closed.add(fringe.state) # expand for successor in problem.getSuccessors(fringe.state): next_state, action, cost = successor expanded_fringe = Fringe(next_state, fringe.actions[:], fringe.cost_backward + cost, 0) expanded_fringe.actions.append(action) if heuristic is not None: expanded_fringe.cost_forward = heuristic( expanded_fringe.state, problem) # push fringe_queue.push(expanded_fringe) return goal_fringe.actions if goal_fringe is not None else []
def uniformCostSearch(problem): """Search the node of least total cost first.""" from util import PriorityQueueWithFunction costFn = lambda n: n[3] open = PriorityQueueWithFunction(costFn) start = problem.getStartState() open.push((start, [], {start: 0}, 0)) while not open.isEmpty(): n = open.pop() if n[3] <= n[2][n[0]]: if problem.isGoalState(n[0]): return n[1] for succ in problem.getSuccessors(n[0]): if not succ[0] in n[2] or n[3] + succ[2] < n[2][succ[0]]: open.push( (succ[0], n[1] + [succ[1]], n[2], n[3] + succ[2])) n[2][succ[0]] = n[3] + succ[2]
def uniformCostSearch(problem): "Search the node of least total cost first. " # Implementing a different approach because I was getting illegal moves using the one above. # On the other hand, it was working for the eightpuzzle. #I am using a dictionary to story the path and cost of the locations and a PriorityQueuewithFunction #for the frontier. And this is not working for the eightpuzzle! from util import PriorityQueueWithFunction temp_solution = [] path_cost = 0 node = problem.getStartState() solution = {} solution[node] = [temp_solution, path_cost] explored = [] def cost(child): return solution[child][1] frontier = PriorityQueueWithFunction(cost) while not problem.isGoalState(node): if node not in explored: explored.append(node) successors = problem.getSuccessors(node) for state, actions, stepCost in successors: try: solution[state] if path_cost + stepCost < solution[state][1]: solution[state] = [ temp_solution + [actions], path_cost + stepCost ] except: solution[state] = [ temp_solution + [actions], path_cost + stepCost ] frontier.push(state) node = frontier.pop() temp_solution = solution[node][0] path_cost = solution[node][1] return solution[node][0]
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" # Astar is essentially the uniform cost search and greedy search algorithms combined! #The implementation is the same as the uniform cost search with an addition of the heuristi #in the cost function. from util import PriorityQueueWithFunction temp_solution = [] path_cost = 0 node = problem.getStartState() solution = {} solution[node] = [temp_solution, path_cost] explored = [] def cost(x): return solution[x][1] + heuristic(x, problem) frontier = PriorityQueueWithFunction(cost) while problem.isGoalState(node) is False: if node not in explored: explored.append(node) successors = problem.getSuccessors(node) for state, actions, stepCost in successors: try: solution[state] if path_cost + stepCost < solution[state][1]: solution[state] = [ temp_solution + [actions], path_cost + stepCost ] except: solution[state] = [ temp_solution + [actions], path_cost + stepCost ] frontier.push(state) node = frontier.pop() temp_solution = solution[node][0] path_cost = solution[node][1] return solution[node][0]
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" # Curry the heuristic to the problem. problemHeuristic = lambda state: heuristic(state, problem) # Factory creating appropriate Nodes given parent-Node and successor (state, action, cost) nodeFactory = lambda parentNode, successor: AStarNode( parentNode, successor, problemHeuristic) # fringe is for AStar, i.e. Nodes with LOWER (total-path-cost+heuristic) have lower priority-value and will be popped of the fringe first. fringeAStar = PriorityQueueWithFunction(lambda node: node.totalCost) # Strategy: Already using a BFS fringe; no extra strategy needed, just pop from fringe. strategyAStar = lambda fringe: fringe.pop() result = genericGraphSearch(problem, fringeAStar, strategyAStar, nodeFactory, True) return getActionsToThisNode(result)
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction def fun((state, action)): return problem.getCostOfActions(action) frontier = PriorityQueueWithFunction(fun) visited = [] frontier.push((problem.getStartState(), [])) while not frontier.isEmpty(): cur, path = frontier.pop() if problem.isGoalState(cur): return path if cur not in visited: visited.append(cur) for next, action, cost in problem.getSuccessors(cur): if next not in visited: frontier.push((next, path + [action])) util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction def priority(fringe): total_cost = 0 for n in fringe: total_cost += n[2] return total_cost + heuristic(fringe[0][0], problem) search_tree = PriorityQueueWithFunction(priority) expanded = [] search_tree.push([(problem.getStartState(), None, 0)]) while not search_tree.isEmpty(): fringe_to_expand = search_tree.pop() node_to_expand = fringe_to_expand[0][0] if node_to_expand in expanded: continue if problem.isGoalState(node_to_expand): directions = [] for node in fringe_to_expand: if None != node[1]: directions.append(node[1]) directions.reverse() return directions expanded.append(node_to_expand) for state in problem.getSuccessors(node_to_expand): if state[0] not in expanded: to_add = fringe_to_expand.copy() to_add.insert(0, state) search_tree.push(to_add) util.raiseNotDefined() util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction dict = {problem.getStartState(): 0} def helper(comb): (v, p) = comb return dict[v] + heuristic(v, problem) pq = PriorityQueueWithFunction(helper) pq.push((problem.getStartState(), [])) visited = set() while pq: (v, p) = pq.pop() if v not in visited: if problem.isGoalState(v): return p visited.add(v) for s in problem.getSuccessors(v): newcost = dict[v] + s[2] dict.update({s[0]: newcost}) pq.push((s[0], p + [s[1]]))
def uniformCostSearch(problem): "Search the node of least total cost first. " "*** YOUR CODE HERE ***" from util import PriorityQueueWithFunction q = PriorityQueueWithFunction(lambda x: x[2]) visited = [] if (problem.getStartState()): q.push((problem.getStartState(), [], 0)) else: return "error" while not q.isEmpty(): cur, res, cost = q.pop() if (problem.isGoalState(cur)): return res if (cur not in visited): visited.append(cur) tmp = problem.getSuccessors(cur) for x in tmp: "res.append(x[1])" q.push((x[0], res + [x[1]], cost + x[2])) return 0 util.raiseNotDefined()