コード例 #1
0
ファイル: search.py プロジェクト: joshuaburkhart/CIS_571
def uniformCostSearch(problem):
  "Search the node of least total cost first. "
  "*** YOUR CODE HERE ***"
  
  from util import PriorityQueue

  frontier = PriorityQueue()
  explored_states = set([])
  node = (problem.getStartState(), [], 0)

  if problem.isGoalState(node[0]):
      return node[1]
  PriorityQueue.push(frontier, node, node[2])
  while True:
      if not frontier:
          return None
      node = PriorityQueue.pop(frontier)
      explored_states.add(node[0])
      successor_candidates = problem.getSuccessors(node[0])
      successor_candidates.reverse()
      for candidate in successor_candidates:
	  if candidate[0] not in explored_states:
	      path_to_node = list(node[1])
	      path_to_node.append(candidate[1])
	      child_node = (candidate[0], path_to_node, node[2] + candidate[2])
	      # if candidate[0] not in explored_states:
	      if problem.isGoalState(child_node[0]):
	          return child_node[1]
	      PriorityQueue.push(frontier, child_node, child_node[2])
コード例 #2
0
ファイル: sudoku.py プロジェクト: lylepmills/Miscellaneous
    def __guess_and_check(self):
        """If it proves impossible to solve the puzzle by pure deduction, this
method is called to guess (using minimum remaining values and least constraining
choice heuristics) a number, which is then used to solve a reduced game (if
possible). All possible choices are exhausted in this manner.
        """
        queue = PriorityQueue()
        impossible_list = []
        for x, y in product(range(9), repeat=2):
            position = self.__positions[x][y]
            n = position.num_possible()
            if n <= 1:
                continue
            for val in position.possible:
                new_board = deepcopy(self)
                new_board.__set_position_val(x, y, val)
                new_board.__enforce_consistency()
                priority = new_board.__possible_count()
                queue.push((new_board, x, y, val), priority*n)
        while not queue.isEmpty():
            new_board, x, y, val = queue.pop()
            for xx, yy, valval in impossible_list:
                new_board.__positions[xx][yy].remove_possible(valval)
            b = new_board.__solver()
            if not isinstance(b, SudokuGame):
                impossible_list.append((x, y, val))
                continue
            return b
        return False
コード例 #3
0
ファイル: searchAgents.py プロジェクト: DavidMcDonnel/cse511
class ApproximateSearchAgent(Agent):
    "Implement your contest entry here.  Change anything but the class name."

    def registerInitialState(self, state):
        "This method is called before any moves are made."
        "*** YOUR CODE HERE ***"
        # ApproximateSearchAgent.create(state,set(state.foodGrid.asList()),state.walls)

    def getAction(self, state):
        """
        From game.py:
        The Agent will receive a GameState and must return an action from
        Directions.{North, South, East, West, Stop}
        """
        "*** YOUR CODE HERE ***"
        if 'actionIndex' not in dir(self): self.actionIndex = 0
        i = self.actionIndex
        self.actionIndex += 1
        if i < len(self.actions):
            return self.actions[i]
        else:
            return Directions.STOP

        # util.raiseNotDefined()

    def __init__(self):
        from util import PriorityQueue
        self.pacman = tuple()
        self.food = []
        self.walls = list()
        self.Queue = PriorityQueue()
        self.min = float("inf")

    def create(self,p,f,w):
        self.pacman = p
        self.food = f
        self.walls = w
        self.myWalls = w.asList()
    def getWalls(self):
        return self.walls
    def getPacman(self):
        return self.pacman
    def getFood(self):
        return self.food
    def getPacmanPosition(self):
        return self.pacman
    def getNumFood(self):
        return len(self.food)
    def hasFood(self,*goal):
        return len(list(*goal))
    def mazeDistance(self,point1,point2):
        for food in self.getFood():
            if food not in self.myWalls:
                prob = PositionSearchProblem(self, start=point1, goal=point2, warn=False)
                dist = len(search.bfs(prob))
                self.Queue.push(food,dist)
                self.min = self.min if self.min<dist else dist
    def newQueue(self):
        from util import PriorityQueue
        self.Queue = PriorityQueue()
コード例 #4
0
ファイル: search.py プロジェクト: anhDean/AI_Assignments
def uniformCostSearch(problem):
    successor_idx = {'dir': 1, 'state': 0, 'cost': -1}

    MAX_ITER = int(2000)
    stateQ = PriorityQueue()
    visitedSet = set()
    successorDict = {}

    curState = problem.getStartState()
    actionList = [] # add actions to get to the state, use pop to remove last one
    currentCost = 0

    for it in range(MAX_ITER):

        if problem.isGoalState(curState):
            return actionList
        
        if curState not in visitedSet:
            successorDict[curState] = problem.getSuccessors(curState)
        visitedSet.add(curState)

        for node in successorDict[curState]:

            if node[successor_idx['state']] not in visitedSet:
                tmp_state = {'cost' : currentCost + node[successor_idx['cost']], 'action' : actionList + [node[successor_idx['dir']]], 'state': node[successor_idx['state']]}
                stateQ.push(tmp_state, tmp_state['cost'])
        # get next state to test
        nState = stateQ.pop()
        actionList = nState['action']
        curState = nState['state']
        currentCost = nState['cost']

    return []
コード例 #5
0
ファイル: search.py プロジェクト: Akshay-Iyangar/Multi-Agent
def aStarSearch(problem, heuristic=nullHeuristic):
  
    
    from collections import defaultdict
    from util import PriorityQueue
    
    initial_node=problem.getStartState()
    
    current_node=defaultdict(list)
    current_node[initial_node].append("No parent")
    current_node[initial_node].append("No direction")
    priority_queue=PriorityQueue()
    cost_array={}
    #priority_queue.push(current_node,0)
    cost_list={}
    cost_list[initial_node]=0
    cost_array[initial_node]=heuristic(initial_node,problem)
    
    direction_list={}
    Child=current_node.keys()
    Parent=current_node.values()[0]
    visited_list={}
          
    
    while (problem.isGoalState(Child[0]) is not True):
            
        if(Child[0] in visited_list.keys()):
            current_node=priority_queue.pop()
            Child=current_node.keys()
            Parent=current_node.values()[0]
        else:
            visited_list[Child[0]]=Parent[0]
            direction_list[Child[0]]=Parent[1]
            Successor_node=problem.getSuccessors(Child[0])
            for index in range(len(Successor_node)):
                temp_dict=defaultdict(list)
                
                temp_dict[Successor_node[index][0]].append(Child[0])
                temp_dict[Successor_node[index][0]].append(Successor_node[index][1])
                cost_list[Successor_node[index][0]]= cost_list[Child[0]]+Successor_node[index][2] 
                cost_array[Successor_node[index][0]]=cost_list[Successor_node[index][0]]+heuristic(Successor_node[index][0],problem)
                priority_queue.push(temp_dict, cost_array[Successor_node[index][0]])
                  
            current_node=priority_queue.pop()
            Child=current_node.keys()
            Parent=current_node.values()[0]
    
    visited_list[Child[0]]= Parent[0]
    direction_list[Child[0]]=Parent[1]
    backtracking =[]
    path = Child[0]
    backtracking.append(direction_list[path])
    path = visited_list[path]
    while (path!= problem.getStartState()):
        backtracking.append(direction_list[path])
        path = visited_list[path]
    backtracking.reverse()
    return backtracking
    util.raiseNotDefined()
コード例 #6
0
ファイル: mypy.py プロジェクト: dtbinh/Multiagent-RL
 def __init__(self, position, blocks, game_state, elements):
     self.elements = elements
     self.ds = PriorityQueue()
     self.position = round_tuple(position)
     self.blocks = [round_tuple(t) for t in blocks]
     self.game_state = game_state
     self.antecessor = {}
