Exemplo n.º 1
0
def aStar(rootNode, heur, timeout):
    open_list = PQ()
    closed_list = []
    search_path = []
    rootNode.fn = rootNode.hn = rootNode.h(
        heur)  # g(n) is 0 by default, so we only set f(n) & h(n)
    open_list.insert(rootNode.fn, rootNode)  # Add initial node
    start_time = perf_counter()  # Start the timer
    timedOut = False

    while (open_list.notEmpty()):
        elapsed_time = perf_counter()

        # if algorithm's runtime has exceeded the specified amount, stop execution
        if ((elapsed_time - start_time) >= timeout):
            timedOut = True
            return (None, None, None, None, None, None, timedOut)

        else:
            currCost, node = open_list.pop()  # get node and its g(n)
            clist_node_index = index(
                node.state, closed_list
            )  # get index of node in closed list or -1 if absent

            # node has been visited, but we must check if it now has a lower f(n) value
            if clist_node_index >= 0:
                if (node.fn < closed_list[clist_node_index].fn):
                    del closed_list[
                        clist_node_index]  # new f(n) < old f(n), so delete old node from cl
                    open_list.insert(node.fn, node)

            else:
                closed_list.append(
                    node
                )  # node is visited for the first time, add to closed list
                search_path.append(node)  # update search path

                # goal achieved, stop algorithm and return results
                if (node.isGoal(node.state)):
                    moves, costs, sol_path = node.traceSolution([], [], [])
                    totalCost = sum(costs)
                    end_time = (elapsed_time - start_time)
                    return (moves, costs, sol_path, search_path, totalCost,
                            end_time, timedOut)  # Return final values

                # goal not achieved yet, generate next nodes and keep evaluating
                else:
                    node.generateSuccessors()
                    successors = node.successors

                    for successor in successors:
                        if successor not in closed_list:
                            successor.hn = successor.h(heur)
                            successor.gn = currCost + successor.cost
                            successor.fn = successor.gn + successor.hn
                            open_list.insert(successor.fn, successor)
Exemplo n.º 2
0
    def __init__(self):
        #This allows access to specific entities
        #sEntityType:(sEntityName:entity)
        self._dEntities = {}

        #This orders the entities so that the ones with the highest draw
        #   priority will be first in the list (highest priority is 0.)
        self._pqDrawableEntities = PQ()
Exemplo n.º 3
0
def gbfs(rootNode, heur, timeout):
    open_list = PQ()
    closed_list = []
    search_path = []
    rootNode.hn = rootNode.h(heur)
    open_list.insert(rootNode.hn, rootNode)  # Add initial node
    start_time = perf_counter()  # Start the timer
    timedOut = False

    while (open_list.notEmpty()):
        elapsed_time = perf_counter()

        # if algorithm's runtime has exceeded the specified amount, stop execution
        if ((elapsed_time - start_time) >= timeout):
            timedOut = True
            return (None, None, None, None, None, None, timedOut)

        else:
            node = open_list.pop()[
                1]  # We don't care about the heuristic value returned

            # if node has not been visited yet, process it
            if node.state not in closed_list:
                closed_list.append(
                    node.state
                )  # node is visited for the first time, add to closed list
                search_path.append(node)  # update search path

                # goal achieved, stop algorithm and return results
                if (node.isGoal(node.state)):
                    moves, costs, sol_path = node.traceSolution([], [], [])
                    totalCost = sum(costs)
                    end_time = (elapsed_time - start_time)
                    return (moves, costs, sol_path, search_path, totalCost,
                            end_time, timedOut)  # Return final values

                # goal not achieved yet, generate next nodes and keep evaluating
                else:
                    node.generateSuccessors()
                    successors = node.successors

                    for successor in successors:
                        if successor not in closed_list:
                            successor.hn = successor.h(heur)
                            open_list.insert(successor.hn, successor)
