def load_remaining_packages(self):
        package_queue = PriorityQueue()

        for k, p in self.packages:
            if p.truck_id is None:
                package_queue.enqueue(p, p.distance_from_hub)

        while (not package_queue.is_empty()):
            if not self.t1.is_truck_full():
                self.t1.load_truck(package_queue.dequeue())
            elif not self.t2.is_truck_full():
                self.t2.load_truck(package_queue.dequeue())
            else:
                self.t3.load_truck(package_queue.dequeue())
예제 #2
0
    def test_dequeue(self):
        pq = PriorityQueue(min)
        pq.enqueue(1)
        pq.enqueue(2)
        pq.enqueue(3)
        assert pq.dequeue() == 1
        assert pq.dequeue() == 2
        assert pq.dequeue() == 3

        mpq = PriorityQueue(max)
        mpq.enqueue(1)
        mpq.enqueue(2)
        mpq.enqueue(3)
        assert mpq.dequeue() == 3
        assert mpq.dequeue() == 2
        assert mpq.dequeue() == 1
 def shortest_path(self, target):
     """
     Uses Dijkstra's algorithm to return the shortest paths between the 
     target and all other nodes in the graph.
     """
     if not self.weighted:
         print "Graph is not weighted; redirecting to BFS"
         return self.bfs(target, min_distance=True)
     distances_pq = PriorityQueue("min")
     distances_dict = {} 
     unvisited = []
     for node in self.adj_matrix[0]:
         if node == target:
             distances_pq.enqueue(0, node)
             distances_dict[node] = 0
         elif node != False:
             distances_pq.enqueue(float('inf'), node)
             distances_dict[node] = float('inf')
         else:
             continue
         unvisited.append(node)
     while unvisited:
         min_distance, min_node = distances_pq.dequeue()
         if min_node not in unvisited:
             continue
         neighbors = self.linked(min_node)
         for neighbor in neighbors:
             neighbor_distance = min(distances_dict[neighbor], 
                                     min_distance + self.link_weight(min_node, neighbor))
             if neighbor_distance != distances_dict[neighbor]:
                distances_dict[neighbor] = neighbor_distance
                distances_pq.enqueue(neighbor_distance, neighbor)
         unvisited.remove(min_node)
     return distances_dict
예제 #4
0
    def dijkstraSearch(network: Network, startNodeId: int, endNodeId: int):
        if (not network.nodesExist([startNodeId, endNodeId])):
            return -1

        costs = {}
        pq = PriorityQueue()

        # Set the costs of all nodes to infinity except the start node which we give zero cost.
        costs[startNodeId] = 0
        for nodeId in network.nodeIds:
            if (nodeId != startNodeId):
                costs[nodeId] = math.inf

        # Begin by adding start node to the queue.
        pq.enqueue(startNodeId, 0)

        # Use priority queue to traverse the nodes having least cost.
        while (not pq.isEmpty()):
            shortestStep = pq.dequeue()
            currentNodeId = shortestStep.nodeId

            # Calculate the cost of travelling to each neighbor.
            for neighbor in network.adjacencies[currentNodeId]:
                cost = costs[currentNodeId] + neighbor.cost

                # If the cost of this path to the neighbor is less than another path
                # we add the neighbor node ID to the queue as a candidate to be traversed.
                if (cost < costs[neighbor.nodeId]):
                    costs[neighbor.nodeId] = cost
                    pq.enqueue(neighbor.nodeId, cost)

        return costs[endNodeId]
