Example #1
0
def uniformCostSearch(problem):
    from util import PriorityQueue
    statesQueue = PriorityQueue()
    path = genericSearch(problem, statesQueue, "UCSPriority")
    return path

    util.raiseNotDefined()
Example #2
0
def uniformCostSearch(problem):
    """
		Search the node of least total cost first.
		REMEMBER: This is same as the Bread-First Search but with a PriorityQueue instead of a Queue
	"""

    startNode = problem.getStartState()
    frontier = PriorityQueue()
    frontier.push((startNode, [], 0), 0)
    explored = set()

    while not frontier.isEmpty():
        state, actions, cost = frontier.pop()

        if problem.isGoalState(state):
            return actions

        explored.add(state)  # Adding the Node to the explored

        for successor, action, pathCost in problem.getSuccessors(state):
            if successor not in explored:
                frontier.push((successor, actions + [action], cost + pathCost),
                              cost + pathCost)

    return []
Example #3
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    # import the PriorityQueue Data Structure
    from util import PriorityQueue
    nodes = PriorityQueue()
    node_visited = {}
    start_state = problem.getStartState()
    gross_cost = 0 + heuristic(start_state, problem)
    nodes.push((start_state, 0, gross_cost), gross_cost)
    while not nodes.isEmpty():
        (current_state, former_cost, gross_cost) = nodes.pop()
        if problem.isGoalState(current_state):
            temp = current_state
            move_list = []
            while temp != start_state:
                (state, direction) = node_visited[temp]
                temp = state
                move_list.append(direction)
            move_list.reverse()
            return move_list
        next_move = problem.getSuccessors(current_state)
        for moves in next_move:
            (next_state, direction, cost) = moves
            if not node_visited.has_key(next_state):
                node_visited[next_state] = (current_state, direction)
                # push the node into the PriorityQueue
                gross_cost = former_cost + cost + heuristic(
                    next_state, problem)
                nodes.push((next_state, (former_cost + cost), gross_cost),
                           gross_cost)
Example #4
0
def uniformCostSearch(problem):
    from util import PriorityQueue
    fringe = PriorityQueue()
    startState = problem.getStartState()
    fringe.push((startState, [], 0), 0)
    #nextPosition, Directions,moving cost , priority
    stamp = dict()
    # stamp[startState] = 0
    # position and Cost
    #cost of a->G != cost of c->G
    while fringe.isEmpty() == False:
        node = fringe.pop()
        # print 'node 0~2', node[0], node[1], node[2]
        stamp[node[0]] = node[2]
        # print 'stamp, type of dictionary', stamp
        if problem.isGoalState(node[0]) == True:
            return node[1]
        for j in problem.getSuccessors(node[0]):
            if (j[0] not in stamp) or (j[0] in stamp
                                       and node[2] + j[2] < stamp[j[0]]):
                # print stamp[node[0]]+j[2]
                fringe.push((j[0], node[1] + [j[1]], node[2] + j[2]),
                            node[2] + j[2])
                stamp[j[0]] = stamp[node[0]] + j[2]
    return False
Example #5
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """
    Search the node that has the lowest combined cost and heuristic first.
    """
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    frontier = PriorityQueue()
    visited = set()
    path = list()
    path_dic = dict()
    frontier.push((problem.getStartState(), None, 0), 0)
    while not frontier.isEmpty():
        current = frontier.pop()
        if current[0] not in visited:
            visited.add(current[0])
            if problem.isGoalState(current[0]):
                dummy = current
                while dummy in path_dic:
                    path.append(dummy[1])
                    dummy = path_dic[dummy]
                path.reverse()
                return path
            for state in problem.getSuccessors(current[0]):
                if state[0] not in visited:
                    cost = state[2] + heuristic(state[0], problem)
                    node = current
                    while node in path_dic:
                        cost += node[2]
                        node = path_dic[node]
                    frontier.push(state, cost)
                    path_dic[state] = current
    util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic):
    """
    Q1.3
    Search the node that has the lowest combined cost and heuristic first."""
    """Call heuristic(s,problem) to get h(s) value."""
    "*** YOUR CODE HERE ***"
    if problem.isGoalState(problem.getStartState()):
        return []
    """As we need LIFO for DFS"""
    from util import PriorityQueue
    """ Initiliazing state of the problem"""
    Frontier = PriorityQueue()
    """Pushing valid start state (this time we also have to consider priorities """
    Frontier.push(problem.getStartState(), 0)
    """Initializing empty explored set """
    statePath = []
    stateVisited = []
    tempPath = []
    """ Choosing a leaf node to remove it from Frontier"""
    xy = Frontier.pop()
    """Initilaizing one more priority Queue for the path to our current """
    pathCurrent = PriorityQueue()
    """Running the loop until we are not in goal state """
    while not problem.isGoalState(xy):
        """Not a  previosly visited node """
        if xy not in stateVisited:
            stateVisited.append(xy)
            """Getting Successors """
            successorPath = problem.getSuccessors(xy)
            """This is where a major change occurs comapred to other two searches, so to clearly illustrate i used them individually instead of 'paths' """
            for coordinate, direction, cost in successorPath:
                newPath = statePath + [direction]
                """ Getting cost of path with state in hand"""
                costOfPath = problem.getCostOfActions(newPath) + heuristic(
                    coordinate, problem)
                """
                print(costOfPath)"""
                if coordinate not in stateVisited:
                    """
                    print(direction)
                    print(coordinate)
                    """
                    Frontier.push(coordinate, costOfPath)
                    pathCurrent.push(newPath, costOfPath)
        xy = Frontier.pop()
        statePath = pathCurrent.pop()
    return statePath
