Exemplo n.º 1
0
def pq_setup():
    """Create random order entry of values into priority queue"""
    pq = PriorityQ()

    for num in range(1, 200):
        pq.insert(randint(1, 10))
    return pq
Exemplo n.º 2
0
def test_pop_empty():
    """Test that popping an empty list raises an index error."""
    from priorityq import PriorityQ
    instance = PriorityQ()

    with pytest.raises(IndexError):
        instance.pop()
def test_pop_empty():
    """Test that popping an empty list raises an index error."""
    from priorityq import PriorityQ
    instance = PriorityQ()

    with pytest.raises(IndexError):
        instance.pop()
def test_insert_item_QNode_to_empty():
    node1 = QNode(10, priority=0)
    pqueue = PriorityQ()
    pqueue.insert(node1)
    assert len(pqueue) == 1
    assert pqueue[0].val == 10
    assert pqueue[0].priority == 0
Exemplo n.º 5
0
 def test_insert_one(self):
     pri, val = 2, 'a'
     testq = PriorityQ()
     testq.insert(pri, val)
     actual = testq.harray
     expected = [[None], [pri, val]]
     self.assertEquals(expected, actual)
Exemplo n.º 6
0
def test_initialize_with_single_tuple():
    """The test initializes priority q with a single tuple."""
    from priorityq import PriorityQ
    new_pq = PriorityQ((3, 2))
    assert len(new_pq) == 1
    assert new_pq._high_p == 2
    assert new_pq.peek() == 3
Exemplo n.º 7
0
def q10():
    """Create Q with 10 priorities that contain 1 value each."""
    from priorityq import PriorityQ
    q = PriorityQ()
    for i in range(1, 10):
        q.insert('a', i)
    return q
Exemplo n.º 8
0
 def test_2(self):
     """ test that insert puts the node in the queue in the correct position with no priority assignment """
     p = PriorityQ()
     n1 = Node(1)
     n2 = Node(2)
     p.insert(n1)
     p.insert(n2)
     self.assertEqual(p.head._value, 1)
Exemplo n.º 9
0
def test_pq_insert_len():
    pq = PriorityQ()
    for num in range(10):
        pq.insert(1)
    p1 = pq.priorities[1]
    assert len(p1.heap_list) is 10
    pq.insert(1)
    assert len(p1.heap_list) is 11
Exemplo n.º 10
0
def test_pop_values_of_same_priority_acts_like_queue(amount):
    """Test that popping only item from queue empties it."""
    from random import randint
    from priorityq import PriorityQ
    q = PriorityQ()
    random_nums = [randint(0, 100) for _ in range(amount)]
    for n in random_nums:
        q.insert(n)
    popped = [q.pop() for _ in random_nums]
    assert popped == random_nums
Exemplo n.º 11
0
def test_peek():
    """Test that peeking reveals the root of the priority queue."""
    from priorityq import PriorityQ
    push_list = [(2, 'maintenance'), (1, 'staff mtg'), (1, 'stand-up'),
                 (0, 'server crash'), (0, 'boss DUI')]

    test_q = PriorityQ()
    for pri, val in push_list:
        test_q.insert(pri, val)

    assert test_q.peek() == 'server crash'
Exemplo n.º 12
0
def full_priorityq():
    priorityq = PriorityQ()
    priorityq.insert(3, 8)
    priorityq.insert(5, 2)
    priorityq.insert(6, 3)
    priorityq.insert(4, 10)
    priorityq.insert(7, 3)
    return priorityq
Exemplo n.º 13
0
def test_insert():
    from priorityq import PriorityQ
    push_list = [(2, 'maintenance'), (1, 'staff mtg'), (1, 'stand-up'),
                 (0, 'server crash')]

    pop_list = ['server crash', 'staff mtg', 'stand-up', 'maintenance']

    test_q = PriorityQ()
    for pri, val in push_list:
        test_q.insert(pri, val)

    for item in pop_list:
        assert test_q.pop() == item
