示例#1
0
def uniformCostSearch(problem):
  "Search the node of least total cost first. "
  "*** YOUR CODE HERE ***"
  from util import PriorityQueueWithFunction
    
  currentState = problem.getStartState()
  
  setOfExploredNodes = set([currentState])
  listofMoves = []  
  priorities = {} # priorities[state] = ( priority value , path to this node )
  successorStack = PriorityQueueWithFunction(lambda x: x[1][x[0]][0])
  pathWeight = 0    
  
  while not problem.isGoalState(currentState):
      for successor in problem.getSuccessors(currentState):          
          priorities[successor[0]] = (pathWeight + successor[2], listofMoves + [successor[1]])
          if successor[0] not in setOfExploredNodes:              
              setOfExploredNodes.add(successor[0])
              successorStack.push( (successor[0], priorities) )
          
          
      
      currentState = successorStack.pop()[0]
            
      setOfExploredNodes.add(currentState)
      listofMoves = priorities[currentState][1]
      pathWeight = priorities[currentState][0]

  return listofMoves
示例#2
0
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 BEST_FIRST_SEARCH(problem, EvalFn, heuristic):
    queuingFn = getQueuingFnHeuristicMode(EvalFn)
    n = Node([problem.getStartState()], [], 0, heuristic(problem.getStartState(), problem))
    from util import PriorityQueueWithFunction
    nodes =  PriorityQueueWithFunction(heuristicAStarQueuingFn)
    nodes.push(n)
    
    while nodes:
        node = nodes.pop()
        if problem.isGoalState(node.getState()):
            return node.parent_node
        nodes = queuingFn(nodes, node.EXPAND(problem))
    
    return None
示例#4
0
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

    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()
示例#6
0
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 []
示例#7
0
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 []
示例#8
0
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()
示例#9
0
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))
示例#10
0
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)))
示例#11
0
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)
示例#12
0
 def __init__(self,problem,shoot):
     self.numExpandedNodes = 0
     self.problem = problem
     self.frontier = PriorityQueueWithFunction(self.fcost)
     self.timeOnHeuris = 0
     self.timeOnTotal = 0
     self.shoot = shoot
示例#13
0
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)))
示例#14
0
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)
示例#15
0
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)
示例#16
0
    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)
示例#17
0
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)
示例#18
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]
示例#19
0
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]
示例#20
0
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 []
示例#21
0
def aStarSearchNormal(problem, heuristic=nullHeuristic):
    from util import PriorityQueueWithFunction
    visitedList = {}
    startState = problem.getStartState()
    q = PriorityQueueWithFunction(lambda a: a.cost + a.heuristic)#proposition to priority
    q.push(aStarPriorityQueueMember(startState, None, None, 0, heuristic(startState, problem)))
    targetState = None
    while not q.isEmpty():
        targetStateAndCost = q.pop()
        targetState = targetStateAndCost.state
        targetPrevState = targetStateAndCost.prevState
        targetAction = targetStateAndCost.action
        targetPathCost = targetStateAndCost.cost
        if targetState not in visitedList.keys(): #why?
                visitedList[targetState] = [targetPrevState, targetAction, targetPathCost]
                if problem.isGoalState(targetState):
                    actionList = buildActionListFromAStarResult(visitedList,startState, targetState)
                    return actionList
                else:
                    for successor in problem.getSuccessors(targetState):
                        state = successor[0]
                        action = successor[1]
                        weight = successor[2]
                        cost =  targetPathCost + weight
                        q.push(aStarPriorityQueueMember(state, targetState, action, cost, heuristic(state, problem)))
示例#22
0
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))
示例#23
0
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)
示例#24
0
    def getLegalMovesWithPriority(self, priorityFunction, n, team):
        """
		The first n legal moves to play for this board ordered by the
		priority given to it by the priority function.
		@param priorityFunction - a function that assigns a priority to a move.
		It must accept a board, move, and string as parameters.
		@param n - the number of moves to return
		@param team - the team. Note: this parameter is not needed to return legality of moves
		but it is useful for ordering them.
		@return a list of n legal moves
		"""
        legalWords = PriorityQueueWithFunction(priorityFunction)
        for word in self.possibleWords:
            if len(legalWords) >= n:
                return legalWords
            if self.isLegalMove(word):
                legalWords.push(self, word, team)
        return legalWords