Example #7
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())
    #print problem.getSuccessors(problem.getSuccessors(problem.getStartState())[0][0])

    "*** YOUR CODE HERE ***"
    closed = []
    from util import PriorityQueue
    fringe = PriorityQueue()
    fringe.push([problem.getStartState(), [], 100000], 100000)
    while 1:
        if fringe.isEmpty():
            return []
        node = fringe.pop()
        #print node[0],
        if problem.isGoalState(node[0]):
            print "goal found"
            # print node
            return node[1]
        isPresent = 0
        for i in closed:
            if i == node[0]:
                isPresent = 1
    #print  node[0] , node[2]
        if isPresent == 0:
            closed.append(node[0])
            successors = problem.getSuccessors(node[0])
            for i in successors:
                newNode = []
                path = []
                for j in node[1]:
                    path.append(j)
            # print i[1] ,
            # print path
                dup = 0
                for j in closed:
                    if j == i[0]:
                        #print "duplicate",
                        dup = 1

                path.append(i[1])

                newNode.append(i[0])
                newNode.append(path)
                newNode.append(node[2] - i[2])
                if dup == 0:
                    fringe.push(newNode, newNode[2])

    util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic):
    # We need priorityqueue as we are implementing aStartSearch
    from util import PriorityQueue

    pqueue = PriorityQueue()

    # take start state and save it in source
    source = problem.getStartState()

    visited = [
    ]  # visited list to make sure, we donot explore already explored nodes

    # get initial children and put them in Queue
    children = problem.getSuccessors(source)
    visited.append(
        source
    )  # Add start state in visited as we have already explored its children
    cnt = 0
    while cnt < len(children):
        child = children[cnt]
        child_pos = child[0]
        child_val = child[2]
        h_val = heuristic(child_pos, problem)
        pqueue.push((child, [], child_val), (child_val + h_val))
        cnt = cnt + 1

    # now take top element of Stack and apply DFS
    while not pqueue.isEmpty():
        top = pqueue.pop()  # pop element with least path from the queue
        node = top[0]
        result = top[1]
        path_val = top[2]
        node_pos = node[0]  # get first element row and column
        node_dir = node[1]

        if problem.isGoalState(node_pos):
            result.append(node_dir)
            return result

        # get successor of first element
        successor = []
        if not node_pos in visited:
            successor = problem.getSuccessors(node_pos)
            visited.append(node_pos)

        cnt = 0
        while cnt < len(successor):
            succ = successor[cnt]
            succ_pos = succ[0]
            succ_val = succ[2]

            if succ_pos not in visited:
                temp_result = [node_dir]
                temp_result = result + temp_result
                h_val = heuristic(succ_pos, problem)
                pqueue.push((succ, temp_result, path_val + succ_val),
                            (path_val + succ_val + h_val))

            cnt = cnt + 1
Example #9
0
def early_execution(network: STN, realization: dict) -> bool:
    ## Bookkeeping for events
    all_uncontrollables = set(network.uncontrollables)
    unused_events = set(network.verts.keys())
    not_scheduled = PriorityQueue()
    final_schedule = {}

    # Mapping from contingent sources to uncontrollables
    contingent_pairs = network.contingentEdges.keys()
    disabled_uncontrollables = {src: sink for (src, sink) in contingent_pairs}

    # Initialize bounds for simulation - starts off with just controllables
    # and zero time point
    controllable_bounds = find_bounds(network)
    true_weight = {}
    for event in controllable_bounds:
        not_scheduled.push(event, controllable_bounds[0])
        true_weight[event] = controllable_bounds[0]
    not_scheduled.addOrDecKey(ZERO_ID, 0)

    # Run simulation
    old_time = 0
    while len(unused_events) > 0:
        current_time, activated_event = not_scheduled.pop()

        # This check ensures that we popped out a valid time_point
        # A better way to deal with this would be to just figure out a way to
        # increase priorities of elements in a heap
        if activated_event in true_weight:
            if true_weight[activated_event] > current_time:
                continue

        unused_events.remove(activated_event)
        final_schedule[activated_event] = current_time

        assert old_time < current_time, "Chronology violated!"

        if activated_event in disabled_uncontrollables:
            # If this is a contingent source, we add the associated uncontrollable sink
            # to the queue
            uncontrollable = disabled_uncontrollables[activated_event]
            delay = realization[uncontrollable]
            not_scheduled.push(uncontrollable, current_time + delay)

        # Update the bounds for all other timepoints
        # We only care about events being moved later in time
        relevant_edges = network.getEdges(activated_event)
        for edge in relevant_edges:
            if (edge.j == activated_event) and (edge.i
                                                not in all_uncontrollables):
                if needs_early_update(edge, activated_event, current_time,
                                      true_weight):
                    lower_bound = current_time - edge.Cij
                    true_weight[edge.i] = lower_bound

        # Keep track of this for next iteration of loop
        old_time = current_time
    # Check if we dispatched succesfully
    return emp.scheduleIsValid(network, final_schedule)