def test_peek():
    """Test that peeking reveals the root of the priority queue."""
    from priorityq import PriorityQ
    push_list = [(2, 'maintenance'),
                 (1, 'staff mtg'),
                 (1, 'stand-up'),
                 (0, 'server crash'),
                 (0, 'boss DUI')]

    test_q = PriorityQ()
    for pri, val in push_list:
        test_q.insert(pri, val)

    assert test_q.peek() == 'server crash'
Exemplo n.º 15
0
def test_pop_from_random_p_q_with_all_diff_priority_in_sorted_order():
    """Test popping all the items from a priority queue are in sorted order.

    All items inserted have the same priority as their value, so when
    removed they should be in sorted order.
    """
    from priorityq import PriorityQ
    from random import randint
    random_nums = list(set([randint(0, 100) for _ in range(20)]))
    q = PriorityQ()
    for n in random_nums:
        q.insert(n, n)
    popped = [q.pop() for _ in range(len(q._all_values) - 1)]
    assert popped == sorted(random_nums, reverse=True)
def test_insert():
    from priorityq import PriorityQ
    push_list = [(2, 'maintenance'),
                 (1, 'staff mtg'),
                 (1, 'stand-up'),
                 (0, 'server crash')]

    pop_list = ['server crash', 'staff mtg', 'stand-up', 'maintenance']

    test_q = PriorityQ()
    for pri, val in push_list:
        test_q.insert(pri, val)

    for item in pop_list:
        assert test_q.pop() == item
Exemplo n.º 17
0
 def test_peek_with_1_elem(self):
     pri1, val1 = 2, 'a'
     pri2, val2 = 5, 'b'
     pri3, val3 = 1, 'c'
     pri4, val4 = 4, 'd'
     pri5, val5 = 3, 'e'
     testq = PriorityQ()
     testq.insert(pri1, val1)
     testq.insert(pri2, val2)
     testq.insert(pri3, val3)
     testq.insert(pri4, val4)
     testq.insert(pri5, val5)
     x = testq.peek()
     self.assertEquals(x, 'c')
Exemplo n.º 18
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    CLOSED = []
    BACKLINKS[initial_state] = None
    g = {initial_state: 0}

    OPEN.insert(initial_state, heuristics(initial_state))

    while not len(OPEN) == 0:
        S, f = OPEN.deletemin()
        while S in CLOSED:
            S, f = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        print(COUNT)

        L = []
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state, CLOSED):
                    L.append(new_state)
                    BACKLINKS[new_state] = S
                    if new_state not in g.keys():
                        g[new_state] = g[S] + 1

        for s2 in L:
            if s2 in OPEN:
                OPEN.remove(s2)

        for elt in L:
            OPEN.insert(elt, heuristics(elt) + g[elt])
Exemplo n.º 19
0
 def test_pop_with_2_elem(self):
     pri1, val1 = 2, 'a'
     pri2, val2 = 5, 'b'
     pri3, val3 = 1, 'c'
     pri4, val4 = 7, 'f'
     pri5, val5 = 1, 'd'
     pri6, val6 = 3, 'e'
     testq = PriorityQ()
     testq.insert(pri1, val1)
     testq.insert(pri2, val2)
     testq.insert(pri3, val3)
     testq.insert(pri4, val4)
     testq.insert(pri5, val5)
     testq.insert(pri6, val6)
     testq.pop()
     expected = [[None], [pri3, val5], [pri6, val6], [pri1, val1],
                 [pri4, val4], [pri2, val2]]
     actual = testq.harray
     self.assertEquals(expected, actual)
Exemplo n.º 20
0
 def test_insert_many(self):
     pri1, val1 = 2, 'a'
     pri2, val2 = 5, 'b'
     pri3, val3 = 1, 'c'
     pri4, val4 = 4, 'd'
     pri5, val5 = 3, 'e'
     testq = PriorityQ()
     testq.insert(pri1, val1)
     testq.insert(pri2, val2)
     testq.insert(pri3, val3)
     testq.insert(pri4, val4)
     testq.insert(pri5, val5)
     expected = [[None], [pri3, val3], [pri5, val5], [pri1, val1],
                 [pri2, val2], [pri4, val4]]
     actual = testq.harray
     self.assertEquals(expected, actual)