コード例 #7
0
ファイル: searchAgents.py プロジェクト: DavidMcDonnel/cse511
 def __init__(self):
     from util import PriorityQueue
     self.pacman = tuple()
     self.food = []
     self.walls = list()
     self.Queue = PriorityQueue()
     self.min = float("inf")
コード例 #8
0
ファイル: search.py プロジェクト: luowei89/neu-courses
def uniformCostSearch(problem):
  "Search the node of least total cost first. "
  start = problem.getStartState()
  frontier = PriorityQueue()  # A priority queue of (state,route_to_state,cost)
  frontier_set = set()  #A set recording what's in the frontier
  explored_set = set()  # A set of states recording the explored nodes
  frontier.push((start,list(),0),0)
  frontier_set.add(start)
  solution_node = ((0,0),list(),-1)

  while not frontier.isEmpty():
    current_node = frontier.pop()
    frontier_set.remove(current_node[0])
    if solution_node[2] == -1 or current_node[2] < solution_node[2]:
      if problem.isGoalState(current_node[0]):
        solution_node = current_node
        successors = list()
      else:
        successors = problem.getSuccessors(current_node[0])
      explored_set.add(current_node[0])
      for s in successors:
        if s[0] not in explored_set.union(frontier_set):
          current_route = list(current_node[1])
          current_route.append(s[1])
          frontier.push((s[0],current_route,current_node[2]+s[2]),current_node[2]+s[2])
          frontier_set.add(s[0])
        elif s[0] in frontier_set:
          #retrieve the frontier to see if current_node has lower cost
          found = False
          nodes = list()
          while not found:
            node = frontier.pop()
            if s[0] == node[0]:
              found = True
              if current_node[2]+s[2] < node[2]:
                current_route = list(current_node[1])
                current_route.append(s[1])
                nodes.append((s[0],current_route,current_node[2]+s[2]))
              else:
                nodes.append(node)
            else:
              nodes.append(node)
          for n in nodes:
            frontier.push(n,n[2])
  if solution_node[2] == -1:
    print "No route found!"
  return solution_node[1]
コード例 #9
0
ファイル: search.py プロジェクト: kli66/UWMadison
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    if problem.isGoalState(problem.getStartState()):
        return list()
    frontier = PriorityQueue()

    ##same as q1,q2 but keep a sum of stepcosts from starting point to current state
    listOfActions = list()
    frontier.push( [problem.getStartState(),listOfActions,0],0 )
    explored = set()

    while not(frontier.isEmpty()):
        node = frontier.pop()
        if problem.isGoalState(node[0]):
            return node[1]

        ##check if the state has been explored before checking its successors
        ##avoid expanding unnecessary nodes and perserve two nodes with same states on the frontier
        if node[0] not in explored:
            for state,action,stepCost in problem.getSuccessors(node[0]):
                oldActions = list(node[1])
                oldActions.append(action)

                ##increment total costs by adding this step's cost to total cost
                oldCosts = node[2]
                oldCosts += stepCost
                nextNode = [state,oldActions,oldCosts]
                if(state not in explored):
                    frontier.push(nextNode,oldCosts)

        explored.add(node[0])

    return None
コード例 #10
0
ファイル: search.py プロジェクト: znyupup/Pacman
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"
    #print 'A* is called'
    queue = PriorityQueue()
    explored = []
      
    queue.push((problem.getStartState(), [], 0), 0) #what in the queue is the (state, path,cost)
    explored.append(problem.getStartState())
    while not queue.isEmpty():
        tuple = queue.pop()
        currentPath = tuple[1]
        currentCost = tuple[2]
                  
        #explored.append(tuple[0])
                  
        if problem.isGoalState(tuple[0]):
            return currentPath
                      
        suc = problem.getSuccessors(tuple[0])
        for triple in suc:
            if explored.__contains__(triple[0]):
                continue
            if not problem.isGoalState(triple[0]):
                explored.append(triple[0])
            path = currentPath + [triple[1]]
            cost = currentCost + triple[2]
            fn = cost + heuristic(triple[0], problem)
            queue.push((triple[0], path, cost), fn)
コード例 #11
0
ファイル: search.py プロジェクト: znyupup/Pacman
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"
    queue = PriorityQueue()
    explored = []
    
    queue.push((problem.getStartState(), [], 0), 0) #what in the queue is the (state, path,cost)
    explored.append(problem.getStartState())
    while not queue.isEmpty():
        tuple = queue.pop()
        #print tuple[0], tuple[2]
        currentPath = tuple[1]
        #print currentPath
        currentCost = tuple[2]
                
        if problem.isGoalState(tuple[0]):
            return currentPath
                    
        suc = problem.getSuccessors(tuple[0])
        for triple in suc:
            if explored.__contains__(triple[0]):
                continue
            if not problem.isGoalState(triple[0]):
                explored.append(triple[0])
            path = currentPath + [triple[1]]
            cost = currentCost + triple[2]
            queue.push((triple[0], path, cost), cost)
コード例 #12
0
ファイル: search.py プロジェクト: acrobat3/search_problem
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""

    from game import Directions
    from util import PriorityQueue

    pqueue = PriorityQueue()
    startNode = problem.getStartState()
    pqueue.push((startNode, []), 0)
    visitedList = []
    oldCost = {}
    oldCost[startNode[0]] = None

    while not pqueue.isEmpty():
        current, actions = pqueue.pop()
        if problem.isGoalState(current):
            return actions
        visitedList.append(current)
        for coord, direction, steps in problem.getSuccessors(current):
            new_actions = actions + [direction]
            priority = problem.getCostOfActions(new_actions) + heuristic(coord, problem)
            if not coord in visitedList or priority < oldCost[coord[0]]:
                oldCost[coord[0]] = priority
                visitedList.append(coord)
                pqueue.push((coord, new_actions), priority)
    return []

    util.raiseNotDefined()
コード例 #13
0
ファイル: search.py プロジェクト: azimmomin/Search_Pacman
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    closed = []
    closedSet = sets.Set(closed)
    fringe = PriorityQueue()
    for child in problem.getSuccessors(problem.getStartState()):
        path = [child[1]]
        fringe.push((child[0], path, child[2]), child[2])
    closedSet.add(problem.getStartState())
    
    while( not(fringe.isEmpty()) ):
        nodePos, nodeDir, nodeCost = fringe.pop()
        if (problem.isGoalState(nodePos)):
            return nodeDir
        if (nodePos not in closedSet):
            successors = problem.getSuccessors(nodePos)
            closedSet.add(nodePos)
            path = [nodeDir]
            for childNode in successors:
                cost = nodeCost + childNode[2]
                path = nodeDir + [childNode[1]]
                childNode = [childNode[0], path , cost]
                fringe.push(childNode, cost)

    return -1
コード例 #14
0
ファイル: search.py プロジェクト: szmark001/CS-188
def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    # fringe
    fringe = PriorityQueue()
    # closed set
    closed = set([])

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

    while True:
        if fringe.isEmpty() == True:
            print 'fail to find a path to the goal state'
            return []
        else:
            node = fringe.pop()
        if problem.isGoalState(node[0]) == True:
            return node[1]
        if node[0] not in closed:
            closed.add(node[0])
            actionsSoFar = node[1]
            costSoFar = node[2]
            for successor in problem.getSuccessors(node[0]):
                newActions = actionsSoFar[:]
                newActions.append(successor[1])
                newCost = costSoFar
                newCost += successor[2]
                fringe.push((successor[0], newActions, newCost), newCost)
