Example #1
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    # Define a funcao que define o custo da lista de acoes
    def ordenaCustos(no):
        acoes = []  # Cria lista de acoes
        if no is None:
            return  # Retorna se caminho estiver vazio (estado inicial)
        acoes = list(no[2])  # Clona lista de acoes do caminho
        custoAcoes = problem.getCostOfActions(acoes)
        custoHeuristico = heuristic(no[0], problem)
        return custoAcoes + custoHeuristico  # Retorna custos final (custo real + custo herusitica)

    # ordenaCustos = lambda path: problem.getCostOfActions([x[1] for x in path][1:])

    # Initializa fila de prioridade com o callback
    filaPrioridade = util.PriorityQueueWithFunction(ordenaCustos)

    # Array de coordenadas ja visitadas
    coordVisitados = []
    # No de inicio  (coordenada do no, direcao, caminho percorrido ate este no)
    noInicial = (problem.getStartState(), None, [])
    # Insere o primeiro inicial na lista de nos
    filaPrioridade.push(noInicial)

    # Itera ate que a fila esteja vazia
    while not filaPrioridade.isEmpty():
        atual = filaPrioridade.pop()  # Remove o no do topo da fila
        atualCoord = atual[0]  # Guarda a coordenada do no atual
        # atualAcao = atual[1]                        # Guarda a acao (direcao) pela qual se chegou no no atual
        atualCaminho = atual[
            2]  # Guarda o caminho ate ter chegado neste no atual
        if (atualCoord not in coordVisitados
            ):  # Se o no atual ainda nao foi visitado, continuar
            coordVisitados.append(
                atualCoord)  # Adiciona a coord do atual na lista de visitados
            if (problem.isGoalState(atualCoord)
                ):  # Se eh o objetivo, retorna o caminho ate chegar neste no
                return atualCaminho
            sucessores = problem.getSuccessors(
                atualCoord)  # Encontrar todos os nos vizinhos (sucessores)
            for sucessor in sucessores:  # Expande os nos vizinhos, na sequencia da lista
                if sucessor[
                        0] not in coordVisitados:  # Se o vizinho ainda nao foi visitado, coloca na lista
                    filaPrioridade.push((sucessor[0], sucessor[1],
                                         atualCaminho + [sucessor[1]]))
    return []
Example #2
0
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"
    print("Start:", problem.getStartState())
    print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
    print("Start's successors:",
          problem.getSuccessors(problem.getStartState()))

    explored = []
    cost = lambda apath: problem.getCostOfActions(x[1] for x in apath)
    fringe = util.PriorityQueueWithFunction(cost)
    #fringe = util.PriorityQueueWithFunction(len) #if cost =1  # define the fringe as a Stack. You can check util.py                            ##
    fringe.push([(problem.getStartState(), "Stop", 0)
                 ])  # adding the first node into the fringe
    # please note that each node is represented using the path from the starting node to the it
    while not fringe.isEmpty():
        # print ("fringe: ", fringe.heap)
        path = fringe.pop(
        )  # pop a node from the fringe                                                     ##
        # print "path len: ", len(path)
        # print "path: ", path

        s = path[len(path) - 1]
        s = s[0]
        # print "s: ", s
        if problem.isGoalState(s):
            # print "FOUND SOLUTION: ", [x[1] for x in path]
            return [x[1] for x in path][1:]

        if s not in explored:
            explored.append(
                s)  # append the state to explored                         ##
            # print "EXPLORING: ", s

            for successor in problem.getSuccessors(s):
                # print "SUCCESSOR: ", successor
                if successor[0] not in explored:
                    successorPath = path[:]
                    successorPath.append(successor)
                    # print "successorPath: ", successorPath
                    fringe.push(
                        successorPath
                    )  # push the sucessor Path into fringe         ##
                    # else:
                    # print successor[0], " IS ALREADY EXPLORED!!"

    return []
    util.raiseNotDefined()