Exemplo n.º 21
0
 def test_3(self):
     """ test that insert puts the node in the queue in the correct position if given a priority value """
     p = PriorityQ()
     n1 = Node(1)
     n2 = Node(2)
     n3 = Node(3)
     p.insert(n1, 1)
     p.insert(n2, 2)
     p.insert(n3, 3)
     self.assertEqual(p.head._priority, 3)
Exemplo n.º 22
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    CLOSED = []
    #define the g score which means
    #the cost of the move will increase by 1 at each depth
    g = {}
    g[initial_state] = 0
    BACKLINKS[initial_state] = None
    #in priority queue, the state is the element
    #and the F score is the priority
    #F socre is the heuristics score plus g scorce
    OPEN.insert(initial_state, g[initial_state] + 0)

    while not OPEN.isEmpty():
        COUNT += 1
        S = OPEN.deletemin()
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)
        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

            # TODO: finish A* implementation
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not (new_state in CLOSED):
                    h = heuristics(new_state)
                    g[new_state] = g[S] + 1
                    if new_state not in OPEN:
                        OPEN.insert(new_state, h + g[new_state])
                        BACKLINKS[new_state] = S
Exemplo n.º 23
0
 def test_many_equal_priorities(self):
     pri1, val1 = 2, 'a'
     pri2, val2 = 5, 'b'
     pri3, val3 = 1, 'c'
     pri4, val4 = 2, 'f'
     pri5, val5 = 4, 'd'
     pri6, val6 = 3, 'e'
     testq = PriorityQ()
     testq.insert(pri1, val1)
     testq.insert(pri2, val2)
     testq.insert(pri3, val3)
     testq.insert(pri4, val4)
     testq.insert(pri5, val5)
     testq.insert(pri6, val6)
     expected = [[None], [pri3, val3], [pri6, val6], [pri1, val1, val4],
                 [pri2, val2], [pri5, val5]]
     actual = testq.harray
     self.assertEquals(expected, actual)
Exemplo n.º 24
0
def AStar(initial_state):
     # this breaks pq ties
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    CLOSED = []
    OPEN.insert(initial_state,0)
    BACKLINKS[initial_state] = None

    while not OPEN.isEmpty():
        COUNT += 1
        S = OPEN.deletemin()
        while S in CLOSED:
            S = OPEN.deletemin()

        CLOSED.append(S)
        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        # TODO: finish A* implementation
        for op in Problem.OPERATORS:
          #Optionally uncomment the following when debugging
          #a new problem formulation.
          # print("Trying operator: "+op.name)
          if op.precond(S):
            new_state = op.state_transf(S)
            if not (new_state in CLOSED):
                h = heuristics(new_state)
                #new_pq_item = ( new_state,h)
                OPEN.insert(new_state , h)
                BACKLINKS[new_state] = S
Exemplo n.º 25
0
def test_insert():
    priorityq = PriorityQ()
    priorityq.insert(3, 8)
    assert priorityq.list[0].value == 3
Exemplo n.º 26
0
def test_intitalize_with_single_digit():
    """The test initialized a prio q with a single digit."""
    from priorityq import PriorityQ
    with pytest.raises(TypeError):
        PriorityQ(3)
def test_empty_instantiation_args():
    tpq = PriorityQ()
    with pytest.raises(IndexError):
        tpq.pop()
def test_valid_instantiation_args(input):
    tpq = PriorityQ(input)
    assert tpq.pop() is not None