コード例 #15
0
ファイル: search.py プロジェクト: maikhaihuy/PacmanUsePython
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    # Visited
    visited = []
    # Declare priority queue
    priorityQueueNode = PriorityQueue()
    # Start state
    priorityQueueNode.push((problem.getStartState(),[]),0)

    while not priorityQueueNode.isEmpty():
        currentState, actions = priorityQueueNode.pop()

        if currentState not in visited:
            #print "Current node ", currentNode
            if problem.isGoalState(currentState):
                return actions
            
            visited.append(currentState)

            seccessors = problem.getSuccessors(currentState)

            for state, action, cost in seccessors:
                if state not in visited:
                    tempActions = actions + [action]
                    priorityQueueNode.push((state, tempActions), problem.getCostOfActions(tempActions))
                    #visited.append(state)

    return []
コード例 #16
0
ファイル: search.py プロジェクト: Jornason/Class-Projects
def uniformCostSearch(problem):
  "Search the node of least total cost first. "
  "*** YOUR CODE HERE ***"
  from util import PriorityQueue
  
  pathConstructDict = {}
  priorityQueue = PriorityQueue()
  costToNode = {}
  
  for successor in problem.getSuccessors(problem.getStartState()):
    priorityQueue.push((successor, None), successor[2]) #push successor and its priority is its path cost

  costToNode[problem.getStartState()] = 0

  while(not priorityQueue.isEmpty()):
    expansion = priorityQueue.pop()
    pathConstructDict[expansion[0]] = expansion[1]

    if(expansion[1] != None):
      costToNode[expansion[0][0]] = costToNode[expansion[1][0]] + expansion[0][2]
    else:
      costToNode[expansion[0][0]] = expansion[0][2]

    if(problem.isGoalState(expansion[0][0])):
      return pathConstructor(expansion[0], pathConstructDict)

    for successor in problem.getSuccessors(expansion[0][0]):
      if(successor[0] not in costToNode):
        priorityQueue.push((successor, expansion[0]), costToNode[expansion[0][0]] + successor[2])

  return None
コード例 #17
0
ファイル: search.py プロジェクト: Jornason/Class-Projects
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"

  #A* is just UCS with g(n) + h(n)
  from util import PriorityQueue
  
  pathConstructDict = {}
  priorityQueue = PriorityQueue()
  costToNode = {}
  
  for successor in problem.getSuccessors(problem.getStartState()):
    priorityQueue.push((successor, None), successor[2] + heuristic(successor[0], problem)) #push successor and its priority is its path cost for a* it is g(n) + h(n)

  costToNode[problem.getStartState()] = 0

  while(not priorityQueue.isEmpty()):
    expansion = priorityQueue.pop()
    pathConstructDict[expansion[0]] = expansion[1]

    if(expansion[1] != None):
      costToNode[expansion[0][0]] = costToNode[expansion[1][0]] + expansion[0][2]
    else:
      costToNode[expansion[0][0]] = expansion[0][2]

    if(problem.isGoalState(expansion[0][0])):
      return pathConstructor(expansion[0], pathConstructDict)

    for successor in problem.getSuccessors(expansion[0][0]):
      if(successor[0] not in costToNode):
        priorityQueue.push((successor, expansion[0]), costToNode[expansion[0][0]] + successor[2] + heuristic(successor[0], problem))

  return None
コード例 #18
0
ファイル: search.py プロジェクト: maikhaihuy/PacmanUsePython
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    # Visited
    visited = []
    # Declare priority queue
    priorityQueueNode = PriorityQueue()
    # Start state
    priorityQueueNode.push((problem.getStartState(),[]),0)

    while not priorityQueueNode.isEmpty():
        currentState, actions = priorityQueueNode.pop()

        if currentState not in visited:
            #print "Current node ", currentNode
            if problem.isGoalState(currentState):
                return actions
            
            visited.append(currentState)

            seccessors = problem.getSuccessors(currentState)

            for state, action, cost in seccessors:
                if state not in visited:
                    tempActions = actions + [action]
                    priorityQueueNode.push((state, tempActions), problem.getCostOfActions(tempActions) + heuristic(state, problem))

    return []