Example #3
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "that's my task Search project"
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  print("Start:", problem.getStartState())
  print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
  print("Start's successors:", problem.getSuccessors(problem.getStartState()))
  explored = []
  # cost function
  fn = lambda path: problem.getCostOfActions(x[1] for x in path) + heuristic(x[1] for x in path) 
  fringe = util.PriorityQueueWithFunction(fn)
  # adding the first node into the fringe
  fringe.push([(problem.getStartState(), "Stop", 0)])
  # please note that each node is represented using the path from the starting node to the it
  while not fringe.isEmpty():
        # print ("fringe: ", fringe.heap)

    path = fringe.pop()  # pop a node from the fringe

    # print "path len: ", len(path)
    # print "path: ", path
    # print(path)
    # print(len(path))
    print(fringe)
    s = path[len(path) - 1]
    s = s[0]
    # print "s: ", s
    if problem.isGoalState(s):
        # print "FOUND SOLUTION: ", [x[1] for x in path]
        return [x[1] for x in path][1:]

    if s not in explored:
        explored.append(s)  # append the state to explored
        # print "EXPLORING: ", s

        for successor in problem.getSuccessors(s):
            # print "SUCCESSOR: ", successor
            if successor[0] not in explored:
                successorPath = path[:]
                successorPath.append(successor)
                # print "successorPath: ", successorPath
                # push the sucessorPath into fringe
                fringe.push(successorPath)
        # else:
        # print successor[0], " IS ALREADY EXPLORED!!"

  return []
  util.raiseNotDefined()
Example #4
0
def AStar_search(problem, heuristic=nullHeuristic):

    """
        Search the node that has the lowest combined cost and heuristic first.
        Return the route as a list of nodes(Int) iterated through starting from the first to the final.
    """
    def f(node):
        return node.path_cost + heuristic(node.state,problem)

    start_no = problem.getStartState()    

    start_node = Node(start_no,start_no,0,start_no,0)
    frontier = util.PriorityQueueWithFunction(f)
    frontier.push(start_node)
    expanded_list = []

    while(not frontier.isEmpty()):
        current_node = frontier.pop()
        if current_node.state in expanded_list:
            continue
        if(problem.isGoalState(current_node.state)):
            goal_node = current_node
            break
        else:
            expanded_list.append(current_node.state)
            succesors = problem.getSuccessors(current_node.state)
            for s in succesors:
                if s[0] in expanded_list:
                    continue
                else:
                    frontier.push(Node(s[0],s[0],current_node.path_cost+s[2],current_node,0))    
    # now extract the list from the goal node

    solution = [] 

    temp = goal_node
    current_no = temp.state
    while(current_no != start_no):
        solution.append(current_no)
        temp = temp.parent_node
        current_no = temp.state

    solution.append(start_no)
    solution.reverse()

    return solution

    # util.raiseNotDefined()
Example #5
0
def uniformCostSearch(problem):
    """Search the node of least total cost first.
     python pacman.py -l mediumMaze -p SearchAgent -a fn=ucs
     python pacman.py -l mediumDottedMaze -p StayEastSearchAgent
     python pacman.py -l mediumScaryMaze -p StayWestSearchAgent
     """
    # TODO Problem 3: UCS
    """
    For Uniform Cost Search, a Priority Queue is used as the container with a function that gets the cost of going
    through the route from the start state to the state of that node. Utilizes the second element of each successor.
    """
    def cost_function(node):
        return problem.getCostOfActions(node[1])

    container = util.PriorityQueueWithFunction(cost_function)
    return search(problem, container)
Example #6
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    frontier = util.PriorityQueueWithFunction(lambda x: x[1]+heuristic(x[0], problem))
    visited = set(problem.getStartState())
    frontier.push((problem.getStartState(),0, []))
    solution_found = False
    while not solution_found:
        expand_element, previous_cost, movelist = frontier.pop()
        if problem.isGoalState(expand_element):
            return movelist
        else:
            successors = problem.getSuccessors(expand_element)
            for successor_state, action, cost in successors:
                if successor_state not in visited:
                    visited.add(successor_state)
                    frontier.push((successor_state, previous_cost + cost, movelist + [action]))
Example #7
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    func = lambda x: heuristic(x[0], problem)

    q = util.PriorityQueueWithFunction(func)
    current_state = problem.getStartState()
    q.push((current_state, []))
    visited = []
    while not q.isEmpty():
        current_state, path = q.pop()
        visited.append(current_state)
        if problem.isGoalState(current_state):
            return path
        for i in problem.getSuccessors(current_state):
            if not i[0] in visited:
                q.push((i[0], path + [i[1]]))
