def most_similar(self, query_vec, ef=50):
        query_node = Node("query", query_vec, 0)
        W = priority_queue(query_vec)
        ep = self.enter_point
        curr_level = ep.level
        enter_point = self.enter_point
        visited = set()
        while curr_level > 0:
            changed = True
            while changed is True:
                changed = False
                for neighbor in enter_point.get_neighbors(curr_level):
                    if neighbor in visited:
                        continue
                    visited.add(neighbor)
                    if node_dist(query_node, neighbor) < node_dist(
                            query_node, enter_point):
                        enter_point = neighbor
                        changed = True
                        break
            curr_level -= 1
        enter_points = priority_queue(query_node.vec)
        enter_points.append(enter_point)

        W = self._search_layer(ef, query_node, enter_points, 0)
        neighbors = self._select_neighbors(query_node, W, 0)
        return [(node_dist(query_node, neighbor), neighbor)
                for neighbor in neighbors]
Example #2
0
def dijkstra_helper(algo_input):
    dij_graph = Graph
    inp_lines = algo_input.splitlines()
    line_index = 0

    vert_edge = inp_lines[line_index].split()
    line_index += 1

    n_vertices = int(vert_edge[0])
    n_edges = int(vert_edge[1])
    network = dij_graph(n_vertices, n_edges)
    input_graph = [[n_edges, n_vertices]]

    for _ in range(n_edges):
        inp = inp_lines[line_index].split()
        line_index += 1
        from_edge = inp[0]
        to_edge = inp[1]
        weight = int(inp[2])
        input_graph.append([inp[0], inp[1], inp[2]])
        network.addEdge(from_edge, to_edge, weight)

    source_dest = inp_lines[line_index].split()
    line_index += 1

    source_router = source_dest[0]
    destination_router = source_dest[1]
    network.set_source_dest(source_router, destination_router)
    queue = priority_queue.priority_queue()

    dist, prev, steps = dijkstra(network, queue)
    return (steps, dist, prev, input_graph)
Example #3
0
def search(start, goal):
    # Take in edges information when making graph for UCS procedure
    G = graph.graph()

    # Add starting node to path
    s = G.get_node(start)
    p = path.path()
    p.add_node(s)

    # Add initial path to min-priority queue
    Q = pq.priority_queue()
    Q.append(p)

    while not Q.is_empty():
        # Pop path P with lowest cost
        P = Q.pop()
        '''
        Found goal node!
        
        Now, return string:
            Num nodes visited: ?
            Num nodes in path: ?
            Distance (km):     ?
        '''
        if P.head().label == goal:
            tot_visited = 0
            for i in G.nodes:
                if G.nodes[i].color == 'b':
                    tot_visited += 1
            in_path = len(P.path)
            distance = P.cost

            # Destroy objects
            del G
            del P
            del Q

            print(
                "UCS\nNum nodes visited: {}\nNum nodes on path: {}\nDistance (km): {}"
                .format(tot_visited, in_path, distance))
            return

        # Explore neighbors, add them to new and distinct lists
        for edge in G.edges[P.head().label]:
            # Only consider unvisited nodes
            if G.get_node(edge.v).color == 'w':
                # Get new path--expand on current list and increase total distance
                new_path = path.path(init_path=P.copy(G.get_node(edge.v)),
                                     init_cost=P.cost)
                new_path.cost += float(edge.dist)

                # Append valid path to list of possible paths
                Q.append(new_path)

        # Current node is considered visited, color it black
        P.head().color = 'b'

    # Return failure
    return None
Example #4
0
    def test4_priority_queue_insert(self):
        """Test 5 ~ Test priority queue insert."""
        testQueue = priority_queue()

        distance_1 = 10
        vertex_1 = 0
        testQueue.insert(distance_1, vertex_1)

        self.assertEqual(testQueue.queue, [(distance_1, vertex_1)])
        self.assertEqual(testQueue.length, 1)
Example #5
0
    def test5_priority_queue_heapify(self):
        """Test 6 ~ Test priority queue heapify."""
        testQueue = priority_queue()

        queue_length = 10
        expected_queue = []
        for i in range(queue_length - 1, -1, -1):
            heapq.heappush(expected_queue, (i + 1, i))
            testQueue.insert(i + 1, i)

        self.assertEqual(testQueue.queue, expected_queue)
        self.assertEqual(testQueue.length, queue_length)