Example #10
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()))
    from util import PriorityQueue
    from game import Directions
    e = Directions.EAST
    w = Directions.WEST
    n = Directions.NORTH
    s = Directions.SOUTH
    # print('class',problem.__class__.__name__)
    q_arr = PriorityQueue()
    visited = {}
    start_state = problem.getStartState()
    info = [start_state, (start_state, 'South', 1),
            int(1)]  # parent, (self info), cost till now
    q_arr.push(info, info[2])
    while q_arr.isEmpty() is False:
        node_info = q_arr.pop()
        # print(node_info)
        node = node_info[1][0]  # info about the present node
        # print('processing node ', node)
        if problem.isGoalState(node):
            visited[node] = node_info
            actions = []
            crawl = node
            # print('Goal Reached: ', crawl)
            while crawl != (visited[crawl]
                            )[0]:  # if the node is not equal to it's parent
                parent = (visited[crawl])[0]
                direction = (visited[crawl])[1][1]
                if direction is 'South':
                    direction = s
                elif direction is 'North':
                    direction = n
                elif direction is 'East':
                    direction = e
                elif direction is 'West':
                    direction = w

                crawl = parent
                actions = actions + [direction]

            # print(list(reversed(actions)))
            return list(reversed(actions))
            # return the list of actions

        if node not in visited:  # process the children
            visited[node] = node_info
            # print('Successors: ', problem.getSuccessors(node))
            for i in problem.getSuccessors(node):
                cost = float(i[2]) + node_info[2]
                child_info = [node, i, cost]
                # child_info[1][2] = child_info[1][2] + node_info[1][2]
                q_arr.push(child_info,
                           child_info[2])  # Add costs till that node
    return []
Example #11
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    #print "STARTASTARSEARCH"
    #print ""
    #print ""

    from game import Directions
    from util import PriorityQueue
    myFringe = PriorityQueue()
    exploredStates = set()
    # heuristic(problem.getStartState(), problem)
    # #print "HEURISTIC: ", heuristic(problem.getStartState(), problem)

    startState = [[problem.getStartState(), -1], []]
    myFringe.push(startState, heuristic(problem.getStartState(), problem))
    if (problem.isGoalState(problem.getStartState())):

        return Directions.STOP
    #loop forever (only return escapes.)
    while (True):
        #if fringe is empty, we failed to add another item.
        if (myFringe.isEmpty()):
            #print 'failure fringe is empty.'
            return ['failure']
        #if not empty, take most recent one, check if goal, return how got there.
        else:
            poppedState = myFringe.pop()
            if (problem.isGoalState(poppedState[0][0])):
                answerArray = []
                #for length of array, #print poppedStates directionArray,
                # populate answerArray with Directions to reach goal.
                for i in range(0, len(poppedState[1])):
                    if (poppedState[1][i] == "North"):
                        answerArray.append(Directions.NORTH)
                    if (poppedState[1][i] == "South"):
                        answerArray.append(Directions.SOUTH)
                    if (poppedState[1][i] == "East"):
                        answerArray.append(Directions.EAST)
                    if (poppedState[1][i] == "West"):
                        answerArray.append(Directions.WEST)
                #print len(answerArray)
                return answerArray
            #if poppedState not in fringe (shouldn't be we just popped it.) or exploredState (should not explore repeated states)
            # then add it to explored, and add children to the fringe.
            if (not (poppedState[0][0] in exploredStates)):
                exploredStates.add(poppedState[0][0])
                #print "NODE EXPLORED: ", poppedState[0][0]
                #call successor only on coordinates.
                newSuccessors = problem.getSuccessors(poppedState[0][0])
                newPathGuide = poppedState[1]
                #get all successors, put them all in fringe. with how to get there.
                for i in range(0, len(newSuccessors)):
                    newPathGuide.append(newSuccessors[i][1])
                    nextNode = [newSuccessors[i], newPathGuide]
                    nextNodeValue = (nextNode[0][2]) + (heuristic(
                        nextNode[0][0], problem))
                    myFringe.push(nextNode, nextNodeValue)
                    newPathGuide = newPathGuide[:-1]