예제 #5
0
    def uniform_cost_search(self, problem):
        #lambda function to compare in the priority queue
        f = lambda node: node.path_cost

        #make node from initial node
        node = Node(problem.initial, None, None, 0, 0)

        #create pq for frontier
        pq = PriorityQueue(min, f)

        #push to pq
        pq.enqueue(node)

        #set of explored states
        #use set because contains is quicker in sets than lists
        #set of states, not nodes because we dont want duplicate states, nodes dont matter
        explored = []

        #loop until pq is empty ---- or goal state is reached?
        while pq.size() > 0:
            node = pq.dequeue()

            #print("woot", node.state, " costs ", node.path_cost)
            #check if it is goal state
            if problem.goal_test(node.state):
                #if goal state return node
                return node
            #otherwise, build out new nodes and push to pq
            else:
                explored.append(node.state)
                problem.visited += 1
                #array of child nodes
                frontier_nodes = node.expand_frontier(problem)
                #problem.time += len(frontier_nodes)
                # if(len(frontier_nodes) > problem.frontier):
                #     problem.frontier = len(frontier_nodes)
                #frontier_states = [(x.state, x.path_cost) for x in frontier_nodes]
                #print("frontier: ", frontier_states)
                #push them onto pq
                for fnode in frontier_nodes:
                    #dont want duplicates, so can't exist in explored or pq
                    if fnode.state not in explored and fnode not in pq:
                        pq.enqueue(fnode)
                        problem.time += 1
                        if (pq.size() > problem.frontier):
                            problem.frontier = pq.size()
                    #if by chance there is a duplicate node in frontier,
                    #delete the "larger"/worst node
                    elif fnode in pq:
                        #print(fnode.node_path())
                        #print(pq.size())
                        current_node = pq[fnode]
                        #print(current_node)
                        if fnode.path_cost < current_node.path_cost:
                            del pq[current_node]
                            pq.enqueue(fnode)
        #if a node was not returned at this point, nothing matches the goal state
        return None
예제 #6
0
def PriorityQueueUnitTest():
    #test enqueue and dequeue
    UnitTest.resetErrorCount()
    q = PriorityQueue()
    UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())
    q.enqueue(1, 2)
    q.enqueue(2, 3)
    UnitTest.assertFalse("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())
    v = q.dequeue()
    UnitTest.assertEquals("q.dequeue() -> " + str(v), v, 1)
    q.enqueue(3, 4)
    v = q.dequeue()
    UnitTest.assertEquals("q.dequeue() -> " + str(v), v, 2)
    v = q.dequeue()
    UnitTest.assertEquals("q.dequeue() -> " + str(v), v, 3)
    UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())

    j = 0
    for ch in "ABCDEFGHIJKLMNOPQRSTUVXYZ":
        q.enqueue(ch, j)
        j += 1
    line = ""
    while not q.isEmpty():
        line += q.dequeue()
    UnitTest.assertEquals("line -> \"" + line + "\"", line,
                          "ABCDEFGHIJKLMNOPQRSTUVXYZ")

    #test clear
    q.clear()
    UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())

    #test len
    j = 0
    for ch in "ABCDEFGHIJKLMNOPQRSTUVXYZ":
        q.enqueue(ch, j)
        j += 1
    length = q.len()
    UnitTest.assertEquals("length -> " + str(length), length, 26)
    q.clear()

    if (UnitTest.getErrorCount() == 0):
        print("QueueUnitTest succeeded")
    else:
        print("QueueUnitTest failed")
예제 #7
0
def dijstra(aGraph, start):
    pq = PriorityQueue(1000)  # 优先级队列实例,小数优先
    start.setDistance(0)  # 设置起始结点到起始结点的权重为0
    # 元组作为优先队列的元素
    pq.buildHeap([(v.getDistance(), v)
                  for v in aGraph])  # 到起始顶点的距离作为优先级队列中的键,图中顶点的键作为优先级队列中的值
    while not pq.isEmpty():
        # 每次从队列中挑选权重最小的边
        currentVert = pq.dequeue()  # 队首元素
        for nextVert in currentVert.getConnections():
            # 新的距离 = 当前结点的距离 + 当前结点到下一个结点之间的权重
            newDist = currentVert.getDistance() + currentVert.getWeight(
                nextVert)
            if newDist < nextVert.getDistance():  # 如果新距离小于当前距离
                nextVert.setDistance(newDist)  # 下一个结点设置新的距离
                nextVert.setPredecessor(currentVert)  # 下一个结点的前一个结点设置为当前结点
                pq.decreaseKey(nextVert, newDist)  # 当队列中的元素的距离改变时,调整优先级队列