Example #6
0
    def test6_priority_queue_sort(self):
        """Test 7 ~ Test priority queue sort."""
        testQueue = priority_queue()

        queue_length = 10
        expected_queue = []
        for i in range(queue_length - 1, -1, -1):
            heapq.heappush(expected_queue, (i + 1, i))
            testQueue.insert(i + 1, i)

        sorted_expected_queue = sorted(expected_queue)
        sorted_return_queue = testQueue.sort()

        self.assertEqual(sorted_expected_queue, sorted_return_queue)
        self.assertEqual(testQueue.length, queue_length)
Example #7
0
def a_s_(s, e, h, w, img):
    pq = priority_queue()
    const = 2000
    found = 0
    visited = [[0 for i in range(w)] for j in range(h)]
    parent = [[Pt() for i in range(w)] for j in range(h)]
    d = heuristic_cost(s, e)
    pq.push(s, d)
    x_c = [0, 0, 1, -1]
    y_c = [1, -1, 0, 0]
    visited[s.y][s.x] = 1
    while pq.size() > 0:
        temp, g = pq._pop()
        if (temp == e):
            found = 1
            break
        for i in range(4):
            t_x = temp.x + x_c[i]
            t_y = temp.y + y_c[i]
            if b.isSafe(t_x, t_y, h, w, img, visited) == True:
                visited[t_y][t_x] = visited[temp.y][temp.x] + 1
                parent[t_y][t_x] = temp
                d = heuristic_cost(Pt(t_x, t_y), e)
                pq.push(Pt(t_x, t_y), d)
                img[t_y][t_x] = list(
                    reversed([
                        i * 255
                        for i in colorsys.hsv_to_rgb(visited[t_y][t_x] /
                                                     const, 1, 1)
                    ]))

    path = []
    if found == 1:
        i = e
        while i != s:
            path.append(Pt(i.x, i.y))
            i = parent[i.y][i.x]
        path.append(s)
        path.reverse()
        for p in path:
            for i in range(-1, 1):
                img[p.y + i][p.x + i] = [0, 0, 0]
        print("Path found")
    else:
        print("Path not found")
Example #8
0
    def test7_priority_queue_remove(self):
        """Test 8 ~ Test priority queue remove."""
        testQueue = priority_queue()

        queue_length = 10
        expected_queue = []
        for i in range(queue_length - 1, -1, -1):
            heapq.heappush(expected_queue, (i + 1, i))
            testQueue.insert(i + 1, i)

        while len(expected_queue) > 0:
            heapq.heappop(expected_queue)
            testQueue.remove()
            self.assertEqual(testQueue.queue, expected_queue)
            self.assertEqual(testQueue.length, len(expected_queue))

        testQueue.remove()

        self.assertEqual(testQueue.queue, [])
        self.assertEqual(testQueue.length, 0)
Example #9
0
    def perform_search(self):
        self.g[0] = 0 # Since 0 is the start state
        closed_list = []
        pq = priority_queue()
        pq.insert(self.roadmap.vertices_dict[0][0],self.roadmap.vertices_dict[0][1],self.g[0],0)

        while not pq.isEmpty():
            temp = pq.pop()

            if [temp.x,temp.y] == self.roadmap.vertices_dict[1]:
                final_path, final_path_idx = [list(reversed(item)) for item in self.get_final_path()]
                return final_path, final_path_idx, self.g[1]

            closed_list.append([temp.x,temp.y])

            successors = self.roadmap.adjacency_dict[temp.idx]
        
            for node_idx in successors:
                if self.roadmap.vertices_dict[node_idx] not in closed_list:
                    xTemp = self.roadmap.vertices_dict[node_idx][0]
                    yTemp = self.roadmap.vertices_dict[node_idx][1]

                    heapIndex = pq.elementInHeap(xTemp,yTemp)

                    distance_index = self.roadmap.adjacency_dict[temp.idx].index(node_idx)

                    gTemp = self.g[temp.idx] + self.roadmap.edge_weights[temp.idx][distance_index] 
                    if gTemp < self.g[node_idx]:
                        self.parents[node_idx] = temp.idx
                        self.g[node_idx] = gTemp

                    if heapIndex != -1:
                        pq.remove(heapIndex)

                    pq.insert(xTemp, yTemp,self.g[node_idx],node_idx)

        return None