Example #12
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    from util import PriorityQueue

    # Creates an empty PriorityQueue.
    open_list = PriorityQueue()

    visited_list = []
    path = []
    priority = 0    # Initializes the priority to 0.

    start_position = problem.getStartState()

    # Pushes the start position to the PriorityQueue.
    open_list.push((start_position, path), priority)

    while not open_list.isEmpty():

        current_node = open_list.pop()
        position = current_node[0]
        path = current_node[1]

        # Pushes the current position to the visited list if it is not visited.
        if position not in visited_list:
            visited_list.append(position)

        # Returns the final path if the current position is goal.
        if problem.isGoalState(position):
            return path

        # Gets successors of the current node.
        successors = problem.getSuccessors(position)

        # We defined a function in order to get the priority of an existing node in the open list.
        def getPriorityOfNode(priority_queue, node):
            for item in priority_queue.heap:
                if item[2][0] == node:
                    return problem.getCostOfActions(item[2][1])

        # Pushes the current node's successors to the PriorityQueue if they are neither in the visited list nor in the open list.
        for item in successors:
            if item[0] not in visited_list and (item[0] not in (node[2][0] for node in open_list.heap)):
                new_path = path + [item[1]]
                new_priority = problem.getCostOfActions(new_path)
                open_list.push((item[0], new_path), new_priority)

            # If the successor is already in the open list, we check its priority.
            elif item[0] not in visited_list and (item[0] in (node[2][0] for node in open_list.heap)):
                old_priority = getPriorityOfNode(open_list, item[0])
                new_priority = problem.getCostOfActions(new_path)

                # Updates priority of the successor if the value of new priority is less than that of the old one.
                if old_priority > new_priority:
                    new_path = path + [item[1]]
                    open_list.update((item[0], new_path), new_priority)

    util.raiseNotDefined()
Example #13
0
def uniformCostSearch(problem):

    #create a priority queue
    from util import PriorityQueue
    pQueue = PriorityQueue()

    #get the starting vertex, push it on the priority queue
    startingVertex = (problem.startingState(), "", 0)
    pQueue.push(startingVertex, startingVertex[2])

    #create a dict that stores the parents of a node
    parents = {}

    #set of visited nodes
    visited = set(startingVertex[0])

    #final path to be returned
    path = []

    #used to calculate cost
    cost = 0

    while pQueue:
        v = pQueue.pop()
        #print v

        #get successors of the coordinates of v
        for u in problem.successorStates(v[0]):

            #if the coordinate hasn't been visited then
            #visit it, push it, and set parent coordinate and direction
            if not u[0] in visited:
                visited.add(u[0])

                #arithmetic to set the cost equal to u + it's parents cost
                if parents.has_key(v[0]):
                    par = parents[v[0]]
                    cost = u[2] + par[1]
                else:
                    cost = u[2]

                #push the cost upstream
                parents[u[0]] = (v, cost)
                pQueue.push(u, cost)

                #if we found the goal then backtrace using the parent dict
                #and prepend to the final path with the next nodes corresponding
                #directions
                if problem.isGoal(u[0]):

                    curr = u
                    while curr != startingVertex:
                        path.insert(0, curr[1])
                        par = parents[curr[0]]
                        curr = par[0]

                    #return the path of directions

                    return path
Example #14
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    fringe = PriorityQueue()


    exploredNodes = []  #All visited states
    path = []   #the path followed from the start node

    nodeState = problem.getStartState()
    # in case the stast state is also a goal state
    if problem.isGoalState(nodeState):
        return path

    #the path cost at this point is 0 since we are exploring the first node of the graph
    priority = 0
    fringe.push((nodeState,path),priority)

    while (True):

        if fringe.isEmpty():
            return []

        currentNode, path = fringe.pop()
        exploredNodes.append(currentNode)       #put the currentNode in the list of the explored nodes

        #uncomment lines 230 and 231 so that the program works properly with the autograder
        #and comment lines 241-242
        #if problem.isGoalState(currentNode):    #if the node is indeed a goal
        #    return path

        #get currentNode's successors
        successors = problem.getSuccessors(currentNode)

        if successors:
            for successor in successors:
                if (successor[0] not in exploredNodes and successor[0] not in (state[2][0] for state in fringe.heap)):

                    #comment here for the program to work right with the autograder
                    if problem.isGoalState(successor[0]):
                       return path + [successor[1]]

                    nPath = path + [successor[1]]
                    priority = problem.getCostOfActions(nPath)
                    fringe.push((successor[0], nPath), priority)

                #in case the node already exists in the fringe we check which one has the highest priority/path cost and
                #peak the lowest one
                elif (successor[0] not in exploredNodes and successor[0] in (state[2][0] for state in fringe.heap)):
                    for state in fringe.heap:
                        if (state[2][0] == successor[0]):
                            fNodePriority = problem.getCostOfActions(state[2][1])
                    succPriority = problem.getCostOfActions(path + [successor[1]])

                    if(fNodePriority > succPriority):
                        nPath = path + [successor[1]]
                        fringe.update((successor[0], nPath), succPriority)