Exemplo n.º 4
0
def ucs(rootNode, timeout):
    open_list = PQ()
    closed_list = set()
    search_path = []
    open_list.insert(0, rootNode)  # Add initial node with g(n) of 0
    start_time = perf_counter()  # Start the timer
    timedOut = False

    while (open_list.notEmpty()):
        elapsed_time = perf_counter()

        # if algorithm's runtime has exceeded the specified amount, stop execution
        if ((elapsed_time - start_time) >= timeout):
            timedOut = True
            return (None, None, None, None, None, None, timedOut)

        else:
            currCost, node = open_list.pop()  # get node and its g(n)

            # if node has not been visited yet, process it
            if (str(node.state) not in closed_list):
                closed_list.add(
                    str(node.state)
                )  # node is visited for the first time, add to closed list
                search_path.append(node)

                # goal achieved, stop algorithm and return results
                if (node.isGoal(node.state)):
                    moves, costs, sol_path = node.traceSolution([], [], [])
                    totalCost = sum(costs)
                    end_time = (elapsed_time - start_time)
                    return (moves, costs, sol_path, search_path, totalCost,
                            end_time, timedOut)  # Return final values

                # goal not achieved yet, generate next nodes and keep evaluating
                else:
                    node.generateSuccessors()
                    successors = node.successors

                    for successor in successors:
                        if successor not in closed_list:
                            successor.gn = currCost + successor.cost
                            open_list.insert(successor.gn, successor)
Exemplo n.º 5
0
    def __init__(self, sName, sType, iDrawPriority, dAttribs):

        Entity.__init__(self, sName, sType, iDrawPriority, {})

        #This takes all of the entities out of the dComponents
        dEntities = dAttribs.pop("entity", {})

        #"These are the entities that are being loaded into the Entity_PQueue"
        #print dEntities

        #This orders the entities so that the ones with the highes t draw
        #   priority will be first in the list (highest priority is 0.)
        self._pqEntities = PQ()

        #This is Pymunk's Space() class basically. But it's in a component.
        #   It will contain the collidable object for Entities.
        Entity._Add_Component( self, getClass("Collision_Space")( {"componentID":"EntityPool",     \
                                                                 "gravity":dAttribs["gravity"].split(",")} ) )

        #This will insert the entities into the PriorityQueue through the proper method.
        for entity in dEntities.values():

            self._Add_Entity(entity)
Exemplo n.º 6
0
    def search_for_path_winter(self, object_orien, start, final):
        """
        Search for path during the winter season
        :param start:Start point
        :param final:Point to be reached
        :return:Final list containing the final path
        """
        object_orien.speed_through_different_paths[(178, 255, 255)] = 5
        object_orien.speed_through_different_paths[(0, 0, 255)] = 0.1

        # To keep track of g values
        cost_so_far = {}

        # Priority queue initialization
        s = PQ()

        # To keep track of predecessors to help in backtracking
        predecessor = {}

        # Insert start point into the priority queue
        s.put(start, 0)

        # g value of start is 0
        cost_so_far[start] = 0

        # f value of start is 0 + h(start)
        f_value = {}
        f_value[start] = object_orien.calculateh(start[0], start[1], final[0],
                                                 final[1])

        final_path_list = []

        # Exiting condition when no path is found
        while not s.empty():
            # Fetch the element in the priority queue with the lowest g(n) + h(n) value
            point_explored = s.get()

            # To keep the final path
            final_path_list = []

            # Exiting condition for when there exists a path between the start point and end point supplied to this function
            if point_explored == final:

                #Backtracking to find the actual path from the start point to the final point
                curr = final
                while curr != start:
                    final_path_list.insert(0, curr)
                    curr = predecessor[curr]
                final_path_list.insert(0, start)
                break

            # Get the neighbours of the element fetched from the priority queue
            neighbour_list = self.getNeighbour_winter(object_orien,
                                                      int(point_explored[0]),
                                                      int(point_explored[1]))

            # Loop through all the neighbours of fetched element
            for neighbour in neighbour_list:
                # Calculate g value for the neighbour
                calculated_g_value = cost_so_far[
                    point_explored] + object_orien.calculateg(
                        neighbour[0], neighbour[1], point_explored[0],
                        point_explored[1])

                # Calculate h value for the neighbour
                calculated_h_value = object_orien.calculateh(
                    neighbour[0], neighbour[1], final[0], final[1])

                # If neighbour not already in queue or neighbour calculated f value less than than its tracked f value till now
                if neighbour not in cost_so_far or \
                                calculated_g_value + calculated_h_value < f_value[neighbour]:

                    cost_so_far[neighbour] = calculated_g_value
                    f_value[
                        neighbour] = calculated_g_value + calculated_h_value
                    s.put(neighbour, calculated_g_value + calculated_h_value)
                    predecessor[neighbour] = point_explored

        return final_path_list