コード例 #19
0
ファイル: search.py プロジェクト: TrungMDang/TCSS435
def aStarSearch(problem, heuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    """
    Only A* can find dots in openMaze. Path looks like a staircase.
    """
    path = list()
    parentChild = list()
    print "Problem: ", problem
    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    print "Start's successors:", problem.getSuccessors(problem.getStartState())
    if problem.isGoalState(problem.getStartState()):
        return None
    explored = list()
    frontier = PriorityQueue()
    #tuple = (problem.getStartState(), float("inf"))
    frontier.push(problem.getStartState(), float("inf"))
    while(not frontier.isEmpty()):
        state = frontier.pop()      #state = [(x, y), cost]
        explored.append(state)
        if (problem.isGoalState(state)):
            #print "Found..."
            path = backtracking(problem, state, parentChild)
            return path
        for successor in problem.getSuccessors(state):
            #print "Successor: ", successor
            if (not successor[0] in explored):
                #print("State[1] ", state[1])
                cost = successor[2] + heuristic(state, problem) #cost = stepCost +currentNodeCost
                parentChild.append((state, successor[1], successor[0]))
                frontier.push(successor[0], cost)
    return None
コード例 #20
0
ファイル: search.py プロジェクト: TrungMDang/TCSS435
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    path = list()
    parentChild = list()
    print "Problem: ", problem
    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    print "Start's successors:", problem.getSuccessors(problem.getStartState())

    if problem.isGoalState(problem.getStartState()):
        return None
    explored = list()
    frontier = PriorityQueue()
    #tuple = (problem.getStartState(), float("inf"))
    frontier.push(problem.getStartState(), float("inf"))
    while(not frontier.isEmpty()):
        state = frontier.pop()      #state = [(x, y), cost]
        explored.append(state)
        if (problem.isGoalState(state)):
            #print "Found..."
            path = backtracking(problem, state, parentChild)
            return path
        for successor in problem.getSuccessors(state):
            
            #print "Successor: ", successor
            if (not successor[0] in explored):
                cost = successor[2] + state[1]
                parentChild.append((state, successor[1], successor[0]))
                frontier.push(successor[0], cost)
    return None
コード例 #21
0
ファイル: search.py プロジェクト: yttfwang/cs188-proj1
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import PriorityQueue
    s = Directions.SOUTH
    w = Directions.WEST
    e = Directions.EAST
    n = Directions.NORTH
    
    visited = [None] # list of states (each state is a position in this case)
    pq = PriorityQueue() # contains pairs. each pair's first elem is a list of actions. second elem is state
    pq.push([[], problem.getStartState()], 0)

    while (not pq.isEmpty()):
        top = pq.pop() # this is the top of the stack
        actions = top[0]
        state = top[1]
        if (state not in visited):
            if problem.isGoalState(state):
                return actions
            
            visited.append(state)
            
            for child in problem.getSuccessors(state):
            
                tempActions = actions[:]
                tempActions.append(child[1])
                totalCostOfActions = problem.getCostOfActions(tempActions) + heuristic(child[0], problem)
                pq.push([tempActions, child[0]], totalCostOfActions)
    return None
コード例 #22
0
ファイル: search.py プロジェクト: azimmomin/Search_Pacman
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    closed = []
    closedSet = sets.Set(closed)
    fringe = PriorityQueue()
    for child in problem.getSuccessors(problem.getStartState()):
        path = [child[1]]
        fringe.push((child[0], path, child[2]), child[2] + heuristic(child[0], problem))
    closedSet.add(problem.getStartState())
    
    while( not(fringe.isEmpty()) ):
        nodePos, nodeDir, nodeCost = fringe.pop()
        if (problem.isGoalState(nodePos)):
            return nodeDir
        if (nodePos not in closedSet):
            successors = problem.getSuccessors(nodePos)
            closedSet.add(nodePos)
            path = [nodeDir]
            for childNode in successors:
                cost = nodeCost + childNode[2]
                path = nodeDir + [childNode[1]]
                childNode = [childNode[0], path , cost]
                fringe.push(childNode, cost + heuristic(childNode[0], problem))

    return -1
コード例 #23
0
ファイル: search.py プロジェクト: DominikDitoIvosevic/Uni
def aStarSearch(problem, heuristic=nullHeuristic):
    closedSet = set()
    openSet = PriorityQueue()
    visited = set()
    start = problem.getStartState()
    cameFrom = dict()

    gScore = dict()
    gScore[start] = 0
    fScore = dict()
    fScore[start] = heuristic(start, problem)

    openSet.push(start, fScore[start])
    visited.add(start)

    while not openSet.isEmpty():
        current = openSet.pop()
        if problem.isGoalState(current):
            return reconstruct(cameFrom, current, start)
        closedSet.add(current)
        for successor in problem.getSuccessors(current):
            succ = successor[0]
            action = successor[1]
            cost = successor[2]
            #(successor, action, stepCost)
            if succ in closedSet:
                continue
            fromStart = gScore[current] + cost
            if succ in visited and fromStart >= gScore[succ]:
                continue
            cameFrom[succ] = (current, action)
            gScore[succ] = fromStart
            fScore[succ] = fromStart + heuristic(succ, problem)
            visited.add(succ)
            openSet.push(succ, fScore[succ])
コード例 #24
0
ファイル: search.py プロジェクト: chabior/ai-search
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""

    fringe = PriorityQueue()
    closed = []

    startState = (problem.getStartState(), None, 0, [], 0)
    fringe.push(startState, 0)

    while True:
        if fringe.isEmpty():
            util.raiseNotDefined()

        node = fringe.pop()

        if problem.isGoalState(node[0]):
            return node[3]


        if node[0] not in closed:
            closed.append(node[0])

            for child in problem.getSuccessors(node[0]):
                childNode = list(child)
                childNode.append(list(node[3]))
                childNode[3].append(childNode[1])
                childNode.append(childNode[2] + node[4])
                fringe.push(childNode, childNode[4] + heuristic(childNode[0], problem))
コード例 #25
0
ファイル: search.py プロジェクト: chabior/ai-search
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    fringe = PriorityQueue()
    closed = []

    startState = (problem.getStartState(), None, 0, [])
    fringe.push(startState, 0)

    while True:
        if fringe.isEmpty():
            return None #failure?

        node = fringe.pop()

        if problem.isGoalState(node[0]):
            return node[3]

        if node[0] not in closed:
            closed.append(node[0])

            for child in problem.getSuccessors(node[0]):
                childNode = list(child)
                childNode.append(list(node[3]))
                childNode[3].append(childNode[1])
                fringe.push(childNode, len(childNode[3]))
コード例 #26
0
ファイル: search.py プロジェクト: acrobat3/search_problem
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    from game import Directions
    from util import PriorityQueue

    pqueue = PriorityQueue()
    startNode = problem.getStartState()
    pqueue.push((startNode, []), 0)
    visitedList = []
    oldCost = {}
    oldCost[startNode] = None

    while not pqueue.isEmpty():
        current, actions = pqueue.pop()
        if problem.isGoalState(current):
            return actions
        visitedList.append(current)
        for coord, direction, steps in problem.getSuccessors(current):
            new_actions = actions + [direction]
            priority = problem.getCostOfActions(new_actions)
            if not coord in visitedList or priority < oldCost[coord]:
                oldCost[coord] = priority
                visitedList.append(coord)
                pqueue.push((coord, new_actions), priority)
    return []

    util.raiseNotDefined()
コード例 #27
0
ファイル: search.py プロジェクト: dowd83/Pacman-Search
def aStarSearch(problem, heuristic=nullHeuristic):

    from util import PriorityQueue
    from game import Directions
    
    actions = []
    
    frontier = PriorityQueue()
    frontier.push((problem.getStartState(), [], 0), 0)
    visited = []

    while (frontier.isEmpty() == False):
        (currentS, currentP, currentC) = frontier.pop()
        if (problem.isGoalState(currentS) == True):
            actions = currentP
            break
        if (visited.count(currentS) == 0):
            visited.append(currentS)
            successors = problem.getSuccessors(currentS)
            for i in range(0,len(successors)):
                (neighbor, direction, cost) = successors[i]
                if (visited.count(neighbor) == 0):
                    frontier.push((neighbor, (currentP +[direction]), (currentC + cost)), (currentC + cost + heuristic(neighbor, problem)))
                
    return actions


    
    util.raiseNotDefined()
コード例 #28
0
ファイル: search.py プロジェクト: erikm0111/AIclass
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    
    from util import PriorityQueue

    queueOpen = PriorityQueue()

    rootNode = SearchNode(problem.getStartState(), None, None, 0, 0)

    if problem.isGoalState(rootNode.position):
        return []

    queueOpen.push(rootNode, 0)
    visited = {}

    while not queueOpen.isEmpty():
        currentNode = queueOpen.pop()
        if currentNode.position in visited:
            continue
        if problem.isGoalState(currentNode.position):
            return currentNode.backtrack()
        visited[currentNode.position] = True
        for succ in expand(problem, currentNode):
            if succ.position not in visited:
                temp = SearchNode(succ.position, currentNode, succ.transition, succ.cost, 0)
                queueOpen.push(temp, succ.cost)
コード例 #29
0
ファイル: search.py プロジェクト: joshuaburkhart/CIS_571
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()
  node = (problem.getStartState(), [], 0)
  PriorityQueue.push(frontier, node, node[2] + heuristic(node[0], problem))
  explored_states = set([])

  if problem.isGoalState(node[0]):
      return node[1]
  elif PriorityQueue.isEmpty(frontier):
      return None
  else:
      while not PriorityQueue.isEmpty(frontier):
          new_node = PriorityQueue.pop(frontier)
          explored_states.add(new_node[0])
	  successor_candidates = problem.getSuccessors(new_node[0])
          if node[0][0] == (13, 5):
	      print "successors: ", successor_candidates
          if successor_candidates:
	      successor_candidates.reverse()
              for candidate in successor_candidates:
		  if candidate[0] not in explored_states:
		      c_path = list(new_node[1])
	              c_path.append(candidate[1])
		      # if candidate[0] not in explored_states:
	              if problem.isGoalState(candidate[0]):
		          return c_path
	              PriorityQueue.push(frontier, (candidate[0], c_path, new_node[2] + candidate[2]), new_node[2] + heuristic(candidate[0], problem))
コード例 #30
0
ファイル: search.py プロジェクト: chabior/ai-search
def uniformCostSearch(problem):
    """Search the node of least total cost first."""

    fringe = PriorityQueue()
    closed = []

    startState = (problem.getStartState(), None, 0, [], 0)
    fringe.push(startState, 0)

    while True:
        if fringe.isEmpty():
            util.raiseNotDefined()

        node = fringe.pop()

        if problem.isGoalState(node[0]):
            return node[3]

        if node[0] not in closed:
            closed.append(node[0])

            for child in problem.getSuccessors(node[0]):
                childNode = list(child)
                childNode.append(list(node[3]))
                childNode[3].append(childNode[1])
                childNode.append(childNode[2] + node[4])

                fringe.push(childNode, childNode[4])
コード例 #31
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"

    from util import PriorityQueue
    priorityQueue = PriorityQueue()
    priorityQueue.push((problem.getStartState(), [], 0), 0)
    visited = []

    while not priorityQueue.isEmpty():
        temp, path, cost = priorityQueue.pop()

        if problem.isGoalState(temp):
            return path

        if temp not in visited:
            visited.append(temp)
            for i in problem.getSuccessors(temp):
                temp = (i[0], path + [i[1]], cost + i[2])
                priorityQueue.update(temp, cost + i[2])

    util.raiseNotDefined()
コード例 #32
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue
    visited = set() # close table for graph search
    q = PriorityQueue()
    #each item of queue is (pos,actions) where actions is a tuple
    #and should not change is the feature
    q.push((problem.getStartState(), ()), problem.getCostOfActions([]))
    while not q.isEmpty():
        curState, actions = q.pop()
        if problem.isGoalState(curState):
            return list(actions)
        if  curState in visited:
            continue
        visited.add(curState)
        successors  = problem.getSuccessors(curState)
        for (nextState, action, cost ) in successors:
            newActions = list(actions) #make a deep copy
            newActions.append(action)
            q.push((nextState, tuple(newActions)), problem.getCostOfActions(newActions))
    util.raiseNotDefined()
コード例 #33
0
ファイル: search.py プロジェクト: yibei/neu
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    if problem.isGoalState(problem.getStartState()):
        return []
    from util import PriorityQueue
    q = PriorityQueue()
    visited = []

    start = problem.getStartState()
    q.push((start, [], 0), 0)

    while not q.isEmpty():
        node, path, cost_till_here = q.pop()
        if problem.isGoalState(node):
            return path
        elif node not in visited:
            visited.append(node)
            for successor in problem.getSuccessors(node):
                if successor[0] not in visited:
                    cost = successor[2] + cost_till_here
                    q.push((successor[0], path + [successor[1]], cost), cost)
    return []
コード例 #34
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    from util import PriorityQueue

    # Cria noh do estado inicial
    initial_state = problem.getStartState()
    node = Node(state=initial_state,
                path=[],
                path_cost=0,
                obj_cost=heuristic(initial_state, problem))

    # Fronteira
    openSet = PriorityQueue()
    openSet.push(node, node.getCost())
    # Nos explorados
    closedSet = []

    while not openSet.isEmpty():
        # Escolhe noh com menor custo
        node = openSet.pop()
        closedSet.append(node)
        # Checa se estado atual eh estado meta
        if problem.isGoalState(node.state):
            return node.path
        # Gera os filhos do estado atual
        for state, direction, cost in problem.getSuccessors(node.state):
            newNodePath = node.path + [direction]
            newNodePathCost = node.path_cost + cost
            newNode = Node(state=state,
                           path=newNodePath,
                           path_cost=newNodePathCost,
                           obj_cost=heuristic(state, problem))
            if newNode not in closedSet:
                # Adiciona novo noh caso ainda nao exista
                # se jah existir noh atualiza o custo se o novo custo for menor
                openSet.update(newNode, newNode.getCost())

    # Caso nao encontre nenhum caminho, nao faz nada
    return []
コード例 #35
0
ファイル: search.py プロジェクト: jacqmhong/AI-projs
def aStarSearch(problem,
                heuristic=nullHeuristic):  # heuristic = func(state, problem)
    """Search the node that has the lowest combined cost and heuristic first."""
    from util import PriorityQueue

    actions = PriorityQueue()
    explored = set()
    actions.push((problem.getStartState(), []),
                 heuristic(problem.getStartState(), problem))

    while actions.isEmpty() == False:
        state, action = actions.pop()
        if problem.isGoalState(state):
            return action
        if state not in explored:
            explored.add(state)
            for successor, act, cost in problem.getSuccessors(state):
                actions.push((successor, action + [act]),
                             cost + problem.getCostOfActions(action) +
                             heuristic(successor, problem))

    util.raiseNotDefined()
コード例 #36
0
ファイル: search.py プロジェクト: Xiaocheng-Zhang/CS4100
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()
    start = problem.getStartState()
    path = []
    frontier.push((start, path, 0), 0)
    explored = []
    while not frontier.isEmpty():
        cur_state, cur_path, cur_cost = frontier.pop()
        if cur_state not in explored:
            explored.append(cur_state)
            if problem.isGoalState(cur_state):
                return cur_path
            successors = problem.getSuccessors(cur_state)
            for successor, action, cost in successors:
                new_path = cur_path + [action]
                new_cost = cur_cost + cost
                new_heuristic_cost = new_cost + heuristic(successor, problem)
                frontier.push((successor, new_path, new_cost),
                              new_heuristic_cost)
コード例 #37
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
    pq = PriorityQueue()
    startState = problem.getStartState()
    visitedList = {}
    action = []
    cost = 0
    pq.push((startState, action, cost), cost)
    while not pq.isEmpty():
        head = pq.pop()
        if problem.isGoalState(head[0]):
            return head[1]
        if head[0] not in visitedList:
            visitedList[head[0]] = True
            for successor_nodes, act, co in problem.getSuccessors(head[0]):
                if successor_nodes and successor_nodes not in visitedList:
                    pq.push((successor_nodes, head[1] + [act], head[2] + co),
                            head[2] + co + heuristic(successor_nodes, problem))

    util.raiseNotDefined()
コード例 #38
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    from util import PriorityQueue
    priorityQueue = PriorityQueue()
    priorityQueue.push((problem.getStartState(), [], 0), 0)
    visited = []

    while not priorityQueue.isEmpty():
        temp, path, cost = priorityQueue.pop()

        if problem.isGoalState(temp):
            return path

        if temp not in visited:
            visited.append(temp)
            for i in problem.getSuccessors(temp):
                temp = (i[0], path + [i[1]], cost + i[2])
                priorityQueue.update(temp, cost + i[2] + heuristic(i[0], problem))

    util.raiseNotDefined()
コード例 #39
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

    open_list = PriorityQueue()
    open_list.push([(problem.getStartState(), '', 0)], 0)

    visited_nodes = []
    final_path = []

    while not open_list.isEmpty():
        node = open_list.pop()
        state = node[-1][0]

        if problem.isGoalState(state):
            for n in node:
                if n[1] != '':
                    final_path.append(n[1])
            return final_path

        if state not in visited_nodes:
            visited_nodes.append(state)

            for successor in problem.getSuccessors(state):
                new_path = node[:] + [successor]

                new_path_actions = []

                for n in node:
                    if n[1] != '':
                        new_path_actions.append(n[1])

                new_path_actions.append(successor[1])

                new_path_cost = problem.getCostOfActions(new_path_actions) + heuristic(successor[0], problem)
                open_list.push(new_path, new_path_cost)

    return []
コード例 #40
0
ファイル: myTeam.py プロジェクト: richarduuz/PacmanContest
  def wAstarSearch(self, gameState):
    myPos = gameState.getAgentState(self.index).getPosition()
    actions = []

    from util import PriorityQueue
    open = PriorityQueue()
    closed = {}
    closed[gameState] = 999999


    open.push((gameState, [], 0), 0 + self.foodHeuristic(gameState))
    while not open.isEmpty():
      gameState, actions, cost = open.pop()
      if gameState not in closed.keys() or closed[gameState] > cost + self.foodHeuristic(gameState):
        closed[gameState] = cost + self.foodHeuristic(gameState)
        if self.isFoodTerminal(gameState):
          return actions
        else:
          currentActions = gameState.getLegalActions(self.index)
          for action in currentActions:
            successor = self.getSuccessor(gameState, action)
            open.update((successor, actions+[action], cost+1), cost+1+self.foodHeuristic(successor))
コード例 #41
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 --frameTime 0
    # python pacman.py -l mediumMaze -p SearchAgent -a fn=astar,heuristic=manhattanHeuristic --frameTime 0

    # If start state is the goal, stop and move nowhere
    if (problem.isGoalState(problem.getStartState())):
        return ['Stop']

    from util import PriorityQueue
    queue = PriorityQueue()
    queue.push((problem.getStartState(), [], 0), 0)

    # Created a list of visited nodes
    visited = set()

    while not queue.isEmpty():
        #Pop the first item from the queue
        currentPos, currentPath, currentCost = queue.pop()
        # print "current pos: ", currentPos, "\t current cost: ", currentCost

        # if solution found, exit
        if (problem.isGoalState(currentPos)):
            return currentPath

        # If it hasn't been visited before, perform this:
        if (not currentPos in visited):
            visited.add(currentPos)

            for successor in problem.getSuccessors(
                    currentPos):  # For every successor of the current node
                newPath = list(currentPath)  # copy the current path
                newPath.append(
                    successor[1])  # add the new direction to the path
                newCost = currentCost + successor[
                    2]  # add the new cost (for clarity) + the heuristic value
                queue.push(
                    (successor[0], newPath, newCost), newCost +
                    heuristic(successor[0], problem))  # push into the queue
コード例 #42
0
ファイル: search.py プロジェクト: tranhieu956230/pacman-cs188
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    startState = (problem.getStartState(), "", 0)
    paths = PriorityQueue()
    paths.push({"path": [startState], "cost": startState[2]}, startState[2])
    visitedNodes = []
    while not paths.isEmpty():
        minPath = paths.pop()
        currentPosition = minPath["path"][-1][0]
        if not currentPosition in visitedNodes:
            visitedNodes.append(currentPosition)
            if problem.isGoalState(currentPosition):
                return [p[1] for p in minPath["path"][1:]]
            successors = problem.getSuccessors(currentPosition)
            for successor in successors:
                if not successor[0] in visitedNodes:
                    newPath = {
                        "path": minPath["path"] + [successor],
                        "cost": minPath["cost"] + successor[2]
                    }
                    paths.push(newPath, newPath["cost"])
コード例 #43
0
def aStarSearch(problem, heuristic=nullHeuristic):
    from util import Queue
    from util import Stack
    from util import PriorityQueue
    from game import Directions
    #Initialize structures
    start = problem.getStartState()
    frontier = PriorityQueue()
    cost = {}
    partial_sols = {}
    solution = []
    #Using for start node
    frontier.push(start, 0)
    cost[start] = 0
    partial_sols[start] = solution[:]

    #Start moving through nodes
    while not frontier.isEmpty():
        current = frontier.pop()
        solution = partial_sols[current]
        #Check problem solution
        if problem.isGoalState(current):
            return partial_sols[current]
        #possible movements
        for successor in problem.getSuccessors(current):
            nextnode, action, action_cost = successor
            new_cost = cost[
                current] + action_cost  #Amount cost + move cost + heuristics
            if nextnode not in cost or new_cost < cost[
                    nextnode]:  #node has no cost assigned or newcost is less than the current cost
                cost[nextnode] = new_cost  #update cost
                priority = new_cost + heuristic(nextnode, problem)
                frontier.push(nextnode,
                              priority)  #set item with the cost as priority
                newsolution = solution[:]  #copy current solution and add the action
                newsolution.append(action)
                partial_sols[nextnode] = newsolution

    util.raiseNotDefined()
コード例 #44
0
ファイル: search.py プロジェクト: joshkarlin/CS188-Project-1
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    

    fringe = PriorityQueue()
    counts = Counter()
    current = (problem.getStartState(), [])    
    counts[str(current[0])] += heuristic(current[0], problem)
    fringe.push(current, counts[str(current[0])])
    closed = []
    
    while not fringe.isEmpty():
        node, path = fringe.pop()
        if problem.isGoalState(node):
            return path
        if not node in closed:
            closed.append(node)
            for coord, move, cost in problem.getSuccessors(node):
                newpath = path + [move]
                counts[str(coord)] = problem.getCostOfActions(newpath)
                counts[str(coord)] += heuristic(coord, problem)
                fringe.push((coord, newpath), counts[str(coord)]) 
コード例 #45
0
ファイル: search.py プロジェクト: agiridharan/Course-Work
def foodAStarSearch(start, goal, walls):
    from util import PriorityQueue

    moveVector = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    pq = PriorityQueue()
    explored = {}
    maxWidth = abs(start[0] - goal[0])
    maxHeight = abs(start[1] - goal[1])

    if start == goal:
        return 0

    pq.push((start, 0, 0), 0)
    explored[start] = True
    nodesPopped = 0

    while not pq.isEmpty():
        currNode = pq.pop()
        currPos, currCost, currSteps = currNode

        for move in moveVector:
            nextPos = (currPos[0] + move[0], currPos[1] + move[1])

            if nextPos not in explored:
                # check that move is within bounds
                nextWidth = abs(nextPos[0] - goal[0])
                nextHeight = abs(nextPos[1] - goal[1])
                if nextWidth <= maxWidth and nextHeight <= maxHeight:
                    if not walls[nextPos[0]][nextPos[1]]:

                        #check for goal
                        if nextPos == goal:
                            return currSteps + 1

                        explored[nextPos] = True
                        nextCost = ((nextPos[0] - goal[0]) ** 2 + (nextPos[1] - goal[1]) ** 2) ** 0.5
                        pq.push((nextPos, nextCost, currSteps + 1), nextCost)

    return 999999
コード例 #46
0
    def AStar(self, gameState, destination):
        from util import PriorityQueue
        visited, movements, costs, start_cost = [], {}, {}, 0
        startAgentState = gameState.getAgentState(self.index)
        startLoc = startAgentState.getPosition()
        movements[startLoc] = []
        costs[startLoc] = 0
        visited.append(startLoc)
        priorityQueue = PriorityQueue()
        priorityQueue.push(gameState, start_cost)

        while not priorityQueue.isEmpty():
            currGameState = priorityQueue.pop()
            currLoc = currGameState.getAgentState(self.index).getPosition()

            if currLoc == destination:
                # print "movements: ",movements[currLoc]
                return movements[currLoc]
                # return movements[currGameState]

            actions = currGameState.getLegalActions(self.index)

            for action in actions:
                succGameState = self.getSuccessor(currGameState, action)
                succLoc = succGameState.getAgentState(self.index).getPosition()
                newCost = 1
                next_cost = costs[currLoc] + newCost

                if succLoc not in visited or next_cost < costs[succLoc]:
                    visited.append(succLoc)
                    movements[succLoc] = []

                    pre = movements[currLoc][:]
                    pre.append(action)
                    movements[succLoc].extend(pre)
                    costs[succLoc] = next_cost
                    heurisitic = self.Heuristic(succLoc, destination)
                    priority = next_cost + heurisitic
                    priorityQueue.push(succGameState, priority)
コード例 #47
0
    def runValueIteration(self):
        "*** YOUR CODE HERE ***"
        prob = self.mdp
        predecessors = self.getPredecessors(prob)
        from util import PriorityQueue
        heap = PriorityQueue()
        states = prob.getStates()
        for state in states:
            if not prob.isTerminal(state):
                actions = prob.getPossibleActions(state)
                value = []

                for action in actions:

                    value.append(self.computeQValueFromValues(state, action))

                diff = abs(self.values[state] - max(value))

                heap.push(state, -1 * diff)
        for i in range(self.iterations):
            if heap.isEmpty():
                break
            s = heap.pop()
            if not prob.isTerminal(s):
                self.bellmanUpdate(s)
                if predecessors[s]:
                    for pred in predecessors[s]:
                        predactions = prob.getPossibleActions(pred)
                        value = []

                        for predaction in predactions:
                            value.append(
                                self.computeQValueFromValues(pred, predaction))

                        preddiff = abs(self.values[pred] - max(value))

                        if preddiff > self.theta:
                            heap.push(pred, -1 * preddiff)
コード例 #48
0
def uniformCostSearch(problem):
    '''
    return a path to the goal
    '''
    # TODO 07
    from util import PriorityQueue

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

    print(problem.getStartState())
    visited = []

    while not frontier.isEmpty():

        #print(f"\n\nfrontier: {frontier}")

        curNode, path, curCost = frontier.pop()
        #print(f"\n\tcurCost: {curCost}, curNode: {curNode}, path: {path}")

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

            if problem.isGoalState(curNode):
                print(f"Path to goal: {path}")
                return path

            successors = problem.getSuccessors(curNode)
            #print(f"\n\t\t{successors}")

            for neighborNode, direction, cost in successors:
                #if neighbor not in visited:
                print(
                    f"\n\nneighbor: {neighborNode}, direction: {direction}, cost: {cost}"
                )
                frontier.update(
                    (neighborNode, path + [direction], curCost + cost),
                    curCost + cost)
コード例 #49
0
ファイル: search.py プロジェクト: fcm2009/PacmanAI
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    stateQueue = PriorityQueue()

    state = problem.getStartState()
    state = [(state, "Stop", 0)]
    stateQueue.push(state, 0)

    while not problem.isGoalState(state[len(state) - 1][0]):
        state = stateQueue.pop()
        successors = problem.getSuccessors(state[len(state) - 1][0])
        for successor in successors:
            if successor[0] not in [position[0] for position in state]:
                tmp = state + [successor]
                stateQueue.push(
                    tmp,
                    problem.getCostOfActions([action[1] for action in tmp]))
    return [direction[1] for direction in state]
コード例 #50
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    state = ()
    state = problem.getStartState()
    costTillNow = 0
    actionsTillnow = []
    visited_states = []

    new_pq = PriorityQueue()
    new_pq.push((state, actionsTillnow, costTillNow), costTillNow)

    while True:

        temp = new_pq.pop()
        state = temp[0]
        costTillNow = temp[2]
        actionsTillnow = temp[1]

        if (problem.isGoalState(state)):
            print "Done!!"
            return actionsTillnow
            break
        elif (not (state in visited_states)):
            visited_states.append(state)
        else:
            continue

        # successors=()
        successors = problem.getSuccessors(state)
        # print state
        # print costTillNow
        # print actionsTillnow
        # print successors
        # temp_actions=[]
        for i in successors:

            temp_actions = actionsTillnow[:]
            temp_actions.append(i[1])
            tempCost = costTillNow + i[2]
            new_pq.push((i[0], temp_actions, tempCost), tempCost)

    util.raiseNotDefined()
コード例 #51
0
ファイル: search.py プロジェクト: preritt/Udacity-AIND
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"

    start_state = problem.getStartState()
    frontier = PriorityQueue()  # queue for frontier
    explored = set()
    frontier.push((start_state, [], 0), heuristic(start_state, problem))
    # [] -> path required to reach here
    # 0 step cost to reach here
    # heuristic(start_state, problem) estimated heurisic distance to reach goal

    while not frontier.isEmpty():
        location, path_to_reach_here, cost_to_reach_here = frontier.pop()
        # explored.add(location)
        if problem.isGoalState(location):
            return path_to_reach_here
        # print location, list(explored)
        # if location not in explored:
        # print "location not in (explored)"
        explored.add(location)
        for neighbor in problem.getSuccessors(location):
            neighbor_location, neighbor_action, neighbor_step_cost = neighbor
            frontier_list = [
                element[0] for element in frontier.heap
            ]  # get a list of all elements in frontier s.union(t)
            # frontier_union_explored = list(set(frontier_list) + explored)
            frontier_union_explored = list(set(frontier_list).union(explored))
            if neighbor_location not in frontier_union_explored:
                neighbor_total_cost_heuristic = cost_to_reach_here + neighbor_step_cost + heuristic(
                    neighbor_location, problem)  # fn
                path_till_neighbor = path_to_reach_here + [neighbor_action]
                cost_to_reach_to_neighbor = cost_to_reach_here + neighbor_step_cost
                frontier.push((neighbor_location, path_till_neighbor,
                               cost_to_reach_to_neighbor),
                              neighbor_total_cost_heuristic)
            elif neighbor_location in frontier_list:
                print "Take care"
コード例 #52
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"

    #A* is just UCS with g(n) + h(n)
    from util import PriorityQueue

    pathConstructDict = {}
    priorityQueue = PriorityQueue()
    costToNode = {}

    for successor in problem.getSuccessors(problem.getStartState()):
        priorityQueue.push(
            (successor, None), successor[2] + heuristic(successor[0], problem)
        )  #push successor and its priority is its path cost for a* it is g(n) + h(n)

    costToNode[problem.getStartState()] = 0

    while (not priorityQueue.isEmpty()):
        expansion = priorityQueue.pop()
        pathConstructDict[expansion[0]] = expansion[1]

        if (expansion[1] != None):
            costToNode[expansion[0]
                       [0]] = costToNode[expansion[1][0]] + expansion[0][2]
        else:
            costToNode[expansion[0][0]] = expansion[0][2]

        if (problem.isGoalState(expansion[0][0])):
            return pathConstructor(expansion[0], pathConstructDict)

        for successor in problem.getSuccessors(expansion[0][0]):
            if (successor[0] not in costToNode):
                priorityQueue.push((successor, expansion[0]),
                                   costToNode[expansion[0][0]] + successor[2] +
                                   heuristic(successor[0], problem))

    return None
コード例 #53
0
    def aStarSearch(self, currentPosition, goalStates, nonGoalStates,
                    gameState):

        from util import PriorityQueue

        frontier = PriorityQueue()

        actions = []
        closed = []
        evaluation = 0
        cost = 0
        minimum = 10000
        if currentPosition in goalStates:
            return None
        for positions in self.defensivePositions:
            distance = self.getMazeDistance(positions, currentPosition)
            if distance < minimum:
                minimum = distance
        frontier.push((currentPosition, []), minimum)
        while (True):

            if frontier.isEmpty():
                return None

            node, path = frontier.pop()

            if node not in closed:
                closed.append(node)
                if node in goalStates:
                    return path
                for successor in self.getSuccessors(node):
                    actions = path + [successor[1]]
                    cost += 1
                    evaluation = cost + self.heuristic(
                        gameState, successor[0], goalStates, nonGoalStates)
                    frontier.push((successor[0], actions), evaluation)

        util.raiseNotDefined()
コード例 #54
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    priorityqueue = PriorityQueue()
    priorityqueue.push((problem.getStartState(), [], 0),0)
    visitedNode = []
    while priorityqueue:
        current = priorityqueue.pop()
        if current[0] not in visitedNode:
            visitedNode.append(current[0])
            if problem.isGoalState(current[0]):
                return current[1]
            nextNodes = problem.getSuccessors(current[0])
            for neighbours in nextNodes:
                currentPath = current[1] + [neighbours[1]]
                currentCost = current[2] + neighbours[2]
                priorityqueue.push((neighbours[0],currentPath, currentCost),currentCost)
コード例 #55
0
ファイル: search.py プロジェクト: JohnPapad/AIMA-Pac-Man
def aStarSearch(problem, heuristic=nullHeuristic):  # it is almost the same code as ucs above but with some minor differences again
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    #util.raiseNotDefined()

    from util import PriorityQueue
    path_to_node = []
    path_cost = 0
    problem_start_state = problem.getStartState()
    start_node = [problem_start_state, path_to_node]  # no need to store the path_cost at the node this time
    frontier = PriorityQueue()
    frontier.push(start_node, path_cost)
    explored = set()

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

        parent = frontier.pop()

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

        if parent[0] not in explored:
            explored.add(parent[0])
            children = problem.getSuccessors(parent[0])
            for child in children:
                child_state = child[0]
                child_action = child[1]

                if child_state not in explored:
                    path_to_child = list(parent[1])
                    path_to_child.append(child_action)
                    heuristic_cost = heuristic(child_state, problem)
                    cost_of_actions = problem.getCostOfActions(path_to_child)  #using getCostOfActions to calculate the cost of actions from beginnig to this node
                    total_cost = heuristic_cost + cost_of_actions
                    child = [child_state, path_to_child]
                    frontier.update(child, total_cost)
コード例 #56
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    startState = problem.getStartState()  #getting the start state
    states = PriorityQueue(
    )  #initializing a Priorityqueue because we need to prioritize nodes/path based on the cost
    t = (startState, [], 0
         )  #creating tuple containg state coordinated and path
    states.push(t, 0)  #pushed the tuple to states stack
    expandedStates = [
    ]  #inititalized an empty list to store the visited states/coordinates
    while not states.isEmpty():
        currState, currPath, currCost = states.pop()
        #print "Cuurent State: ", currState, currPath, currCost
        if problem.isGoalState(currState):
            return currPath

        if currState not in expandedStates:
            expandedStates.append(
                currState)  #adding the state to expanded state list
            #print "expandedStates: ", expandedStates
            successors = problem.getSuccessors(currState)  #finding successors
            #print "successors: ", successors
            for succ in successors:
                succState = succ[0]
                succMove = succ[1]
                succCost = succ[2]
                totalCost = currCost + succCost
                succPath = list(currPath)
                hCost = heuristic(succState, problem)
                #print "totalCost: ", totalCost
                #print "curPath: ", curPath
                succPath.append(succMove)
                states.push(
                    (succState, succPath, totalCost),
                    totalCost + hCost)  #adding successors to states stack
    return []
    util.raiseNotDefined()
コード例 #57
0
    def findPathToClosestDot(self, gameState):
        "Returns a path (a list of actions) to the closest dot, starting from gameState"
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition()
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState)

        "*** YOUR CODE HERE ***"

        from util import PriorityQueue

        fila = PriorityQueue()
        colorir = []
        inicial = (startPosition, None, None, [])
        "Tupla formada por (Estado atual, Estado Pai, Ação, Distancia)"
        fila.push(inicial, 0)
        colorir.append(inicial)

        while fila.isEmpty() == False:
            noAtual = fila.pop()
            cord = noAtual[0]

            if food[cord[0]][cord[1]] == True:
                return noAtual[3]
            else:
                for item in problem.getSuccessors(noAtual[0]):
                    est = item[0]
                    aco = item[1]
                    cus = item[2]
                    if est not in colorir:
                        no1 = (est, noAtual, aco)
                        acoesAlcancar = qtdAcoesAlcancar(no1)
                        no2 = (est, noAtual, aco, acoesAlcancar)
                        fila.push(no2, problem.getCostOfActions(no2[3]))
                        colorir.append(est)

        print "FOOOD", food[startPosition[0]][startPosition[1]]