Example #15
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    #cette algo implemente l algo astar en utilisant la structure priority queue
    #qui est une file prenant en compte une priorite pour chaque noeud et qui va s organiser de telle sorte
    #que quand on defile une valeur, c est toujours cellee avec la plus basse valeur d evaluation qui va etre retournee
    from game import Directions
    n = Directions.NORTH
    s = Directions.SOUTH
    w = Directions.WEST
    e = Directions.EAST
    from util import PriorityQueue

    frontier = PriorityQueue()  # declare la file de priorite
    start = problem.getStartState()  # initialisation

    frontier.push(start, 0)

    came_from = {
    }  # correspond a meta dans dfs et bfs, sert a etablir la liste d'action
    cost_so_far = {
    }  # g(n) : sert a donner le cout du chemin parcouru jusquau noeud actuel

    #Set start state in the PriorityQueue
    came_from[start] = (None, None)
    cost_so_far[start] = 0

    while not frontier.isEmpty():
        current = frontier.pop(
        )  #defile un element (ce sera l element avec l'evaluation la plus faible pour permettre de defiler en priorite des noeuds interessants qui se rapprochent de l'objectif)

        if problem.isGoalState(
                current
        ):  # si l'element est l'objectif, on retourne la liste d'action
            return action_path(current, came_from, start)
        for (a, b, c) in problem.getSuccessors(
                current):  #sinon on observe les successeurs
            new_cost = cost_so_far[
                current] + c  # g(n+1) = g(n) + stepCost (dans ce cas, toutes les stepCost sont 1, on peut verifier par la fonction getSuccessors et voir le 3eme argument) -> definition de l'evaluation du noeud
            if a in cost_so_far.keys():  #si le successeur a deja ete parcouru
                if new_cost < cost_so_far[
                        a]:  #et que son evaluation est inferieure (ce qui n'arrivera jamais dans notre cas vu que les couts sont egaux a 1)
                    cost_so_far[
                        a] = new_cost  #alors on remplace le cout associe a ce noeud par le nouveau cout
                    priority = new_cost + heuristic(
                        a, problem
                    )  # priority = f(n), new_cost = g(n), heuristic(a, problem) = h(n)
                    frontier.update(
                        a, priority
                    )  #sert au fonctionnement de la file de priorite
                    came_from[a] = (current, b)  # et on update son noeud pere
                else:
                    continue
            else:  #si le successeur est un nouveau noeud
                cost_so_far[a] = new_cost
                frontier.update(
                    a, new_cost + heuristic(a, problem)
                )  #on l'ajoute a la file en lui associant sa priorite
                came_from[a] = (current, b)  #on lui associe son noeud pere
Example #16
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    start = problem.getStartState()
    frontier = PriorityQueue()
    frontier.push((start, []), 0)
    return doUCS([], problem, frontier)