示例#25
0
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]
示例#26
0
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 []
示例#27
0
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)
示例#28
0
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)
示例#30
0
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]
示例#31
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()
示例#33
0
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()
示例#34
0
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()
示例#35
0
	def search(self, init_board):
		fringe = PriorityQueueWithFunction(lambda state: state.f)

		init_state = State(init_board, 0, self.heuristic_function, [])
		fringe.push(init_state)

		visited = []

		while not fringe.isEmpty():
			# print(f'Open: {len(fringe)}, Close: {len(visited)}')
			item: State = fringe.pop()
			if item in visited:
				continue
			visited.append(item)
			if item.is_goal():
				return item.path

			for move in item.get_legal_action():
				new_board = deepcopy(item.board)
				new_board.next_move = move
				new_board.step()
				new_state = State(new_board, item.g + 1, self.heuristic_function, [move] + item.path)
				fringe.push(new_state)
		return []
示例#36
0
def uniformCostSearch2(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueueWithFunction
    visitedList = {}
    startState = problem.getStartState()
    q = PriorityQueueWithFunction(lambda a: -a.pathCost)
    q.push(StateWithPathCost(startState, 0))
    visitedList[startState] = [None, None]
    while not q.isEmpty():
        swp = q.pop()
        targetState = swp.state
        for successor in problem.getSuccessors(targetState):
            state = successor[0]
            action = successor[1]
            weight = successor[2]
            if state not in visitedList.keys():
                visitedList[state] = [targetState, action]
                q.push(StateWithPathCost(state, weight + swp.pathCost))
            if problem.isGoalState(state):
                return buildActionListFromBFSResult(visitedList,startState, state)
示例#37
0
def uniformCostSearch(problem):
    "*** YOUR CODE HERE ***"
    from util import PriorityQueueWithFunction
    visitedList = {}
    startState = problem.getStartState()
    q = PriorityQueueWithFunction(lambda a: a[1])#proposition to priority
    q.push((startState, 0))
    visitedList[startState] = [None, None, 0]
    while not q.isEmpty():
        targetStateAndCost = q.pop()
        print targetStateAndCost
        targetState = targetStateAndCost[0]
        targetPathCost = targetStateAndCost[1]
        if problem.isGoalState(targetState):
                return buildActionListFromBFSResult(visitedList,startState, targetState)
        else:
            for successor in problem.getSuccessors(targetState):
                state = successor[0]
                action = successor[1]
                weight = successor[2]
                cost =  targetPathCost + weight
                if state not in visitedList.keys()  or visitedList[state][2] > cost: #why?
                    visitedList[state] = [targetState, action, cost]
                    q.push((state, cost))
示例#38
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueueWithFunction
    expanded = set()
    from util import manhattanDistance
    fringe = PriorityQueueWithFunction(manhattanDistance)

    fringe.push((problem.getStartState(), [], 0))

    while fringe.isEmpty != True:
        current = fringe.pop()

        if current[0] in expanded:
            continue

        expanded.add(current[0])

        if problem.isGoalState(current[0]):
            return current[1]

        successor = problem.getSuccessors(current[0])
        for s in successor:
            fringe.push((s[0], current[1] + [s[1]], current[2] + s[2]))
示例#39
0
def cornersHeuristic(state, problem):
  """
  A heuristic for the CornersProblem that you defined.
  
    state:   The current search state 
             (a data structure you chose in your search problem)
    
    problem: The CornersProblem instance for this layout.  
    
  This function should always return a number that is a lower bound
  on the shortest path from the state to a goal of the problem; i.e.
  it should be admissible (as well as consistent).
  """
  corners = problem.corners # These are the corner coordinates
  walls = problem.walls # These are the walls of the maze, as a Grid (game.py)
  
  "*** YOUR CODE HERE ***"
  from util import PriorityQueue, PriorityQueueWithFunction
  import heapq
  def negManhatDist(pair):
    return -1 * util.manhattanDistance(pair[0], pair[1]) # negative to find the biggest using minheap
  def manhatDistToPos(point):
    return util.manhattanDistance(position, point)

  totalCost = 0
  position, cornerStatus = state

  cornersList = []
  for i in xrange(len(cornerStatus)):
    if cornerStatus[i] is False: # unvisited
      cornersList.append(corners[i])

  if len(cornersList) == 0:
    return 0
  elif len(cornersList) == 1:
    return util.manhattanDistance(position, corners[0])

  furthest = PriorityQueueWithFunction(negManhatDist)
  for corner1 in cornersList:
    for corner2 in cornersList:
      if corner1 == corner2:
        continue
      else:
        furthest.push((corner1, corner2))

  maxDist, pair = heapq.heappop(furthest.heap) # !!maxDist is negative
  candidates = []
  candidates.append(pair)
  while not furthest.isEmpty():
    nextVal, nextPair = heapq.heappop(furthest.heap)
    if nextVal == maxDist:
      candidates.append(nextPair)
    else:
      break
  maxDist = -maxDist # Turn back to positive
  totalCost += maxDist
  closest = PriorityQueueWithFunction(manhatDistToPos)
  ## Find closest point to current position
  for candidate in candidates:
    closest.push(candidate[0])
  minDist, pair = heapq.heappop(closest.heap)
  totalCost += minDist
  return maxDist + minDist
示例#40
0
 def  __init__(self, priorityFunction):
   PriorityQueueWithFunction.__init__(self,priorityFunction)        # super-class initializer
示例#41
0
 def push(self, item, priority=0):
   print self,item
   PriorityQueueWithFunction.push(self, item) #Ignoring Priority
示例#42
0
class AstarSearch:
    def __init__(self,problem,shoot):
        self.numExpandedNodes = 0
        self.problem = problem
        self.frontier = PriorityQueueWithFunction(self.fcost)
        self.timeOnHeuris = 0
        self.timeOnTotal = 0
        self.shoot = shoot

    def run(self):
        "estimate running time of A*"

        if self.problem.goalState == []:
            print '*** No goals, no actions'
            print '\n'
            return []

        t1 = time()
        (result,nNodes) = self.Astar()
        t2 = time()
        self.timeOnTotal = t2 - t1
        #print "Explored %d nodes" % len(nodes)

        if result == False:
            print '*** Could not find a path, no actions'
            print '\n'
            return []

        retActions = []
        initPos = result[0]
        prevPos = initPos
        for s in result:
            if s == initPos:
                continue
            (x,y) = prevPos[0]
            d = prevPos[1]
            states = [(x+neigh[d][0][0],y+neigh[d][0][1]),
                    (x+neigh[d][1][0],y+neigh[d][1][1]),
                    (x+neigh[d][2][0],y+neigh[d][2][1]),
                    (x+neigh[d][3][0],y+neigh[d][3][1])]
            #states = [(x,y+1),(x-1,y),(x,y-1),(x+1,y)] # u-0 l-1 d-2 r-3
            #print '----------'
            #print 'curPos:'
            #print s
            #print 'prev->nextStates:'
            #print states
            if s[0] == states[0]:
                retActions = retActions + ['Forward']
            if s[0] == states[1]:
                retActions = retActions + ['TurnLeft','Forward']
            if s[0] == states[2]:
                retActions = retActions + ['TurnRight','Forward']
            if s[0] == states[3]:
                retActions = retActions + ['TurnLeft','TurnLeft','Forward']
            prevPos = s

        if self.shoot == True:
            retActions.insert(-2,'Shoot')

        #print '------------------------------------------'
        print 'path:'
        print result
        #print '------------------------------------------'
        print 'action sequence:'
        print retActions
        print '\n'
        return (retActions)


    def fcost(self, path):
        if len(path) > 0:
            endOfPath = path[-1]
            th1 = time()
            heuristic = self.problem.heuristic(endOfPath)
            th2 = time()
            self.timeOnHeuris = self.timeOnHeuris + (th2-th1)
            return len(path) - 1 + heuristic
        else:
            return 0

    def Astar(self):
        "Based on algorithm given in AI class"
        explored = set()
        initialPath = [self.problem.initialState]
        # Priority queue
        self.frontier.push(initialPath)
        while True:
            #print "*debug* numExplored = %d" % len(explored)
            if len(explored) > NMAX:
                return (False,NMAX)
            if self.frontier.isEmpty():
                return (False,len(explored))
            # This is the 'remove_choice' line from the algorithm
            path = self.frontier.pop()
            s = path[-1]
            explored.add(s[0])
            if self.problem.goalTest(s):
                return (path,len(explored))
            #(states, actions) = self.problem.nextStates(s)
            #for ind,ns in states.items():
            for ns in self.problem.nextStates(s):
                if ns[0] not in explored:
                    newPath = path + [ns]
                    self.frontier.push(newPath)
                    explored.add(ns[0])