コード例 #58
0
def waStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has has the weighted (x 2) lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE FOR TASK 2 ***"
    from util import PriorityQueue
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    n = Directions.NORTH
    e = Directions.EAST

    Frontier = PriorityQueue()
    closed = set()
    startPoint = problem.getStartState()
    gCostNow = {startPoint: 0}
    fCost = {startPoint: 2 * heuristic(startPoint, problem) + 0}
    actionPath = []
    Frontier.push((startPoint, actionPath), fCost[startPoint])
    parent = {}

    while not Frontier.isEmpty():
        firstNode = Frontier.pop()
        currentPos = firstNode[0]
        actionPath = firstNode[1]

        if problem.isGoalState(currentPos):
            path = [currentPos]
            while path[-1] != startPoint:
                parentNode = parent[path[-1]]
                path.append(parentNode)
            path.reverse()
            #print(path)
            #print(actionPath)
            return actionPath
        if currentPos not in closed:
            closed.add(currentPos)

        for neighbour in problem.getSuccessors(currentPos):
            nodeState = neighbour[0]
            nodeAction = neighbour[1]

            if nodeState not in gCostNow.keys() and nodeState not in closed:
                gCostNow[nodeState] = problem.getCostOfActions(actionPath +
                                                               [nodeAction])
                fCost[nodeState] = gCostNow[nodeState] + 2 * heuristic(
                    nodeState, problem)
                parent[nodeState] = currentPos
                newUpdate(Frontier, (nodeState, actionPath + [nodeAction]),
                          fCost[nodeState])