Example #17
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """
    Search the node that has the lowest combined cost and heuristic first.
    """
    aStarPath = graphSearch_aStar(problem, PriorityQueue(), heuristic)
    return aStarPath

    """
Example #18
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    fail = Directions.STOP

    from util import Queue
    from util import PriorityQueue
    from util import Stack
    succ = problem.getSuccessors(problem.getStartState())
    allSuccessors = PriorityQueue()
    allPaths = PriorityQueue()  #A queue of lists for a path of each function.
    allPathsCost = PriorityQueue()

    hasExpanded = [problem.getStartState()]

    for element in succ:
        allSuccessors.push(element, element[2])
        allPaths.push([element[1]], element[2])
        allPathsCost.push(element[2], element[2])

    while not allSuccessors.isEmpty():
        node = allSuccessors.pop()
        parentPath = allPaths.pop()
        pathCost = allPathsCost.pop()
        if not node[0] in hasExpanded:
            #print("Node is ", node)

            hasExpanded.append(node[0])

            #check if the current node is the goal node, returning the directions if so
            if problem.isGoalState(node[0]):
                return parentPath

            #Add Successors if not found already
            S = problem.getSuccessors(node[0])
            for element in S:
                if not element[0] in hasExpanded:
                    g = pathCost + element[2]
                    allSuccessors.push(element, g)
                    newPath = parentPath.copy()
                    newPath.append(element[1])
                    allPaths.push(newPath, g)
                    allPathsCost.push(g, g)

    return [fail]
Example #19
0
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    from game import Directions
    import heapq

    open_nodes = PriorityQueue()
    closed_nodes = []
    iteration = {}
    path = []

    open_nodes.push(problem.getStartState(), 0)

    while (not open_nodes.isEmpty()):
        (cur_cost, cur_node) = heapq.heappop(open_nodes.heap)

        if problem.isGoalState(cur_node):
            break

        if cur_node in closed_nodes:
            continue

        expand_nodes = []
        for item in problem.getSuccessors(cur_node):
            if (item[0] not in closed_nodes):
                expand_nodes.append((item[0], item[2]))

        if (len(expand_nodes) > 0):
            for item in expand_nodes:
                if not iteration.has_key(item[0]):
                    open_nodes.push(item[0], item[1] + cur_cost)
                    iteration[item[0]] = cur_node
                else:
                    for i in open_nodes.heap:
                        if i[1] == item[0]:
                            if item[1] + cur_cost < i[0]:
                                iteration[item[0]] = cur_node
                                open_nodes.heap.remove((i[0], i[1]))
                                open_nodes.push(item[0], item[1] + cur_cost)
                            break

        closed_nodes.append(cur_node)

    while (cur_node != problem.getStartState()):
        parent_node = iteration[cur_node]
        if cur_node[0] == parent_node[0] + 1:
            path.append(Directions.EAST)
        elif cur_node[1] == parent_node[1] - 1:
            path.append(Directions.SOUTH)
        elif cur_node[0] == parent_node[0] - 1:
            path.append(Directions.WEST)
        elif cur_node[1] == parent_node[1] + 1:
            path.append(Directions.NORTH)
        cur_node = parent_node

    path.reverse()
    return path
Example #20
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    # Use Queue for the frontier
    from util import PriorityQueue
    qu = PriorityQueue()

    # Maintain a list of already visited states
    visited = []

    # Get the start state
    state = problem.getStartState()
    # Put it in visited array
    visited.append(state)
    # Get the list of successor states
    suc = problem.getSuccessors(state)

    # For every state in successors,
    # push to frontier if not visited
    for s in suc:
        if s[0] not in visited:
            l = list(s)
            l[1] = l[1].split()
            qu.push(l,
                    l[2] + heuristic(s[0], problem))  # Add heuristic of node

    while (1):

        # finish when the frontier is empty
        if qu.isEmpty():
            break

        # visit state
        p = qu.pop()

        if p[0] not in visited:
            visited.append(p[0])
            # end on reaching goal state
            if (problem.isGoalState(p[0])):
                return p[1]
                break

            # Get the list of successor states
            suc = problem.getSuccessors(p[0])

            #For every state in successors,
            # push to frontier if not visited or if not in frontier
            for s in suc:
                if ((s[0] not in visited)):
                    c = list(s)
                    c[1] = c[1].split()
                    c[1] = p[1] + c[
                        1]  # update actions for every state right from the start state
                    c[2] = p[2] + c[2]
                    qu.update(
                        c, c[2] +
                        heuristic(s[0], problem))  # Add heuristic of node
    util.raiseNotDefined()
Example #21
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    #declaring priority queue for storing frontiers
    frontier = PriorityQueue()

    #explored = dict()
    explored = dict()

    #stroring current state in a variable
    position = problem.getStartState()

    vertex = {
        "from": None,
        "to": None,
        "current_pos": position,
        "cost": 0,
    }
    frontier.push(vertex, vertex["cost"] + heuristic(position, problem))

    #till frontier is not empty iterate to find path
    while not frontier.isEmpty():

        #popping next vertex from frontier priority queue
        vertex = frontier.pop()
        current_pos = vertex["current_pos"]
        current_cost = vertex["cost"]

        #if already explored then go to next vertex
        if explored.has_key(current_pos):
            continue
        explored[current_pos] = True

        #if goal is reached then break loop
        if problem.isGoalState(current_pos):
            break

        #if goal not reached then see for next available paths
        for next_state in problem.getSuccessors(current_pos):
            #if this vertex is not already explored then add it to frontier
            if not explored.has_key(next_state[0]):  #gives next state
                next_vertex = {
                    "from": vertex,
                    "to": next_state[1],
                    "current_pos": next_state[0],
                    "cost": next_state[2] + current_cost
                }

                frontier.push(
                    next_vertex,
                    next_vertex["cost"] + heuristic(next_state[0], problem))

    #array for storing actions
    actions = []
    while vertex["from"] != None:
        actions.insert(0, vertex["to"])
        vertex = vertex["from"]
    return actions
Example #22
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    #util.raiseNotDefined()
    from game import Directions
    from util import PriorityQueue
    close = set()
    fringes = PriorityQueue()
    #Stack for father nodes doesn't fit BFS, have to enqueue the entire path
    currentState = []
    currentState.append((problem.getStartState(), None, 1))
    fringes.push(currentState, 0 + heuristic(currentState[-1][0], problem))
    while (not fringes.isEmpty()):
        currentState = fringes.pop()
        close.add(currentState[-1][0])
        if (problem.isGoalState(currentState[-1][0])):
            ret = []
            for i in range(1, len(currentState)):
                ret.append(currentState[i][1])
            return ret
        successors_list_not_filtered = problem.getSuccessors(
            currentState[-1][0])
        for i in range(0, len(successors_list_not_filtered)):
            currentState_copy = currentState.copy()
            currentState_copy.append(successors_list_not_filtered[i])
            to_calculate = []
            for i in range(1, len(currentState_copy)):
                to_calculate.append(currentState_copy[i][1])
            fringes.push(
                currentState_copy,
                problem.getCostOfActions(to_calculate) +
                heuristic(currentState_copy[-1][0], problem))
        #Now filter the fringes in case that new states in close set aren't counted in
        new_fringes = PriorityQueue()
        while (not fringes.isEmpty()):
            new_fringe = fringes.pop()
            if (not new_fringe[-1][0] in close):
                to_calculate = []
                for i in range(1, len(new_fringe)):
                    to_calculate.append(new_fringe[i][1])
                new_fringes.push(
                    new_fringe,
                    problem.getCostOfActions(to_calculate) +
                    heuristic(new_fringe[-1][0], problem))
        fringes = new_fringes
Example #23
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    from searchAgents import manhattanHeuristic
    import re

    closed = []
    from util import PriorityQueue
    fringe = PriorityQueue()
    fringe.push((problem.getStartState(), [], 1.0), 0)
    print fringe.isEmpty()
    result = []
    "print type(fringe)"
    while (fringe.isEmpty() == False):
        node = fringe.pop()
        #print
        #print node
        x = node[0]
        if x == (5, 1, [((1, 1), False), ((1, 12), False), ((28, 1), False),
                        ((28, 12), False)]):
            #print "Here",x
            result = aStarSearch1(problem)
            return result

        result = node[1]
        cost = node[2]
        if problem.isGoalState(node[0]):
            return result

        if node[0] not in closed:
            """
            print "Inloop",node[0]
            
            print type(node[1])
            print result
            print node[1]
            
            print result
            """
            closed.append(node[0])

            temp = problem.getSuccessors(node[0])

            #print temp
            #print cost
            for child_node in temp:
                if (type(node[0]) == tuple):
                    h = manhattanHeuristic(child_node[0], problem)
                else:
                    h = nullHeuristic(child_node, node, problem)
                fringe.push((child_node[0], result + [child_node[1]],
                             child_node[2] + cost), child_node[2] + cost + h)

    return []

    util.raiseNotDefined()
Example #24
0
    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [
            ghostState.scaredTimer for ghostState in newGhostStates
        ]
        newGhostPositions = successorGameState.getGhostPositions()
        score = 0  # 100*len(newGhostStates)
        for pos in newGhostPositions:
            distFromGhost = manhattan_dist(newPos, pos)
            distFromGhost += 0.01  # avoid 0 division
            # print('distFromGhost ', distFromGhost)
            if distFromGhost <= 4:
                score -= 200 / distFromGhost
                # break
        pq = PriorityQueue()
        for foodPos in newFood.asList():
            dist = manhattan_dist(newPos, foodPos)
            # print(bcolors.WARNING,' distFromFood ', dist, ' at', foodPos, bcolors.ENDC)
            dist += 0.01
            pq.push(dist, dist)

            # if dist<=4:
            # print(bcolors.WARNING,' distFromFood ', dist, bcolors.ENDC)
            # score += 100/dist

        while pq.isEmpty() is False:
            dist = pq.pop()
            # print(bcolors.WARNING, ' distFromFood ', dist, bcolors.ENDC)
            score += 100 / dist

        # score += 500/(newFood.count()+0.1)
        if currentGameState.getFood().count() > successorGameState.getFood(
        ).count():
            # print(bcolors.BOLD, 'Will get food', bcolors.ENDC)
            score += 200

        "*** YOUR CODE HERE ***"
        # print(action, newPos, newFood.count(), newGhostPositions, newScaredTimes, ' score ', score)
        return score  # successorGameState.getScore()
Example #25
0
def uniformCostSearch(problem):
        
    loc_pqueue = PriorityQueue()
    visited_node = {}
    parent_child_map = {}
    direction_list = [] 
    path_cost = 0
       
    start_node = problem.getStartState()
    parent_child_map[start_node] = []
    loc_pqueue.push(start_node,path_cost)
        
    def traverse_path(parent_node):
        while True:
            map_row = parent_child_map[parent_node]
            if (len(map_row) == 3):
                parent_node = map_row[0]
                direction = map_row[1]
                direction_list.append(direction)
            else:
                break       
        return direction_list
        
    while (loc_pqueue.isEmpty() == False):
        
        parent_node = loc_pqueue.pop()
        
        if (parent_node != problem.getStartState()):
            path_cost = parent_child_map[parent_node][2]
                
        if (problem.isGoalState(parent_node)):
            pathlist = traverse_path(parent_node)
            pathlist.reverse()
            return pathlist
        
        elif (visited_node.has_key(parent_node) == False):
            visited_node[parent_node] = []            
            sucessor_list = problem.getSuccessors(parent_node)
            no_of_child = len(sucessor_list)
            if (no_of_child > 0):          
                temp = 0
                while (temp < no_of_child):
                    child_nodes = sucessor_list[temp]
                    child_state = child_nodes[0];
                    child_action = child_nodes[1];
                    child_cost = child_nodes[2];
                    gvalue = path_cost + child_cost
                    if (visited_node.has_key(child_state) == False):
                        loc_pqueue.push(child_state,gvalue)
                    if (parent_child_map.has_key(child_state) == False):
                        parent_child_map[child_state] = [parent_node,child_action,gvalue]
                    else:
                        if (child_state != start_node):
                            stored_cost = parent_child_map[child_state][2]
                            if (stored_cost > gvalue):
                                parent_child_map[child_state] = [parent_node,child_action,gvalue]
                    temp = temp + 1
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    strategy = 'astar'
    fringe = PriorityQueue()
    fringe.push([problem.getStartState(), [], 0], 0)
    actions = graphSearch(problem, fringe, strategy, heuristic)
    return actions
Example #27
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    from util import PriorityQueue

    # Creates an empty PriorityQueue.
    open_list = PriorityQueue()

    visited_list = []
    path = []
    priority = 0    # Initializes the priority to 0.

    start_position = problem.getStartState()

    # Pushes the start position to the PriorityQueue.
    open_list.push((start_position, path), priority)

    while not open_list.isEmpty():

        current_node = open_list.pop()
        position = current_node[0]
        path = current_node[1]

        # Returns the final path if the current position is goal.
        if problem.isGoalState(position):
            return path

        # Pushes the current position to the visited list if it is not visited.
        if position not in visited_list:
            visited_list.append(position)

            # Gets successors of the current node.
            successors = problem.getSuccessors(position)

            # Pushes the current node's successors to the PriorityQueue if they are not visited.
            for item in successors:
                if item[0] not in visited_list:
                    new_position = item[0]
                    new_path = path + [item[1]]

                    # Updates priority of the successor using f(n) function.

                    """ g(n): Current cost from start state to the current position. """
                    g = problem.getCostOfActions(new_path)

                    """ h(n): Estimate of the lowest cost from the current position to the goal state. """
                    h = heuristic(new_position, problem)

                    """ f(n): Estimate of the lowest cost of the solution path
                              from start state to the goal state passing through the current position """
                    f = g + h

                    new_priority = f
                    open_list.push((new_position, new_path), new_priority)

    util.raiseNotDefined()
Example #28
0
def aStarSearch(problem, heuristic=nullHeuristic):

    "Search the node that has the lowest combined cost and heuristic first."

    from util import PriorityQueue
    from searchAgents import node

    #initialize frontier
    frontier = PriorityQueue()
    initialState = problem.getStartState()
    currentNode = node(initialState, None, 0, 0,
                       0)  #create the root node and add it to the frontier

    frontier.push(currentNode, currentNode.getTotalPathCost())

    #initialize the explored set
    explored = dict()

    while True:
        #no solution
        if (frontier.isEmpty()):
            return []

        #choose the lowest cost (path + heuristic) node in the frontier
        current = frontier.pop()

        #solution found
        if (problem.isGoalState(current.getCurrentState())):
            solution = list()
            step = current

            #collect the path
            while (step.getParentNode() != None):
                solution.append(step.getLastAction())
                step = step.getParentNode()

            solution.reverse()

            return solution  #return list of actions from start state to goal state

        #add node to explored
        explored[current.getCurrentState()] = "True"

        for successor in problem.getSuccessors(current.getCurrentState()):

            #calculate step cost and total path cost
            myStepCost = successor[2]
            myTotalPathCost = current.getTotalPathCost() + myStepCost
            child = node(successor[0], current, successor[1], myStepCost,
                         myTotalPathCost)

            #add the current node's child to the frontier
            if (child.getCurrentState() not in explored):
                frontier.push(
                    child,
                    child.getTotalPathCost() +
                    heuristic(child.getCurrentState(), problem))
Example #29
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    strategy = "ucs"
    fringe = PriorityQueue()
    fringe.push([problem.getStartState(), [], 0], 0)
    actions = graphSearch(problem, fringe, strategy)
    return actions
Example #30
0
def foodHeuristic(state, problem):
    """
    Your heuristic for the FoodSearchProblem goes here.

    This heuristic must be consistent to ensure correctness.  First, try to come
    up with an admissible heuristic; almost all admissible heuristics will be
    consistent as well.

    If using A* ever finds a solution that is worse uniform cost search finds,
    your heuristic is *not* consistent, and probably not admissible!  On the
    other hand, inadmissible or inconsistent heuristics may find optimal
    solutions, so be careful.

    The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid
    (see game.py) of either True or False. You can call foodGrid.asList() to get
    a list of food coordinates instead.

    If you want access to info like walls, capsules, etc., you can query the
    problem.  For example, problem.walls gives you a Grid of where the walls
    are.

    If you want to *store* information to be reused in other calls to the
    heuristic, there is a dictionary called problem.heuristicInfo that you can
    use. For example, if you only want to count the walls once and store that
    value, try: problem.heuristicInfo['wallCount'] = problem.walls.count()
    Subsequent calls to this heuristic can access
    problem.heuristicInfo['wallCount']
    """
    position, foodGrid = state
    "*** YOUR CODE HERE ***"
    

    from util import manhattanDistance
    from util import PriorityQueue
    euclideanDistance = lambda p1,p2:((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)**0.5
    vertices = []
    for i in range(foodGrid.width):
        for j in range(foodGrid.height):
            if foodGrid[i][j]:
                vertices.append((i,j))
    vertices.append(position)
    edges = PriorityQueue()
    map = {}
    for i in range(len(vertices)):
        map[vertices[i]] = vertices[i]
        for j in range(i+1,len(vertices)):
            edges.push((euclideanDistance(vertices[i],vertices[j]),vertices[i],vertices[j]),euclideanDistance(vertices[i],vertices[j]))
    V = set()
    w = 0
    while len(V) < len(vertices) and not edges.isEmpty():
        edge = edges.pop()
        r1 = find(map,edge[1])
        r2 = find(map,edge[2])
        if r1 != r2:
            w += edge[0]
            union(map,edge[1],edge[2])
    return w