Esempio n. 1
0
def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first [p 85].

    Your search algorithm needs to return a list of actions that reaches
    the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].

    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())
    """

    # THIS IS A NEW CODE BY OLEKSII & HYUNGJOON
    # TODO: Check wether there are some evidence that DFS is faster in connectivity detection

    exploredNodes = []
    # These dict's serves to retrieve the path
    trackParents = {}
    trackActions = {}

    # Get the beginning node of the given problem
    initialNode = problem.getStartState()
    if problem.isGoalState(initialNode):
        # If the first node is already a goal
        # then return nothing (just stay there)
        return []

    # Create the instance from Stack class to store nodes
    # Push the first node to explore its successors
    dfsStack = util.Stack()
    dfsStack.push(initialNode)

    # Do iteration until the stack is empty
    while not dfsStack.isEmpty():
        # Pop the node in a stack
        currentNode = dfsStack.pop()
        # Add the node to the exploredNodes list
        exploredNodes.append(currentNode)
        for (nextState, action, cost) in problem.getSuccessors(currentNode):
            # Only if this successor is not in the exploredNodes list
            if nextState not in exploredNodes:
                # Add this successor to the exploredNodes list
                exploredNodes.append(nextState)
                # Save tracking information -
                # from what parent and with what action we came
                trackParents[nextState] = currentNode
                trackActions[nextState] = action
                if problem.isGoalState(nextState):
                    # If a goal is found - return this solution
                    return getSolution(nextState, trackParents, trackActions)
                # Otherwise push a successor into the stack
                dfsStack.push(nextState)

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 2
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."

    from game import Directions
    from spade import pyxf
    import time

   # Creates an instance and makes a query to XSB using SPADE interface
    myXsb = pyxf.xsb('C:/XSB/config/x86-pc-windows/bin/xsb.exe')
    myXsb.load('D:/Tmp/maze.P')
    myXsb.load('D:/Tmp/astar.P')

    # print ('Starting to search!')

    time.sleep(2)
    result = myXsb.query("astar(start,finish,Direction).")

    finalDirections = []
    res = []

    # Choose the shortest path from all results available.
    # XSB is unstable from time to time, so we print something when it goes wrong.
    # print ('Retrieving results!')
    # print result

    # Choose the shortest path from all results available.
    if isinstance(result,bool):
        print "Catches XSB Problem!"

    else:
        cnt = 99999
        for dict in result:
            if len(dict['Direction']) < cnt:
                cnt = len(dict['Direction'])
                res = dict['Direction']
                res = res.split(",")
                print res
                break

        # print ('Final processing')
        # Perform final step to return real directions to Pacman
        for direction in res:
            if direction=="s":
                finalDirections.append(Directions.SOUTH)
            if direction=="w":
                finalDirections.append(Directions.WEST)
            if direction=="n":
                finalDirections.append(Directions.NORTH)
            if direction=="e":
                finalDirections.append(Directions.EAST)

        print finalDirections

    return finalDirections

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 3
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"

    # THIS IS A NEW CODE BY OLEKSII & HYUNGJOON
    # BFS implementation is pretty much the same with DFS except using a queue instead of a stack
    # Again e apply iGoalTest while generating successors, that is explained in the textbook,
    # pages 81 - 82

    exploredNodes = []
    # These dict's serves to retrieve the path
    trackParents = {}
    trackActions = {}

    # Get the beginning node of the given problem
    initialNode = problem.getStartState()
    if problem.isGoalState(initialNode):
        # If the first node is already a goal
        # then return nothing (just stay there)
        return []

    # Create the instance from simple Queue class to store nodes
    # Push the first node to explore its successors
    bfsQueue = util.Queue()
    bfsQueue.push(initialNode)

    # Do iteration until the queue is empty
    while not bfsQueue.isEmpty():
        # Dequeue the node in a queue
        currentNode = bfsQueue.pop()
        # Add the node to the exploredNodes list
        exploredNodes.append(currentNode)
        for (nextState, action, cost) in problem.getSuccessors(currentNode):
            # Only if this successor is not in the exploredNodes list
            if nextState not in exploredNodes:
                # Add this successor to the exploredNodes list
                exploredNodes.append(nextState)
                # Save tracking information -
                # from what parent and with what action we came
                trackParents[nextState] = currentNode
                trackActions[nextState] = action
                if problem.isGoalState(nextState):
                    # If a goal is found - return this solution
                    return getSolution(nextState, trackParents, trackActions)
                # Otherwise enqueue a successor into the queue
                bfsQueue.push(nextState)

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 4
0
def breadthFirstSearch(problem):
    """
  Search the shallowest nodes in the search tree first.
  [2nd Edition: p 73, 3rd Edition: p 82]
  """
    "*** YOUR CODE HERE ***"
    exploredNodes = []
    # These dict's serves to retrieve the path
    trackParents = {}
    trackActions = {}

    # Get the beginning node of the given problem
    initialNode = problem.getStartState()
    if problem.isGoalState(initialNode):
        # If the first node is already a goal
        # then return nothing (just stay there)
        return []

    # Create the instance from simple Queue class to store nodes
    # Push the first node to explore its successors
    bfsQueue = util.Queue()
    bfsQueue.push(initialNode)

    # Do iteration until the queue is empty
    while not bfsQueue.isEmpty():
        # Dequeue the node in a queue
        currentNode = bfsQueue.pop()
        # Add the node to the exploredNodes list
        exploredNodes.append(currentNode)
        for (nextState, action, cost) in problem.getSuccessors(currentNode):
            # Only if this successor is not in the exploredNodes list
            if nextState not in exploredNodes:
                # Add this successor to the exploredNodes list
                exploredNodes.append(nextState)
                # Save tracking information -
                # from what parent and with what action we came
                trackParents[nextState] = currentNode
                trackActions[nextState] = action
                if problem.isGoalState(nextState):
                    # If a goal is found - return this solution
                    return getSolution(nextState, trackParents, trackActions)
                # Otherwise enqueue a successor into the queue
                bfsQueue.push(nextState)

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 5
0
def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first [p 85].

    Your search algorithm needs to return a list of actions that reaches
    the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].

    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())
    """
    from game import Directions
    from spade import pyxf
    import time

    # Creates an instance and makes a query to XSB using SPADE interface
    myXsb = pyxf.xsb('C:/XSB/config/x86-pc-windows/bin/xsb.exe')
    myXsb.load('D:/Tmp/maze.P')
    myXsb.load('D:/Tmp/dfs.P')

    # print ('Starting to search!')

    time.sleep(2)
    result = myXsb.query("dfs(finish,[start],Direction).")

    finalDirections = []
    res = []

    # print ('Retrieving results!')

    # Choose the shortest path from all results available.
    # XSB is unstable from time to time, so we print something when it goes wrong.
    if isinstance(result,bool):
        print "Catches XSB Problem!"
    else:
        cnt = 99999
        for dict in result:
            if len(dict['Direction']) < cnt:
                cnt = len(dict['Direction'])
                res = dict['Direction']
                res = res.split(",")
                print res
                break

        # print ('Final processing')
        # Final step to return real direction to Pacman

        for direction in res:
            if direction=="s":
                finalDirections.append(Directions.SOUTH)
            if direction=="w":
                finalDirections.append(Directions.WEST)
            if direction=="n":
                finalDirections.append(Directions.NORTH)
            if direction=="e":
                finalDirections.append(Directions.EAST)

        print finalDirections

    return finalDirections

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 6
0
def uniformCostSearch(problem):
    "Search the node of least total cost first. "

    # THIS IS A NEW CODE BY OLEKSII & HYUNGJOON
    # ATTENTION: in UCS check for isGoal must be conducted
    # during analyzing the particular vertex retrieved from
    # the priority queue

    '''
    In fact, this is an implementation of Dijkstra's algorithm
    using priority queue. Graph complexity is O(MlogN)
    '''

    exploredNodes = []
    # These dict's serves to retrieve the path
    trackParents = {}
    trackActions = {}

    # We need to track the best currently known distance (cost)
    # to yet unexplored vertices
    currentDistance = {}

    # Get the beginning node of the given problem
    initialNode = problem.getStartState()
    if problem.isGoalState(initialNode):
        # If the first node is already a goal
        # then return nothing (just stay there)
        return []

    # ATTENTION: we have changed the code in util.py
    # to get priority back as well when pop an item!
    uscQueue = util.PriorityQueue()

    # Initialize the queue, each tuple contain vertex
    # and distance (cost) as a priority
    uscQueue.push(initialNode, 0)
    # Initialize the first known distance
    currentDistance[initialNode] = 0


    # Do iteration until the queue is empty
    while not uscQueue.isEmpty():
        # We retrieve a node with the best priority (cost or distance)
        (priority, node) = uscQueue.pop()
        '''
        This implementation uses the following trick -
        we cannot change priority of an element inside priority queue,
        but we need to do it during the relaxation phase.
        So indeed during relaxation we just add to the queue new values,
        not removing for a vertex its old priority in the queue.
        So we need to check for the following fictive nodes.
        More details can be found in Russian at e-maxx.ru :)
        '''
        # Fictive nodes will be omitted
        if priority > currentDistance[node]:
            # meaning an old one  - let's pop the next
            continue
        if problem.isGoalState(node):
            # If a goal is found - return this solution
            # Note, we should check it here! not while generating children
            # as in previous algorithms
            return getSolution(node, trackParents, trackActions)
        exploredNodes.append(node)
        for (nextState, action, cost) in problem.getSuccessors(node):
            if nextState in exploredNodes:
                # not interesting for us anymore
                continue
            # THE RELAXATION PHASE follows
            if nextState not in currentDistance or priority + cost < currentDistance[nextState]:
                uscQueue.push(nextState, priority + cost)
                currentDistance[nextState] = priority + cost
                # Update tracking information -
                # from what parent and with what action we came
                trackParents[nextState] = node
                trackActions[nextState] = action

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Esempio n. 7
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."

    # THIS IS A NEW CODE BY OLEKSII & HYUNGJOON
    # aStarSearch is pretty much the same with uniformCostSearch
    # except using the lowest combined cost plus heuristic

    exploredNodes = []
    # These dict's serves to retrieve the path
    trackParents = {}
    trackActions = {}

    # We need to track the best currently known distance (cost)
    # to yet unexplored vertices
    currentDistance = {}

    # Get the beginning node of the given problem
    initialNode = problem.getStartState()
    if problem.isGoalState(initialNode):
        # If the first node is already a goal
        # then return nothing (just stay there)
        return []

    # ATTENTION: we have changed the code in util.py
    # to get priority back as well when pop an item!
    astarQueue = util.PriorityQueue()

    # Initialize the queue, each tuple contain vertex
    # and distance (cost) as a priority
    astarQueue.push(initialNode, 0)
    # Initialize the first known distance
    currentDistance[initialNode] = 0

    # Do iteration until the queue is empty
    while not astarQueue.isEmpty():
        # We retrieve a node with the best priority (cost or distance)
        (priority, node) = astarQueue.pop()
        # Fictive nodes will be omitted
        if priority > currentDistance[node]:
            # meaning an old one  - let's pop the next
            continue
        if problem.isGoalState(node):
            # If a goal is found - return this solution
            # Note, we should check it here! not while generating children
            # as in previous algorithms
            return getSolution(node, trackParents, trackActions)
        exploredNodes.append(node)
        for (nextState, action, cost) in problem.getSuccessors(node):
            if nextState in exploredNodes:
                # not interesting for us anymore
                continue
            # THE RELAXATION PHASE follows
            if nextState not in currentDistance or priority + cost + heuristic(
                    nextState, problem) < currentDistance[nextState]:
                astarQueue.push(
                    nextState, priority + cost + heuristic(nextState, problem))
                currentDistance[nextState] = priority + cost + heuristic(
                    nextState, problem)
                # Update tracking information -
                # from what parent and with what action we came
                trackParents[nextState] = node
                trackActions[nextState] = action

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()