コード例 #59
0
def uniformCostSearch(problem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    open_list = PriorityQueue()
    open_list.push([(problem.getStartState(), '', 0)], 0)

    visited_nodes = []
    final_path = []

    while not open_list.isEmpty():
        node = open_list.pop()
        state = node[-1][0]

        if problem.isGoalState(state):
            for n in node:
                if n[1] != '':
                    final_path.append(n[1])
            return final_path

        if state not in visited_nodes:
            visited_nodes.append(state)

            for successor in problem.getSuccessors(state):
                new_path = node[:] + [successor]

                new_path_actions = []
                for n in node:
                    if n[1] != '':
                        new_path_actions.append(n[1])

                new_path_actions.append(successor[1])

                new_path_cost = problem.getCostOfActions(new_path_actions)
                open_list.push(new_path, new_path_cost)

    return []
コード例 #60
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    # Once again we use a priority queue, we instead use estimated cost as our priority
    PriorityQueue = util.PriorityQueue()
    for successor in problem.getSuccessors(problem.getStartState()):
        # We calculate the estimated cost by adding our heuristic to the cost
        estCost = successor[2] + heuristic(successor[0], problem)
        PriorityQueue.push((successor, []), estCost)

    # another searching strategy, another empty visited set
    visitedSet = set()

    # Much like before, this checks if a given priority queue contains a given coord
    def pQueueContainsNode(PriorityQueue, coord):
        for item in PriorityQueue.heap:
            if item[0] == coord:
                return True
        return False

    # this loop doesn't end unless we return
    while True:

        # The queue is empty, as are our hopes of finding a solution
        if PriorityQueue.isEmpty():
            return False

        # Pop out that node and path
        currentNode, currentPath = PriorityQueue.pop()

        # We found the way
        if problem.isGoalState(currentNode[0]):
            solution = currentPath + [currentNode[1]]
            # We tell pacman the way
            return solution

        # If we have never been there and it isn't on our fringe
        if not (pQueueContainsNode(PriorityQueue, currentNode[0])) and not (
                setContainsNode(visitedSet, currentNode[0])):
            # Now we been there
            visitedSet.add(currentNode[0])
            path = currentPath + [currentNode[1]]
            # Now we add the successors to the fringe, once again calculating estimated cost and using that as our priority
            for successor in problem.getSuccessors(currentNode[0]):
                estCost = successor[2] + heuristic(successor[0], problem)
                PriorityQueue.push((successor, path), estCost)