Example #8
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    #util.raiseNotDefined()
    def cost_astar(current_node):
        # here the heuristic which is used to compute Astar (Manhattan/ Euclidean dist) is used from searchAgents package
        # which takes two parameters the position and the problem
        cost = problem.getCostOfActions(current_node[1]) + heuristic(
            current_node[0], problem)
        return cost

    nodeDataStructure = util.PriorityQueueWithFunction(cost_astar)
    path = commonSearch(problem, nodeDataStructure)
    #print "PATH:",path
    return path
Example #9
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    def calculateUniformSearchCost(pathCost):
        start = 3
        totalCost = 0.0
        length = len(pathCost)
        while start < length:
            y = pathCost[start]
            totalCost += y[2]
            start += 1
        return totalCost

    return graphSearch(
        problem, util.PriorityQueueWithFunction(calculateUniformSearchCost))
Example #10
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    current, cost = problem.getStartState(), 0
    costfunction = lambda state: path[state][2] + cost
    fringe, explored, path = util.PriorityQueueWithFunction(
        costfunction), set(), {
            current: [None, None, 0]
        }
    fringe.push(current)
    while not fringe.isEmpty():
        current = fringe.pop()
        # check if current is goal
        if problem.isGoalState(current):
            state = current
            # get current's parent and action required from dict
            actions, parent = [path[state][0]], path[state][1]
            # parent is None only at the starting state
            while parent is not None and path[parent][0] is not None:
                # append each action required and get an upper parent
                actions.append(path[parent][0])
                parent = path[parent][1]
            # went backwards so actions should be parsed in reverse
            actions.reverse()
            return actions
        if current not in explored:
            explored.add(current)
            nearStates = problem.getSuccessors(current)
            for state in nearStates:
                child, direction, cost = state
                fringenodes = [node[2] for node in fringe.heap]
                if child not in explored and child not in fringenodes:
                    # add child to dict with action required, parent and its path cost
                    path[child] = [direction, current, costfunction(current)]
                    # add child in priority queue with priority its path cost
                    fringe.push(child)
                elif child in fringenodes:
                    # child exists in fringe, another path is found with cost newcost
                    # newcost is equal to the parent's cost plus the cost of the new action
                    newcost = costfunction(current)
                    # checks if child's cost in dict is greater than the new
                    if path[child][2] > newcost:
                        # replace the child's cost with the better newcost in dict and fringe
                        path[child] = [direction, current, newcost]
                        fringe.update(child, newcost)
    util.raiseNotDefined()
    return False
Example #11
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  if(problem.isGoalState(problem.getStartState())):
    return ['Stop']
  
  fila = util.PriorityQueueWithFunction(lambda x: x[2] + heuristic(x[0], problem))

  final = None
  inicial = problem.getStartState()

  caminho = []
  predecessores = {}
  visitados = {}

  visitados[inicial] = True
  fila.push((inicial, None, 0))

  while fila.isEmpty() == False:
    
    aux = fila.pop()
    u = aux[0]

    if(problem.isGoalState(u)):
      final = aux
      break

    for adj in problem.getSuccessors(u):
      v = adj[0]

      if not(v in visitados):

        fila.push((adj[0], adj[1], aux[2]+adj[2]))
        visitados[v] = True

        if not(v in predecessores):
          predecessores[v] = aux

  it = final[0]
  caminho.insert(0, final[1])

  while predecessores[it][0] != inicial:
    caminho.insert(0, predecessores[it][1])
    it = predecessores[it][0]


  return caminho