def result(input_):
    file_inp = open(input_, "r")
    vert_edge = file_inp.readline().split()
    n_vertices = int(vert_edge[0])
    n_edges = int(vert_edge[1])
    network = graph(n_vertices, n_edges)
    input_graph = [[n_edges, n_vertices]]

    for _ in range(n_edges):
        inp = file_inp.readline().split()
        from_edge = inp[0]
        to_edge = inp[1]
        weight = int(inp[2])
        input_graph.append([inp[0], inp[1], inp[2]])
        network.addEdge(from_edge, to_edge, weight)

    source_dest = file_inp.readline().split()
    source_router = source_dest[0]
    destination_router = source_dest[1]
    network.set_source_dest(source_router, destination_router)
    queue = priority_queue.priority_queue()

    dist, prev, steps = dijkstra(network, queue)
    return(steps, dist, prev, input_graph)
    def solution(self, board):
        if self.isSolvable(board) == False:
            print("Unsolvable puzzle")

        else:
            start = self.board
            num_move = 1
            nodes = []
            items = []
            path = []
            #state_seen = []
            while not self.isgoal(start):
                for state in self.neighbors(start):
                    #for i in state_seen:
                    #if not state.equals(i) or len(state_seen) == 0:
                    man = self.manhattan(state)
                    #num_move += 1
                    priority = man + num_move
                    node = Node.Node(state, priority)
                    #dic[str(state)] = priority
                    #        state_seen.append(state)
                    #print(state_seen)
                    nodes.append(node.get_val())
                    items.append(node)
            #print(nodes)

                pq = priority_queue.priority_queue()
                pq.buildHeap(list(i for i in nodes))
                val = pq.delMin()
                for i in items:
                    if i.get_val() == val:
                        start = i.get_key()
                path.append(start)
                num_move += 1
            #print(start)
            return path
Example #12
0
 def test3_priority_queue_initialization(self):
     """Test 4 ~ Test priority queue constructor."""
     testQueue = priority_queue()
     self.assertEqual(testQueue.queue, [])
     self.assertEqual(testQueue.length, 0)
Example #13
0
from datetime import datetime, timedelta
from priority_queue import priority_queue
from threading import Condition, Timer
import pickle
from message_unit import message_unit
from collections import defaultdict
from queue import Queue
from standup_config import *
#from utils import fetch_display_name
#from bot_config import auth_header

SAVE_FILE = "save.dat"
subscriptions = {}
standups = priority_queue()


standup_oq = Queue()
condition = Condition()


IDLE = 0
CREATING = 1
CREATED = 2
RUNNING = 3


#call update_standup whenever you change standups queue. This will notify the timer thread waiting on the condition to re-calculate timer.
#manual insert, update_standup()
#update_standup(standup)  will also insert
#delete element standups queue, update_standup()
def update_standup(new_standup=None):
    def insert(self, query_name, query_vec):
        if self.enter_point is None:
            node_level = self._draw_level(
            )  # new element level, also top layer of the graph
            self.max_level = node_level
            query_node = Node(query_name, query_vec, node_level)
            self.enter_point = query_node
            if node_level > self.max_level:
                self.max_level = node_level
            self.nodes.append(query_node)
            return
        else:
            node_level = self._draw_level()  # new element level
            query_node = Node(query_name, query_vec, node_level)
        self.nodes.append(query_node)
        curr_level = node_level
        enter_point = self.enter_point
        visited = set()
        while curr_level > self.max_level:
            changed = True
            while changed is True:
                changed = False
                for neighbor in enter_point.get_neighbors(curr_level):
                    if neighbor in visited:
                        continue
                    visited.add(neighbor)
                    if node_dist(query_node, neighbor) < node_dist(
                            query_node, enter_point):
                        enter_point = neighbor
                        changed = True
                        break
            curr_level -= 1

        enter_points = priority_queue(query_node.vec, False)
        enter_points.append(enter_point)

        for curr_level in reversed(range(1 + min(node_level, self.max_level))):
            if curr_level > 0:
                M = self.M
            else:
                M = self.M0
            W = self._search_layer(self.ef_construction, query_node,
                                   enter_points, curr_level)
            neighbors = self._select_neighbors(query_node, W.rebase(query_vec),
                                               curr_level)
            for neighbor in neighbors:
                if query_node != neighbor:
                    query_node.add_neighbor(neighbor, curr_level)
                    neighbor.add_neighbor(query_node, curr_level)
                    if len(neighbor.neighbors[curr_level]) > M:
                        newneighbors = self._select_neighbors(
                            neighbor, neighbor.neighbors[curr_level],
                            curr_level)
                        oldneighbors = copy.copy(
                            neighbor.neighbors[curr_level])
                        for on in oldneighbors:
                            on.del_neighbor(neighbor, curr_level)
                            neighbor.del_neighbor(neighbor, curr_level)
                        for nn in newneighbors:
                            nn.add_neighbor(neighbor, curr_level)
                            neighbor.add_neighbor(nn, curr_level)

            enter_points = W

        if node_level > self.max_level:
            self.max_level = node_level
            self.enter_point = query_node