예제 #8
0
def prim(G, start):
    pq = PriorityQueue(1000)  # 优先级队列实例,小数优先
    # 所有顶点初始化
    for v in G:
        v.setDistance(sys.maxsize)
        v.setPredecessor(None)

    start.setDistance(0)  # 起始结点权重设置为0
    pq.buildHeap([(v.getDistance(), v) for v in G])  # 构建最小堆
    while not pq.isEmpty():
        currentVert = pq.dequeue()
        for nextVert in currentVert.getConnections():
            newCost = currentVert.getWeight(nextVert)
            if nextVert in pq and newCost < nextVert.getDistance():
                nextVert.setPredecessor(currentVert)  # 下一个结点的前导结点为当前结点
                nextVert.setDistance(newCost)  # 下一个结点的距离设置为newCost
                pq.decreaseKey(nextVert, newCost)  # 重新调整为最小堆
예제 #9
0
    def solvable(self):

        agent = (self.agent['x'], self.agent['y'])
        gold = (self.gold['x'], self.gold['y'])

        pq_open = PriorityQueue((lambda x, y: y[0] - x[0]))
        pq_open.enqueue((self.__heuristic(agent, gold), agent, None))
        closed = set()

        while not pq_open.isEmpty():
            current_node = pq_open.dequeue()
            if current_node[1] == gold:
                return True

            closed.add(current_node[1])
            for child in self.__expand(current_node[1]):
                if child not in closed:
                    pq_open.enqueue((self.__heuristic(child, gold), child, current_node))

        return False
예제 #10
0
    def test_size(self):
        #create lambda function which just calls func defined below
        #this allows the mocks to be compared in the PriorityQueue
        f = lambda x: x()

        #Stubbed function that can be assigned to a mock
        def func(m):
            return m.return_value

        #create mock items and stubbed functions for the mocks
        mock_item1 = MagicMock()
        mock_item1.func = func
        mock_item1.return_value = 1
        #print(f(mock_item1)) #uncomment for debug
        mock_item2 = MagicMock()
        mock_item2.func = func
        mock_item2.return_value = 2
        #print(f(mock_item2)) #uncomment for debug
        mock_item3 = MagicMock()
        mock_item3.func = func
        mock_item3.return_value = 3
        #print(f(mock_item3)) #uncomment for debug

        #initialize PriorityQueue as a min queue with lambda f
        pq = PriorityQueue(min, f)
        assert pq.size() == 0
        pq.enqueue(mock_item1)
        assert pq.size() == 1
        pq.enqueue(mock_item2)
        assert pq.size() == 2
        pq.enqueue(mock_item3)
        assert pq.size() == 3
        #quick check to make sure the stubbed function works
        assert pq.peek() == mock_item1

        pq.dequeue()
        assert pq.size() == 2
        pq.dequeue()
        assert pq.size() == 1
        pq.dequeue()
        assert pq.size() == 0
def PriorityQueueTest():
    errorcount = 0
    q = PriorityQueue()
    #UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())
    if q.isEmpty() != True:
        errorcount += 1
    if len(q) != 0:
        errorcount += 1

    q.enqueue("Kokichi", 10)
    q.enqueue("Gonta", 9)
    q.enqueue("Kirumi", 4)
    q.enqueue("Kaede", 2)
    q.enqueue("Miu", 8)
    q.enqueue("Kaito", 11)
    q.enqueue("Ryoma", 3)
    q.enqueue("Korekiyo", 7)
    q.enqueue("Rantaro", 1)
    q.enqueue("Angie", 5)
    q.enqueue("Tenko", 6)

    ###TEST STUFF HERE###

    if q.isEmpty():
        errorcount += 1
    if len(q) != 11:
        errorcount += 1

    line = []
    while not q.isEmpty():
        #print(q.printout())
        #print(q.dequeue())
        line.append(q.dequeue())
        #print(q.printout())
        #print(len(q))
        #print(" ")
    for i in range(len(line)):
        if i + 1 != line[i][
                1]:  #checks to see if the priority does indeed go from min(1) to max(11) values
            errorcount += 1

    if q.isEmpty(
    ) != True:  #makes sure that after dequeueing all of that, q is empty
        errorcount += 1
    if len(q) != 0:
        errorcount += 1

    #Testing out cases where the priorities are not numerically right after the other
    q.enqueue("Keebo", 11)
    q.enqueue("Tsumugi", 3)
    q.enqueue("Shuichi", 7)
    q.enqueue("Himiko", 1)
    q.enqueue("Maki", 5)

    line = []
    while not q.isEmpty():
        #print(q.printout())
        #print(q.dequeue())
        line.append(q.dequeue())
        #print(q.printout())
        #print(len(q))
        #print(" ")

    #print(line)
    lastpriority = line[0][1]
    for i in range(1, len(line)):
        if lastpriority > line[i][
                1]:  #checks to see if the priority of outputs still is from min to max
            errorcount += 1
        lastpriority = line[i][1]

    q.enqueue("Monokid", 11)
    #Just adding values to make sure the .clear() function works...
    q.enqueue("Monodam", 3)
    q.enqueue("Monophanie", 7)
    q.enqueue("Monokuma", 1)
    q.enqueue("Monosuke", 6)
    q.enqueue("Monotaro", 5)
    q.enqueue("Nanokumas", 10)

    q.clear()  #Test to see if .clear() works
    if len(q) != 0:
        errorcount += 1
    if q.isEmpty() != True:
        errorcount += 1

    if (errorcount == 0):
        print("PriorityQueueTest succeeded")
    else:
        print("PriorityQueueTest failed")
