Example #1
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    print("The problem is:", problem)
    closed=[]
    fringe=[]
    state=problem.getStartState()
    start_forward_Cost=searchAgents.manhattanHeuristic(state,problem)
    fringe.append((state,[],start_forward_Cost))

    # print("The min index is: ", popindex, "for the following item: ", fringe[popindex])

    while fringe:
        # print("The fringe is:", fringe)
        minimum = min(fringe, key=lambda x: x[2])
        popindex = fringe.index(minimum)
        # print("The minimum value is apparently:", minimum, " and it has the index in fringe of: ", popindex)
        node,actions,Back_Cost=fringe.pop(popindex)
        # print("This is what we chose to pop:", node,actions,cost)
        # input('')
        if problem.isGoalState(node):
            return actions

        if node not in closed:
            closed.append(node)
            for child in problem.getSuccessors(node):
                Forward_cost=searchAgents.manhattanHeuristic(child[0],problem)
                fringe.append((child[0],actions+[child[1]],Back_Cost+Forward_cost+child[2]))

    if not fringe:
        print("the fringe is empty cuz")
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    visited = dict()  #keep on track of the visited nodes for astar algorithm
    node = {}  #node
    node["parent"] = None
    node["action"] = None
    node["state"] = problem.getStartState()
    node["cost"] = 0

    frontier = util.PriorityQueue()  #for astar frontier is priority queue
    heuristicN = node["cost"] + searchAgents.manhattanHeuristic(
        node["state"],
        problem)  #manattan heuristic  *********************************
    #heuristicN=1    # hn=1 heuristic             ***************   to change through heurictic functions plese toggle the comment symbol
    frontier.push(node, heuristicN)  # init frontier
    while frontier:
        node = frontier.pop()  #returns node with least cost

        if visited.has_key(node["state"]):  #if exist in visited go to loop
            continue

        visited[node["state"]] = True  #set visited true
        if problem.isGoalState(node["state"]):  #if goal break
            break
        for child in problem.getSuccessors(
                node["state"]):  #successor odes of currentnode
            if not visited.has_key(
                    child[0]
            ):  #if child not in visited add to visited as well as frotier
                NodeChild = {}
                NodeChild["parent"] = node
                NodeChild["action"] = child[1]
                NodeChild["state"] = child[0]
                NodeChild["cost"] = node["cost"] + 1
                heuristicN = node["cost"] + searchAgents.manhattanHeuristic(
                    node["state"], problem
                )  #manattan heuristic  *********************************
                #heuristicN=1                  # hn=1 heuristic            ********    to change through heurictic functions plese toggle the comment symbol
                frontier.push(NodeChild, heuristicN)

    actions = []
    while node[
            "action"] != None:  #construct path by iterating through parents of goal state
        actions.insert(0, node["action"])
        node = node["parent"]

    return actions
    util.raiseNotDefined()
Example #3
0
    def getAction(self, state):
        problem = PositionSearchProblem(
            state)  #Mapeia todos os estados do jogo
        problem.goal = state.getPacmanPosition(
        )  #Mapeia o estado atual do pacman
        problem.startState = state.getGhostPosition(
            self.index)  #Mapeia o estado atual do objeto do fantasma

        frontier = util.PriorityQueue()  #Cria uma fila de prioridade
        frontier.push(
            problem.getStartState(),
            manhattanHeuristic(problem.getStartState(),
                               problem))  #coloca na heap o primeiro estado
        explored = []  #Nos expandidos
        paths = {}  #Todos os estados que foram percorridos
        totalCost = {}  #Custo total
        paths[problem.getStartState()] = list()
        totalCost[problem.getStartState()] = 0

        def isBestCostforState(cost, state):
            for n in frontier.heap:
                if n[1] == state:
                    if (n[1] in totalCost.keys()) and (totalCost[n[1]] > cost):
                        frontier.heap.remove(n)
                        return True
                    else:
                        return False
            return True

        while not frontier.isEmpty():
            s = frontier.pop()
            if problem.isGoalState(s):
                return paths.popitem()[1][0]
            explored.append(s)
            successors = problem.getSuccessors(s)
            for successor in successors:
                successorState = successor[0]
                move = successor[1]
                cost = successor[2]
                if (successorState not in explored and isBestCostforState(
                        totalCost[s] + cost, successorState)):
                    paths[successorState] = list(paths[s]) + [move]
                    totalCost[successorState] = totalCost[s] + cost
                    frontier.push(
                        successorState,
                        manhattanHeuristic(successorState, problem) +
                        totalCost[successorState])
        return []