Exemplo n.º 29
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    OPEN = PriorityQ()  #currently discovered, not yet evaluated states
    CLOSED = []  #already evaluated states
    BACKLINKS[initial_state] = None  #Tracks most efficient previous step

    #Calculate F, G, H scores for Starting state
    initialize_scores(initial_state)

    #Only one state is known as of now
    OPEN.insert(initial_state, F_SCORE[initial_state])

    while OPEN.isEmpty() != True:
        S, priority = OPEN.deletemin()
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: beginning
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        if (COUNT % 32) == 0:
            #        if True:
            # print(".",end="")
            #            if (COUNT % 128*128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                #print("len(OPEN)=" + str(len(OPEN))) #PriorityQ OPEN doesn't have len()
                print("len(CLOSED)=" + str(len(CLOSED)))

        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state,
                                 CLOSED):  #ignore already evaluated neighbors

                    #find tentative score of neighbor
                    tentative_g_score = G_SCORE[S] + 1

                    if new_state not in G_SCORE:  #Default INFINITY
                        BACKLINKS[
                            new_state] = S  #First known path to new_state

                    elif tentative_g_score <= G_SCORE[new_state]:
                        BACKLINKS[
                            new_state] = S  # Found better path to new_State

                    else:
                        continue  #current path is not the best path to the neighbor

                    G_SCORE[new_state] = tentative_g_score
                    F_SCORE[new_state] = G_SCORE[new_state] + h_score_fn(
                        new_state)

                    # Delete previous F-score in PriorityQ if it exists
                    if OPEN.__contains__(new_state):
                        OPEN.remove(new_state)

                    #Update PriorityQ with new priority
                    OPEN.insert(new_state, F_SCORE[new_state])

                # print(Problem.DESCRIBE_STATE(new_state))
        #print(OPEN)

    #Failure, if goal_test has not succeeded until now
    print("COULD NOT FIND GOAL")
    return
def test_insert_item_not_QNode_to_empty():
    queue = PriorityQ()
    queue.insert(50)
    assert len(queue) == 1
    assert queue[0].val == 50
    assert queue[0].priority is None
Exemplo n.º 31
0
def pop_empty():
    priorityq = PriorityQ()
    with pytest.raises(IndexError):
        priorityq.pop()
Exemplo n.º 32
0
from priorityq import PriorityQ
import EightPuzzle
import EightPuzzleWithHeuristics
OPEN = PriorityQ()
s1 = EightPuzzle.State([0, 1, 2, 3, 4, 5, 6, 7, 8])
s2 = EightPuzzle.State([1, 0, 2, 3, 4, 5, 6, 7, 8])
s3 = EightPuzzle.State([1, 0, 3, 2, 4, 5, 6, 7, 8])
h1 = EightPuzzleWithHeuristics.h_euclidean(s1)
h2 = EightPuzzleWithHeuristics.h_euclidean(s2)
h3 = EightPuzzleWithHeuristics.h_euclidean(s3)
OPEN.insert(s1, h1)
OPEN.insert(s2, h2)
OPEN.insert(s3, h3)
print(OPEN)
s = OPEN.deletemin()
print(s)
s = OPEN.deletemin()
print(s)
OPEN.deletemin()
print(OPEN)
Exemplo n.º 33
0
def empty_priority_q():
    """Thie fixture creates and empty priority queue."""
    from priorityq import PriorityQ
    new_pq = PriorityQ()
    return new_pq
Exemplo n.º 34
0
def test_pop_last():
    priorityq = PriorityQ()
    priorityq.insert(5, 2)
    assert priorityq.pop() == 5
    assert priorityq.list == []
Exemplo n.º 35
0
def empty_priorityq():
    """Create an empty priority queue."""
    from priorityq import PriorityQ
    return PriorityQ()
Exemplo n.º 36
0
def test_PriorityQ_default():
    test_pq = PriorityQ([1, 2, 3])
    assert test_pq._priority_heap._heap_list[0]._priority == 1
Exemplo n.º 37
0
def test_pq():
    return PriorityQ(PQ_ITEM_LIST)
Exemplo n.º 38
0
def empty_q():
    """Create empty BinaryHeap."""
    from priorityq import PriorityQ
    return PriorityQ()
Exemplo n.º 39
0
 def test_1(self):
     """ test that insert puts the node in the queue """
     p = PriorityQ()
     n1 = Node(1)
     p.insert(n1)
     self.assertEqual(p.head._value, 1)
Exemplo n.º 40
0
def test_insert_more():
    priorityq = PriorityQ()
    priorityq.insert(3, 8)
    priorityq.insert(5, 2)
    assert priorityq.list[0].value == 5
    assert priorityq.list[1].value == 3