예제 #12
0
class Search:
    def __init__(self, start=None, goal=None):
        self.search_start = start  # This list the starting state of the puzzle
        self.search_goal = goal  # This list the solution to the puzzle
        self.closed_list = []  # This is a list that holds the nodes that have been expanded
        self.open_list = PriorityQueue()  # This is a list that holds the nodes that need to be expanded

    """""""""""""""""""""""""""""""""""""""    CHECK PARITY    """""""""""""""""""""""""""""""""""""""

    """ This method will determine the parity of the puzzle to determine if it is solvable. """
    def equal_parity(self, s, g):

        # Make copies of s and g so that the lists can be manipulated without impacting
        # the rest of the code.
        s_test = copy.deepcopy(s)
        g_test = copy.deepcopy(g)

        # Remove blank space marker.
        s_test.remove('X')
        g_test.remove('X')

        # Start parity counts at zero.
        s_parity = 0
        g_parity = 0

        # Compare each element of the list against all the elements indexed after it, incrementing
        # parity count each time the element is greater than any of the elements indexed after it.
        for i in range(len(s_test)):
            for j in range(i, len(s_test)):
                if s_test[i] > s_test[j]:
                    s_parity += 1
                if g_test[i] > g_test[j]:
                    g_parity += 1

        # Determine whether parities or both equal or both odd; if they are the same return true.
        if (s_parity % 2) == (g_parity % 2):
            return True  # The parities ARE the same
        else:
            return False  # The parities are NOT the same

    """""""""""""""""""""""""""""""""""""""     PRINTING METHODS     """""""""""""""""""""""""""""""""""""""

    """This prints the current puzzle state."""
    def print_state(self, n):
        for x in range(3):
            print(n.val[x][0], n.val[x][1], n.val[x][2])

    """ This method prints the path of the solution. """
    def print_path(self, n):

        path = []

        # Add all predecessors of goal state to path list
        while n.pred is not None:
            path.insert(0, n)
            n = n.pred

        path.insert(0, n)

        # Print each state in path list
        print()
        print("Solution Path:")

        for i in range(len(path)):
            self.print_state(path[i])
            print()

    """""""""""""""""""""""""""""""""""""""     'CHECK' METHODS     """""""""""""""""""""""""""""""""""""""

    """ This method checks to see if the current node is located in the closed list. If it is, it is removed from the
    open_list. """

    def duplicate(self, n):

        duplicate = True

        for i in range(len(self.closed_list)):
            duplicate = True
            for x in range(len(n.val)):
                for y in range(len(n.val)):
                    if n.val[x][y] != self.search_goal.val[x][y]:
                        duplicate = False

        return duplicate

    def check_duplicate(self, n):

        if len(self.closed_list) == 0:
            return False

        duplicate = True

        for x in range(len(self.closed_list)):
            temp = self.closed_list[x]
            duplicate = True

            for i in range(3):
                for j in range(3):
                    if n.val[i][j] is not temp.val[i][j]:
                        duplicate = False

            if duplicate is True:
                return duplicate

        return duplicate

    """ This method compares the current node to search_goal. """

    def check_solution(self, current):
        for x in range(len(self.search_goal.val)):
            for y in range(len(self.search_goal.val)):
                if current.val[x][y] != self.search_goal.val[x][y]:
                    return False

        return True

    """"""""""""""""""""""""""""""""""""""" EXPAND NODE METHODS """""""""""""""""""""""""""""""""""""""

    """ This method finds the blank ('X') in the puzzle. """
    def find_blank(self, n):

        index = [0, 0]
        arr = n.val
        for i in range(3):
            for j in range(3):
                if arr[i][j] is 'X':
                    index = [i, j]

        return index

    """ This method expands the current puzzle node. """
    def expand(self, curr_node):

        # Get and store the index of the "blank" tile in curr_node
        index = self.find_blank(curr_node)
        x = index[0]
        y = index[1]

        # Create list to store the nodes expanded from curr_node
        options = []

        # UP
        if x > 0:
            # Create deep copy of curr_node's state so that original won't be altered
            new_list = copy.deepcopy(curr_node.val)
            # Swap "blank" with whatever "tile" is stored in the row above it on the puzzle
            new_list[x - 1][y], new_list[x][y] = new_list[x][y], new_list[x - 1][y]
            # Create new node, using the new_list puzzle state as its value
            n = Node(new_list, curr_node, curr_node.g + 1)
            # If new node is not a duplicate, add to options list
            if not self.check_duplicate(n):
                options.append(n)
        # DOWN
        if x < 2:
            new_list = copy.deepcopy(curr_node.val)
            new_list[x + 1][y], new_list[x][y] = new_list[x][y], new_list[x + 1][y]
            n = Node(new_list, curr_node, curr_node.g + 1)
            if not self.check_duplicate(n):
                options.append(n)
        # LEFT
        if y > 0:
            new_list = copy.deepcopy(curr_node.val)
            new_list[x][y - 1], new_list[x][y] = new_list[x][y], new_list[x][y - 1]
            n = Node(new_list, curr_node, curr_node.g + 1)
            if not self.check_duplicate(n):
                options.append(n)
        # RIGHT
        if y < 2:
            new_list = copy.deepcopy(curr_node.val)
            new_list[x][y + 1], new_list[x][y] = new_list[x][y], new_list[x][y + 1]
            n = Node(new_list, curr_node, curr_node.g + 1)
            if not self.check_duplicate(n):
                options.append(n)

        return options

    """"""""""""""""""""""""""""""""""""""" BREADTH FIRST SEARCH """""""""""""""""""""""""""""""""""""""

    def breadth_first_search(self):

        curr_node = self.search_start  # Create our 'current' node and set it equal to the puzzle start
        self.open_list.enqueue_bfs(curr_node)  # Enqueue the current node

        # While loop to continue expanding nodes until solution is reached
        while self.check_solution(curr_node) is False:

            curr_node = self.open_list.dequeue()  # dequeue front of PQ

            options = self.expand(curr_node)  # temp list to hold our expanded options

            for x in range(len(options)):  # for loop to enqueue all expanded options
                self.open_list.enqueue_bfs(options[x])

            self.closed_list.append(curr_node)  # Add the current node to the end of the closed_list

        self.print_path(curr_node)
        print("Open List Size: ", len(self.open_list.queue))
        print("Closed List Size: ", len(self.closed_list))

    """"""""""""""""""""""""""""""""""""""" MISPLACED TILES """""""""""""""""""""""""""""""""""""""

    """ Compare node n to goal state and return number of tiles "misplaced" """
    def num_misplaced(self, n):

        num_misplaced = 0

        for i in range(3):
            for j in range(3):
                if n.val[i][j] is not self.search_goal.val[i][j]:
                    if n.val[i][j] is not 'X':
                        num_misplaced += 1

        return num_misplaced

    """ This method runs the misplaced tiles puzzle solver. """
    def misplaced_tiles(self):

        # Begin with a node holding the user-input start state
        curr_node = self.search_start
        self.open_list.enqueue(curr_node)

        while not self.check_solution(curr_node):

            # Store the cheapest unexpanded node in curr_node
            curr_node = self.open_list.dequeue()

            # Expand curr_node and store new nodes inside temp
            options = self.expand(curr_node)

            # Update f value (g + number of misplaced tiles) in all options
            # Enqueue updated node into open list
            for i in range(len(options)):
                options[i].f = options[i].g + self.num_misplaced(options[i])
                self.open_list.enqueue(options[i])

            # Add current node to closed list
            self.closed_list.append(curr_node)

        self.print_path(curr_node)
        print("Open List Size: ", len(self.open_list.queue))
        print("Closed List Size: ", len(self.closed_list))

    """"""""""""""""""""""""""""""""""""""" MANHATTAN DISTANCE """""""""""""""""""""""""""""""""""""""

    """ This method returns the index of a given element in a 2D list """
    def get_index(self, n, a):

        index = [0, 0]

        for i in range(3):
            for j in range(3):
                if n.val[i][j] is a:
                    index = [i, j]

        return index

    """ This method returns the total 'manhattan distance' of a puzzle state """
    def distance(self, curr_node):

        # start with a total distance of zero
        dist = 0

        # find and sum distances of tiles 1 - 8 from their current to goal states
        for i in range(9):
            # get the index of the tile in both curr_node and the goal state
            tile_a = self.get_index(curr_node, i)
            tile_b = self.get_index(self.search_goal, i)
            # add the distance of individual tile to total distance
            dist += (abs(tile_a[0] - tile_b[0]) + abs(tile_a[1] - tile_b[1]))

        return dist

    """ This method runs the manhattan distance puzzle solver. """
    def manhattan_distance(self):

        # Begin with a node holding the user-input start state
        curr_node = self.search_start
        self.open_list.enqueue(curr_node)

        while not self.check_solution(curr_node):

            # Store the cheapest unexpanded node in curr_node
            curr_node = self.open_list.dequeue()

            # Expand curr_node and store new nodes inside temp
            options = self.expand(curr_node)

            # Update f value (g + number of misplaced tiles) in all options
            # Enqueue updated node into open list
            for i in range(len(options)):
                options[i].f = options[i].g + self.distance(options[i])
                self.open_list.enqueue(options[i])

            # Add current node to closed list
            self.closed_list.append(curr_node)

        self.print_path(curr_node)
        print("Open List Size: ", len(self.open_list.queue))
        print("Closed List Size: ", len(self.closed_list))

    """""""""""""""""""""""""""""""""""""""      GASCHNIG      """""""""""""""""""""""""""""""""""""""

    """ This method runs the gaschnig puzzle solver. """
    def gaschnig(self):
        # Begin with a node holding the user-input start state
        curr_node = self.search_start
        self.open_list.enqueue(curr_node)
        while not self.check_solution(curr_node):
            # Store the cheapest unexpanded node in curr_node
            curr_node = self.open_list.dequeue()
            # Expand curr_node and store new nodes inside temp
            options = self.expand(curr_node)
            # Update f value (g + number of switches) in all options
            # Enqueue updated node into open list
            for i in range(len(options)):
                options[i].f = options[i].g + self.switch_check(options[i])
                self.open_list.enqueue(options[i])

            # Add current node to closed list
            self.closed_list.append(curr_node)

        self.print_path(curr_node)
        print("Open List Size: ", len(self.open_list.queue))
        print("Closed List Size: ", len(self.closed_list))

    """ The following method determines how many switches are necessary to complete the puzzle 
        if you can swap tiles. """
    def switch_check(self, curr_node):
        # Start by creating deep copies of our current puzzle & the goal puzzle as well as two empty lists
        c = copy.deepcopy(curr_node.val)
        g = copy.deepcopy(self.search_goal.val)
        current = []
        goal = []

        # The double for loop appends the c & g lists into a 1D array for easier sorting
        x = 0
        for y in range(len(c)):
            for z in range(len(c[y])):
                current.append(c[y][z])
                goal.append(g[y][z])

                x = x + 1

        # The for loop cycles through the current array to determine how many switches are needed to have current = goal
        switch = 0
        for x in range(len(current)):
            if current[x] != goal[x]:
                # If the current location in each array are not equal to each other, we search current for the value to
                # swap our current value with and increment switch by 1
                for y in range(x, len(current)):
                    if goal[x] == current[y]:
                        current[x], current[y] = current[y], current[x]
                        switch = switch + 1

        return switch  # Return how many switches are needed to store into h