Example #12
0
    def aStarSearch(self, startPosition, gameState, goalPositions, avoidPositions=[], returnPosition=False):
        """
        This is Astar function which returns the path to the goal positons and avoiding the avoid positions
        """
        walls = gameState.getWalls()

        walls = walls.asList()

        actions = [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]
        actionVec = [Actions.directionToVector(action) for action in actions]
        actionVec = [tuple(int(number) for number in vector) for vector in actionVec]

        # Each node of the graph is stored as a tuple (Position, path, total cost)_

        currentPos, currentPath, currentCost = startPosition, [], 0

        # we use the priority queue with the implemented huesristic : sum of distances to goals and 100 times distance to avoid positon

        queue = util.PriorityQueueWithFunction(lambda x: x[2] +  # Total cost so far
                                                         (100) * self.getMazeDistance(startPosition, x[0]) if
        x[0] in avoidPositions else 0 +  # Avoid enemy locations
                                    sum([self.getMazeDistance(x[0], Pos) for Pos in
                                         goalPositions]))

        # we put all visited locations in an open list
        visited = set([currentPos])

        while currentPos not in goalPositions:

            possiblePos = [((currentPos[0] + vector[0], currentPos[1] + vector[1]), action) for
                           vector, action in zip(actionVec, actions)]
            legalPositions = [(position, action) for position, action in possiblePos if position not in walls]

            for position, action in legalPositions:
                if position not in visited:
                    visited.add(position)
                    queue.push((position, currentPath + [action], currentCost + 1))

            if len(queue.heap) == 0:
                return None
            else:
                currentPos, currentPath, currentCost = queue.pop()

        if returnPosition:
            return currentPath, currentPos
        else:
            return currentPath
Example #13
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    # Closed nodes, initially empty
    astarClosed = []

    # Frontier nodes, initialize with start State
    astarFrontier = util.PriorityQueueWithFunction(
        lambda state:
        state.getAccumulatedCost() + heuristic(state.getState(), problem)
    )
    astarFrontier.push(
        SearchNode()
            .setState(problem.getStartState())
    )

    while True:
        # If Frontier is Empty -> return failure
        if astarFrontier.isEmpty():
            goalState = None
            break

        # Pop Node from Frontier
        currentState = astarFrontier.pop()

        # If Node is goal state -> return Node
        if (problem.isGoalState(currentState.getState())):
            goalState = currentState
            break

        # If currentState was not already closed, add to closed and explore (add its successors to frontier)
        if currentState not in astarClosed:
            astarClosed.append(currentState)
            for successor in problem.getSuccessors(currentState.getState()):
                astarFrontier.push(
                    SearchNode()
                        .setState(successor[0])
                        .setAction(successor[1])
                        .setParent(currentState)
                        .setAccumulatedCost(currentState.getAccumulatedCost() + successor[2])
                )

    # If there's a solution, return actions, otherwise exit
    if goalState:
        return getActionsFromGoalState(goalState)
    else:
        print("This problem is not solvable")
        exit(0)
Example #14
0
def aStarSearch(grid,
                dictionary,
                heuristic=nullHeuristic,
                choiceMult=1,
                choiceMin=1):
    visited = []  # Swapped to dict for faster accessing
    sorter = util.PriorityQueueWithFunction(heuristic)
    sorter.push((grid, 0))

    iterations = 0
    times_visited = 0
    while not sorter.isEmpty():
        gridState, depth = sorter.pop()
        iterations += 1
        #if iterations > 2:
        #    break
        # print(f"iteration {iterations}: testing state at depth {depth} with grid:")
        # print(str(gridState))
        if gridState in visited:
            times_visited += 1
            continue
        visited.append(gridState)
        #print(f"Scanning {gridState}", end='\t')
        if gridState.isComplete() and gridState.isValid(
                dictionary
        ):  # fine to test it this way since the python and statement will only test the second case if the first one is true
            #print("DONE")
            #h = hpy()
            #print(h.heap())
            #print(f'Found same state {times_visited} times.')
            return gridState, iterations

        successors = gridState.getNextGridStates(
            dictionary,
            int(choiceMult * (depth + 1)) + choiceMin)
        random.shuffle(successors)
        #print(f"Expanding from {gridState}")
        for newState in successors:
            #print(newState)
            if newState.isValid(dictionary):
                sorter.push((newState, depth + 1))
            else:
                del (newState)
        #del(gridState)
    #print(f'Found same state {times_visited} times.')

    return None, iterations
Example #15
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    def priorityFunction(node):
        return heuristic(node[0], problem)+node[2]
    closed = []
    fringe = util.PriorityQueueWithFunction(priorityFunction)
    fringe.push((problem.getStartState(),list(),0))
    while not fringe.isEmpty():
        node = fringe.pop()
        if problem.isGoalState(node[0]):
            return node[1]
        elif node[0] not in closed:
            closed.append(node[0])
            for child_node in problem.getSuccessors(node[0]):
                temp_node = (child_node[0], node[1] + [child_node[1]], node[2] + child_node[2])
                fringe.push(temp_node)
    return []