def searchF(route, g, threshold, problem):
    currState = route.pop()
    route.push(currState) #only make sure there is at least node in the stack
    node, action, cost, path = currState
    f = g + searchAgents.manhattanHeuristic(node,problem)
    if f > threshold:
        # in idaStarSearch, this larger f would become the new threshold
        return f
    if problem.isGoalState(node):
        return FOUND
    succStates = problem.getSuccessors(node)
    min = float("inf")
    for succState in succStates: #find the smallerst f cost of children
        #recursive call with next node as current node for depth search
        if True: #no cycle check here
            succNode, succAction, succCost = succState
            newstate = (succNode, succAction, cost + succCost, path + [(node, action)])
            route.push(newstate)
            temp = searchF(route, g+1, threshold, problem) #cost between node is 1
            # searchF will continu to explore to the deeper of this branch.
            # searchF will stop goind deeper when f>threshold is found
            if (temp == FOUND):
                return FOUND
            if (temp < min):
                min = temp
            route.pop() #Due to FIFO, there will be only on node left eventually
    return min
Example #5
0
def nullHeuristic(state, problem=None):
    """
  A heuristic function estimates the cost from the current state to the nearest
  goal in the provided SearchProblem.  This heuristic is trivial.
  """
    from searchAgents import manhattanHeuristic
    return manhattanHeuristic(state, problem)
Example #6
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  #util.raiseNotDefined()
#util.raiseNotDefined()
  node = ((problem.getStartState(),'',0),[],0)
  explored = []
  path = []
  fringe = []
  fringe.append(node)
  
  while (not problem.isGoalState(node[0][0])):
      
      for i in problem.getSuccessors(node[0][0]):
          if i[0] not in explored:
              tmpPath = node[1][:]
              tmpPath.append(i[1])
              fringe.append(((i), tmpPath,node[2]+i[2]))
              fringe = sorted(fringe, key=lambda fringe:( fringe[0][2] + searchAgents.manhattanHeuristic(fringe[0][0],problem)))
              
      explored.append(node[0][0])
      fringe.remove(node)
      if len(fringe) == 0:
        break
      node = fringe[0]
      
  return node[1]
def nullHeuristic(state, problem=None):
  """
  A heuristic function estimates the cost from the current state to the nearest
  goal in the provided SearchProblem.  This heuristic is trivial.
  """
  from searchAgents import manhattanHeuristic
  return manhattanHeuristic(state,problem)
def improve(state0,problem):
    node0, action0, cost0, path0 = state0
    myQueue = util.Queue()
    myQueue.push(state0)
    visited = set()
    while not myQueue.isEmpty():
        popState = myQueue.pop()
        node, action, cost, path = popState
        if node not in visited:
            visited.add(node)
            if searchAgents.manhattanHeuristic(node,problem) < searchAgents.manhattanHeuristic(node0,problem):
                return popState #return the current state to be the new startState for ehc
            succStates = problem.getSuccessors(node)
            for succState in succStates:
                succNode, succAction, succCost = succState
                newstate = (succNode, succAction, cost + succCost, path + [(node, action)])
                myQueue.push(newstate)
    return popState
Example #9
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()
def idaStarSearch(problem, heuristic=nullHeuristic):
    """COMP90054 your solution to part 2 here """
    startState = (problem.getStartState(), '', 0, [])
    threshold = searchAgents.manhattanHeuristic(startState[0],problem)
    route = util.Stack()
    route.push(startState)

    while True:
        temp = searchF(route,0,threshold,problem) #at first state, the g is 0
        if temp == FOUND:
            finalState = route.pop()
            fnode, faction, fcost, fpath = finalState
            fpath = fpath + [(fnode, faction)]
            actions = [faction[1] for faction in fpath]
            del actions[0]
            return actions
        if temp == float("inf"):
            return Fail
        threshold = temp
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    visited = dict()
    node = {}
    node["parent"] = None
    node["action"] = None
    node["state"] = problem.getStartState()
    node["cost"] = 0

    frontier = util.PriorityQueue()
    heuristicN = node["cost"] + searchAgents.manhattanHeuristic(
        node["state"], problem)
    heuristicN = 1
    frontier.push(node, heuristicN)
    while frontier:
        node = frontier.pop()

        if visited.has_key(node["state"]):
            continue

        visited[node["state"]] = True
        if problem.isGoalState(node["state"]):
            break
        for child in problem.getSuccessors(node["state"]):
            if not visited.has_key(child[0]):
                NodeChild = {}
                NodeChild["parent"] = node
                NodeChild["action"] = child[1]
                NodeChild["state"] = child[0]
                NodeChild["cost"] = node["cost"] + 1
                #heuristicN = node["cost"] + searchAgents.manhattanHeuristic(node["state"], problem)
                heuristicN = 1
                frontier.push(NodeChild, heuristicN)

    actions = []
    while node["action"] != None:
        actions.insert(0, node["action"])
        node = node["parent"]

    return actions
    util.raiseNotDefined()
Example #12
0
def manhattanHeuristic(state, problem):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem. Using the manhattan distance betwen this 2 points
    """
    return searchAgents.manhattanHeuristic(state, problem)
Example #13
0
 def __init__(self, path, dad, action):
     self.path = path
     self.dad = dad
     self.action = action
     self.cost = manhattanHeuristic(path, problem.goal)
Example #14
0
def manhattanHeuristic(state, problem):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem. Using the manhattan distance betwen this 2 points
    """
    return searchAgents.manhattanHeuristic(state, problem)