예제 #13
0
def oneRun(eps, filename):
    class Astar:
        def isLocValid(self, y, x):
            """check if the input position is valid. valid means 
            that the x,y is smaller or equal to max or bigger or equal to 1"""
            if y < height and y >= 0 and x < width and x >= 0:
                return True
            else:
                return False

        def getNextNeighbour(self, y, x):
            """at each location, check the four directions,
            the sequence is to check top, right, bot, left,
            Return a list of valid positions.
            """
            check_top = self.isLocValid(y - 1, x) and (m[y - 1, x]
                                                       in (' ', 'E'))
            check_right = self.isLocValid(y, x + 1) and (m[y, x + 1]
                                                         in (' ', 'E'))
            check_bot = self.isLocValid(y + 1, x) and (m[y + 1, x]
                                                       in (' ', 'E'))
            check_left = self.isLocValid(y, x - 1) and (m[y, x - 1]
                                                        in (' ', 'E'))

            check_sequence = [
                (check_top, (y - 1, x)), (check_right, (y, x + 1)),
                (check_bot, (y + 1, x)), (check_left, (y, x - 1))
            ]

            result = []
            if check_sequence[0][0]:
                result.append(check_sequence[0][1])
            if check_sequence[1][0]:
                result.append(check_sequence[1][1])
            if check_sequence[2][0]:
                result.append(check_sequence[2][1])
            if check_sequence[3][0]:
                result.append(check_sequence[3][1])
            return result

        def loadMaze(self, fName):
            #load the maze
            arr = np.genfromtxt(fName, dtype=str, delimiter=1, comments=None)
            return arr

        # just the straight line distance to the end.
        def heuristic(self, start, end):
            return ((float(start[0]) - float(end[0]))**2 +
                    (float(start[1]) - float(end[1]))**2)**(0.5)

        def calculatePriority(self, NumSteps, epsilon, start, end):
            """I implemented the static weighing, epsilon will be defaulted as 
               0. And we could pass a value to epsilon.
            """
            priority = NumSteps + self.heuristic(start, end) * (1 + epsilon)
            return priority

    ##program running#################################

    #initialize an object
    A = Astar()

    #load the maze
    m = A.loadMaze(filename)

    #height, width is the shape of the loaded maze
    height, width = m.shape

    #will turn off the App aplication if running for test, otherwise turn it on
    try:
        if sys.argv[3] == 'test':
            pass
        else:
            a = App(m)
    except IndexError:
        a = App(m)

    # Find the Start and End positions
    for y in range(len(m)):
        for x in range(len(m[y])):
            if m[y][x] == 'S':
                startPos = (y, x)
            if m[y][x] == 'E':
                endPos = (y, x)
    #print(startPos)
    #print(endPos)

    Q = PriorityQueue()
    totalSteps = 0
    stepsInPath = 0

    #generate the current position tuple and enqueue it to the priority queue
    curPos = (startPos, stepsInPath,
              A.calculatePriority(stepsInPath, eps, startPos, endPos))
    Q.enqueue(curPos[0], curPos[1], curPos[2])

    #first step action
    m[curPos[0]] = 'c'
    totalSteps += 1
    stepsInPath += 1

    #delay of time
    delay = float(sys.argv[2])

    # While queue is not empty, actual algorithm
    while (len(Q) > 0):
        # Algo goes here.
        #this session is for debugging. ignore it.
        #print (str(totalSteps))
        #print('current position: '+' y: ' + str(curPos[0][0]) + ' x: ' + str(curPos[0][1]))
        #print("No of items in Q: ", len(Q))
        #print(Q.pos_tuple)
        #print(m)
        #print()
        """1. mark the first step as x, then dequeue for the new curPos,
              new stepsInpath will also be the stepsInPath parameter 
           2. check if the current position is Exit,
              2.1 if yes, print the stepsInPath, change to 'f' and break the 
                  loop
              2.2 if no, change to 'c' and get all available neigbour positions,
                  add one more steps in path then enqueue all new neiPos to 
                  priority queue
                     2.2.1 if nPos is the Exit, then do nothing. next step ,
                     the current step will for sure be selected 
                     2.2.2 if nPos is not the Exit, we will mark it as 'p'
           3. then each time, we add totalSteps by 1
           4. if application is initialized, the we render it for each loop
        """
        m[curPos[0]] = 'x'
        curPos = Q.dequeue()
        stepsInPath = curPos[1]

        if m[curPos[0]] == 'E':
            stepsInPath += 1
            print("total number of steps to the end is: ", stepsInPath)
            m[curPos[0]] = 'f'
            break
        else:
            m[curPos[0]] = 'c'
            neiPos = A.getNextNeighbour(curPos[0][0], curPos[0][1])
            stepsInPath += 1

            for nPos in neiPos:
                Q.enqueue(nPos, stepsInPath,
                          A.calculatePriority(stepsInPath, eps, nPos, endPos))
                if m[nPos] == 'E':
                    pass
                else:
                    m[nPos] = 'p'
        totalSteps += 1

        try:
            if sys.argv[3] == 'test':
                pass
            else:
                a.on_init()
                a.on_render()
                time.sleep(delay)
        except IndexError:
            a.on_init()
            a.on_render()
            time.sleep(delay)

    try:
        if sys.argv[3] == 'test':
            pass
        else:
            a.on_render()
            time.sleep(delay)
    except IndexError:
        a.on_render()
        time.sleep(delay)

    #print out the final results
    print('epsilon is: ', eps)
    print('input file is: ', filename)
    print('Total Steps:' + str(totalSteps))
    curPos = (curPos, stepsInPath,
              A.calculatePriority(stepsInPath, eps, curPos[0], endPos))
    print('Steps In Path:' + str(curPos[1]))
    return totalSteps, curPos[1]