Exemplo n.º 41
0
def filled_priority_q():
    """The fixture creates a filled priority queue."""
    from priorityq import PriorityQ
    new_pq = PriorityQ(TEST_SET[0])
    return new_pq
Exemplo n.º 42
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    # inserts the initial state with a priority of 0 (priority for initial state is irrelevant to algorithm)
    OPEN.insert(initial_state, 0)
    CLOSED = []
    BACKLINKS[initial_state] = None

    while OPEN.__len__() > 0:
        # S = min-priority state (priority value gets discarded, only state is looked at)
        S = OPEN.deletemin()[0]
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: beginning
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        # if (COUNT % 32)==0:
        if True:
            # print(".",end="")
            # if (COUNT % 128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                print("len(OPEN)=" + str(len(OPEN)))
                print("len(CLOSED)=" + str(len(CLOSED)))

        L = []
        # looks at all possible new states from operations on S
        # if the new state has not already been put on CLOSED, append to L
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                #print(new_state.__str__())
                if not occurs_in(new_state, CLOSED):
                    L.append(new_state)
                    BACKLINKS[new_state] = S

        # adds new states in L into OPEN with their priorities
        # if any state already occurs in OPEN...
        #   if L's state has a lower priority, change OPEN's state priority to L's
        #   otherwise, keep OPEN's state in OPEN, ignore L's
        for state in L:
            g_state = G(state)
            if OPEN.__contains__(state):
                if g_state < OPEN.getpriority(state):
                    OPEN.remove(state)
                else:
                    break
            OPEN.insert(state, g_state)
Exemplo n.º 43
0
def sample_priorityq():
    """Make a sample_priorityq for testing."""
    from priorityq import PriorityQ
    return PriorityQ()
Exemplo n.º 44
0
def pq_setup_large():
    pq = PriorityQ()

    for num in range(1, 10001):
        pq.insert(randint(1, 10))
    return pq
Exemplo n.º 45
0
def AStar(initial_state):
    # print("In RecDFS, with depth_limit="+str(depth_limit)+", current_state is ")
    # print(Problem.DESCRIBE_STATE(current_state))
    global COUNT, BACKLINKS

    #Tracks most efficient previous step
    BACKLINKS[initial_state] = None

    #already evaluated states
    CLOSED = []

    #currently discovered, not yet evaluated states
    OPEN = PriorityQ()

    #Calculate F, G, H scores
    initialize_scores(initial_state)

    #Only initial node is known as of now
    OPEN.insert(initial_state, F_SCORE[initial_state])

    while OPEN.isEmpty() != True:
        S = OPEN.deletemin()
        CLOSED.append(S)

        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            backtrace(S)
            return  #FOUND GOAL

        COUNT += 1
        if (COUNT % 32) == 0:
            #        if True:
            # print(".",end="")
            #            if (COUNT % 128*128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                #print("len(OPEN)=" + str(len(OPEN))) #PriorityQ OPEN doesn't have len()
                print("len(CLOSED)=" + str(len(CLOSED)))

        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state,
                                 CLOSED):  #ignore already evaluated neighbors

                    #find tentative score of neighbor
                    tentative_g_score = G_SCORE[S] + 1

                    if new_state not in G_SCORE:  #Default INFINITY
                        BACKLINKS[
                            new_state] = S  #First known path to new_state
                    elif tentative_g_score >= G_SCORE[new_state]:
                        continue  #current path is not the best path to the neighbor
                    else:
                        BACKLINKS[
                            new_state] = S  #Found better path to new_State

                    G_SCORE[new_state] = tentative_g_score
                    F_SCORE[new_state] = G_SCORE[new_state] + h_score_fn(
                        new_state)

                    # discovered a new State
                    if not OPEN.__contains__(new_state):
                        OPEN.insert(new_state, F_SCORE[new_state])

                    # print(Problem.DESCRIBE_STATE(new_state))
            #print(OPEN)

    #Failure, if goal_test has not succeeded until now
    print("COULD NOT FIND GOAL")
    return