Example #16
0
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    explored = set()
    frontier = util.PriorityQueueWithFunction(lambda node: node.pathCost)
    frontier.push(util.Node((problem.getStartState(), None, None)))
    while not frontier.isEmpty():
        node = frontier.pop()
        state = node.state
        if problem.isGoalState(state):
            return node.getPath()
        if state in explored:
            continue
        explored.add(state)
        for successor in problem.getSuccessors(state):
            if successor[0] not in explored:
                frontier.push(util.Node(successor, node))
    return []
Example #17
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."

    "*** YOUR CODE HERE ***"

    def aStarHeuristic(item):
        position, direction, totalCost, parent = item
        return totalCost + heuristic(
            position, problem
        )  #combines actual cost of getting to node with cost of heuristic(manhatten)

    pQWF = util.PriorityQueueWithFunction(aStarHeuristic)
    return findGoal(problem, pQWF)

    "Bonus assignment: Adjust the getSuccessors() method in CrossroadSearchAgent class"
    "in searchAgents.py and test with:"
    "python pacman.py -l bigMaze -z .5 -p CrossroadSearchAgent -a fn=astar,heuristic=manhattanHeuristic "
Example #18
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    def priority_func(path):
        act_cost_gn = problem.getCostOfActions(path[1])
        est_cost_fn = heuristic(path[0], problem)
        return act_cost_gn + est_cost_fn

    frontier = util.PriorityQueueWithFunction(
        priority_func)  # Priority Queue with priority function based on
    # cost of path.
    closed = set(
    )  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state into the Priority Queue.
    return execute_common_search_logic(frontier, closed, problem)
Example #19
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 ***"
    fringeStrategy = util.PriorityQueueWithFunction(lambda x: -len(x[1]))
    return graphSearch(problem, fringeStrategy, nullHeuristic)
Example #20
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    def pushByCostHeuristic(collection,
                            element,
                            heuristic=heuristic,
                            problem=problem):
        fn = element[2] + heuristic(element[0], problem)
        collection.push(((element[0], element[1], element[2]), fn))

    def priorityFunction(stateSpace):
        return stateSpace[1]

    collection = util.PriorityQueueWithFunction(priorityFunction)
    result = search(problem, collection, pushByCostHeuristic)
    return result
Example #21
0
def closetPosition(fromPosition, positions):
    if len(positions) == 0:
        return None

    def fn((pos, dis)):
        return dis

    # let the PriorityQueueWithFunction do the sort
    options = util.PriorityQueueWithFunction(fn)
    for position in positions:
        # calc the cost
        euclidean_distance = euclideanDistance(fromPosition, position)
        # push with the cost
        options.push((position, euclidean_distance))

    # get the top that is the lowest distance
    return options.pop()
Example #22
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """
    Search the node that has the lowest combined cost and heuristic first.
    python pacman.py -l bigMaze -z .5 -p SearchAgent -a fn=astar,heuristic=manhattanHeuristic
    """
    # TODO Problem 4: A*S
    """
    For A* search, a Priority Queue is used as the container with a function that gets the cost of going
    through the route from the start state to the state of that node, as UCS, 
    but also adds the Heuristic of the successor state.
    """
    def cost_function(node):
        return problem.getCostOfActions(node[1]) + heuristic(
            node[0][0], problem)

    container = util.PriorityQueueWithFunction(cost_function)
    return search(problem, container)
Example #23
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    start_state = problem.getStartState()
    pqueue = util.PriorityQueueWithFunction(lambda x: x[2]+heuristic(x[0],problem)) #same as UCS. Just added heuristic to
    pqueue.push((start_state, None, 0))                                             #cost to reach the state. So if x is that state
    cost = 0                                                                    #then x[2] is the cost to reach that state, and heuristic(state,problem) is the heuristic.
    visited = []                                                                #Hint to Heuristic function parameters got from nullHeuristic function definition above
    path = []
    parentSeq = {}
    parentSeq[(start_state, None, 0)] = None
    while pqueue.isEmpty() == False:
        current_fullstate = pqueue.pop()
        # print current_fullstate
        if (problem.isGoalState(current_fullstate[0])):
            break
        else:
            current_state = current_fullstate[0]
            if current_state not in visited:
                visited.append(current_state)
            else:
                continue
            successors = problem.getSuccessors(current_state)
            for state in successors:
                cost = current_fullstate[2] + state[2];
                # print state,cost
                if state[0] not in visited:
                    pqueue.push((state[0], state[1],cost))
                    # parentSeq[state] = current_fullstate
                    parentSeq[(state[0], state[1])] = current_fullstate

    child = current_fullstate

    while (child != None):
        path.append(child[1])
        if child[0] != start_state:
            child = parentSeq[(child[0], child[1])]
        else:
            child = None
    path.reverse()
    return path[1:]


    return []

    util.raiseNotDefined()