예제 #14
0
from PriorityQueue import PriorityQueue

pq = PriorityQueue()
pq.enqueue(4,"Maestre")
pq.enqueue(2,"Ninos")
pq.enqueue(4,"Mecanicos")
pq.enqueue(3,"Hombres")
pq.enqueue(4,"Vigia")
pq.enqueue(5,"Capitan")
pq.enqueue(4,"Timonel")
pq.enqueue(3,"Mujeres")
pq.enqueue(2,"3ra Edad")
pq.enqueue(1,"Ninas")
print(pq.to_string())
pq.dequeue()
pq.dequeue()
pq.dequeue()
pq.to_string()
from PriorityQueue import PriorityQueue

patient1 = [2, "John"]
patient2 = [1, "Jim"]
patient3 = [5, "Tim"]
patient4 = [7, "Cindy"]

priorityQueue = PriorityQueue()
priorityQueue.enqueue(patient1)
priorityQueue.enqueue(patient2)
priorityQueue.enqueue(patient3)
priorityQueue.enqueue(patient4)
    
while priorityQueue.getSize() > 0:
    print(str(priorityQueue.dequeue()), end = " ")
예제 #16
0
from PriorityQueue import PriorityQueue

print("Lista de prioridad de desembarqu en caso de emergencia\n")

cp = PriorityQueue()
cp.enqueue(4, "Maestres")
cp.enqueue(2, "Niños")
cp.enqueue(4, "Mecanico")
cp.enqueue(3, "Hombres")
cp.enqueue(4, "Vigia")
cp.enqueue(5, "Capitan")
cp.enqueue(4, "Timonel")
cp.enqueue(3, "Mujeres")
cp.enqueue(2, "3ra Edad")
cp.enqueue(1, "Niñas")

print(cp.to_string())

while cp.is_empty() != True:
    siguiente = cp.dequeue()
    print(f"\nLa tripulacion {siguiente} ha abandonado el barco")
    if cp.is_empty() != True:
        print(f"Tripulacion que falta por evacuar{cp.to_string()}")
    else:
        print("\nLa tripulacion ha evacuado exitosamente")
예제 #17
0
from PriorityQueue import PriorityQueue

patient1 = [2, "John"]
patient2 = [1, "Jim"]
patient3 = [5, "Tim"]
patient4 = [7, "Cindy"]

priorityQueue = PriorityQueue()
priorityQueue.enqueue(patient1)
priorityQueue.enqueue(patient2)
priorityQueue.enqueue(patient3)
priorityQueue.enqueue(patient4)

while priorityQueue.getSize() > 0:
    print(str(priorityQueue.dequeue()), end=" ")