Example #24
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    def priorityFunctionForUniformCostSearch(n):
        actions = []
        for element in n:
            act = element[1]
            if act != "Stop":
                actions.append(act)

        totalCost = problem.getCostOfActions(actions)
        return totalCost

    open = util.PriorityQueueWithFunction(priorityFunctionForUniformCostSearch)
    open.push([(problem.getStartState(), "Stop", 0)])
    visited = []

    while not open.isEmpty():
        n = open.pop()
        lastTuple = n[len(n) - 1]
        currentState = lastTuple[0]
        actions = []

        if problem.isGoalState(currentState):
            actions = []
            for element in n:
                act = element[1]
                if act != "Stop":
                    actions.append(act)
            return actions

        if currentState not in visited:
            visited.append(currentState)

            successors = problem.getSuccessors(currentState)
            for state, action, cost in successors:
                if state not in visited:
                    listOfSuccessors = []
                    for item in n:
                        listOfSuccessors.append(item)
                    listOfSuccessors.append((state, action, cost))
                    open.push(listOfSuccessors)

    return False
Example #25
0
def aStarSearch(problem, heuristic=gpHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"

    # f(x) = g(x) + h(x). f(x) is stored in the fringe.
    def costPlusHeuristic(node):
        g = node.getTotalCost()
        state = node.getState()
        h = heuristic(state, problem)
        return g + h

    fringe = util.PriorityQueueWithFunction(
        costPlusHeuristic)  # stores NODES that we encounter
    firstNode = Node(state=problem.getStartState())
    fringe.push(firstNode)

    explored = []  # stores STATES that have been explored

    while not fringe.isEmpty():
        currentNode = fringe.pop()
        currentState = currentNode.getState()
        isNew = True
        # skip node if we have already explored it
        for e in explored:
            if len(currentState) == len(e) and all(
                [p in e for p in currentState]):
                isNew = False
        if isNew:
            # if at a goal state, backtrace parent nodes to get complete path taken to goal
            if problem.isGoalState(currentState):
                path = deque()
                while currentNode.getParent():
                    path.appendleft(currentNode.getPrevAction())
                    currentNode = currentNode.getParent()
                return path
            # if not at goal state, mark current state as explored and add successors to fringe
            else:
                explored.append(currentState)
                for successors in problem.getSuccessors(currentState):
                    (successor, action) = (successors[0], successors[1])
                    node = Node(state=successor,
                                parent=currentNode,
                                prevAction=action,
                                pathCost=1)
                    fringe.push(node)
Example #26
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"


    from game import Directions, Actions
    pacmanPriorityQueueWithFunction = util.PriorityQueueWithFunction(lambda x: x[2] + heuristic(x[0],problem))
    positionList = {}
    positionListFinal = {}

    currentState = (problem.getStartState(),[],0)
    FoundGoal = problem.isGoalState(currentState[0])

    pacmanPriorityQueueWithFunction.push(currentState)
    positionList[currentState[0]] = 0

    while(FoundGoal != True):
        currentState = pacmanPriorityQueueWithFunction.pop()
        if(problem.isGoalState(currentState[0])):
            FoundGoal = True
            break
        succ = problem.getSuccessors(currentState[0])
        for i in range(0,len(succ)):
            successor = succ[i][0]
            action = succ[i][1]
            totalPath = currentState[1] + [action]
            totalPathCost = heuristic(successor,problem) + problem.getCostOfActions(totalPath)
            if(not (successor in positionList)): 
                pacmanPriorityQueueWithFunction.push((succ[i][0],totalPath,totalPathCost)) 
                positionListFinal[successor] = (currentState[0],action)
                positionList[successor] = totalPathCost
            elif(totalPathCost < positionList[successor]):
                pacmanPriorityQueueWithFunction.push((successor,totalPath,totalPathCost)) 
                positionList[successor] = totalPathCost
                positionListFinal[successor] = (currentState[0], action)
    
    endList = []
    currentState = positionListFinal[currentState[0]]
    while(currentState[0] != problem.getStartState()):
        endList.insert(0,currentState[1])
        currentState = positionListFinal[currentState[0]]

    endList.insert(0,currentState[1])

    return endList
Example #27
0
    def aStarSearch(self, startPosition, gameState, goalPositions, avoidPositions=[], returnPosition=False):
        """
        Finds the distance between the agent with the given index and its nearest goalPosition
        """
        walls = gameState.getWalls()
        width = walls.width
        height = walls.height
        walls = walls.asList()

        actions = [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]
        actionVectors = [Actions.directionToVector(action) for action in actions]
        # Change action vectors to integers so they work correctly with indexing
        actionVectors = [tuple(int(number) for number in vector) for vector in actionVectors]

        # Values are stored a 3-tuples, (Position, Path, TotalCost)

        currentPosition, currentPath, currentTotal = startPosition, [], 0
        # Priority queue uses the maze distance between the entered point and its closest goal position to decide which comes first
        queue = util.PriorityQueueWithFunction(lambda entry: entry[2] +   # Total cost so far
                                               width * height if entry[0] in avoidPositions else 0 +  # Avoid enemy locations like the plague
                                               min(util.manhattanDistance(entry[0], endPosition) for endPosition in goalPositions))

        # Keeps track of visited positions
        visited = set([currentPosition])

        while currentPosition not in goalPositions:

            possiblePositions = [((currentPosition[0] + vector[0], currentPosition[1] + vector[1]), action) for vector, action in zip(actionVectors, actions)]
            legalPositions = [(position, action) for position, action in possiblePositions if position not in walls]

            for position, action in legalPositions:
                if position not in visited:
                    visited.add(position)
                    queue.push((position, currentPath + [action], currentTotal + 1))

            # This shouldn't ever happen...But just in case...
            if len(queue.heap) == 0:
                return None
            else:
                currentPosition, currentPath, currentTotal = queue.pop()

        if returnPosition:
            return currentPath, currentPosition
        else:
            return currentPath
Example #28
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """
    Searches the node that has the lowest combined cost and heuristic first.
    """

    def sortingFn(path):
        """ Returns the cost of a path, that will ultimately be used to sort the Priority Queue.
            Computes cost function for a set of actions in a path combined with the heuristic estimate.    
        """
        actions = [action for _,action,_ in path][1:] # disregards first action STOP for the initial node

        cur_state,_,_ = path[-1] # State to use for determining heuristic

        return problem.getCostOfActions(actions) + heuristic(cur_state, problem) # Overall cost = Cost so far + heuristic

    priority_q = util.PriorityQueueWithFunction(sortingFn) # Initializes a PriorityQueue with a sorting key function

    return generalSearch(problem=problem, structure=priority_q)
Example #29
0
def uniformCostSearch(problem):
    """
    Searches the node of least total cost first. 
    Employs a Priority Queue that takes a sorting function. 
    The sorting function ensures nodes with least cost functions are visited first
    """

    def sortingFn(path):
        """ Returns the cost of a path, that will ultimately be used to sort the Priority Queue.
            Computes cost function for a set of actions in a path.    
        """
        actions = [action for _,action,_ in path][1:] # disregards first action STOP for the initial node

        return problem.getCostOfActions(actions)

    priority_q = util.PriorityQueueWithFunction(sortingFn) # Initializes a PriorityQueue with a sorting key function

    return generalSearch(problem=problem, structure=priority_q)
Example #30
0
def uniformCostSearch(problem):
    """
    uniform cost function = cost of previous action
    """

    # define costFunction
    def costFunction(tuState):
        return problem.getCostOfActions(tuState[1])

    # create priority queue with cost function
    RoutePQ = util.PriorityQueueWithFunction(costFunction)

    # push initial state tuple:(position, list:Route)
    tuStart = problem.getStartState()
    RoutePQ.push((tuStart, []))

    # call genericSearch with problem and data structure
    return genericSearch(problem, RoutePQ)