def test_remove_asc_num(self): pq = pqueue.PriorityQueue(self.cmp_asc_num) pq.insert(3) pq.insert(45) pq.insert(-123) self.assertEqual(pq.remove(), -123) self.assertEqual(pq.remove(), 3) self.assertEqual(pq.remove(), 45)
def test_remove_asc_len(self): pq = pqueue.PriorityQueue(self.cmp_asc_len) pq.insert('g') pq.insert('zzz') pq.insert('bb') self.assertEqual(pq.remove(), 'g') self.assertEqual(pq.remove(), 'bb') self.assertEqual(pq.remove(), 'zzz')
def test_basic_operations(): pq = PriorityQueue.PriorityQueue() pq.enqueue(8, 'Sam') pq.enqueue(6, 'Tristen') pq.dequeue() == (6, 'Tristen') assert pq.peek() == (8, 'Sam') pq.enqueue(1, 'of one') assert str(pq) == "[[1, 'of one'], [8, 'Sam']]" pq2 = PriorityQueue.PriorityQueue() pq2.enqueue(8, 'Sam') pq2.enqueue(1, 'of one') assert pq == pq2 pq2.clear() assert pq2.is_empty()
def dijkstra(user, start): dist = {} prev = {} # list of different sizes of the same node as start same_item_nodes = graph.get_same_nodes(start) # initialize all costs to infinity except start for node in graph.neighbors_lst: dist[node] = float("inf") dist[start] = 0 Q = pqueue.PriorityQueue() Q.push(start, 0) expanded = 0 # while there are still nodes to be popped while not Q.is_empty(): v = Q.pop() # increment the number of expanded nodes expanded += 1 # if node has already been purchased by user (stop condition) if v in user.node_rating_dict: rating = user.node_rating_dict[v] current = v confidence = 1 length_of_path = 0 # aggregate confidences and ratings across path while current is not start: rating += graph.edge_matrix[current][ prev[current]].mean_of_diffs confidence *= graph.edge_matrix[current][ prev[current]].confidence length_of_path += 1 current = prev[current] # pick size of start item that would have best rating (closest to 50), update confidence if necessary (multiply by 0.7: confidence of fake edge) best_rating_so_far = rating best_diff_so_far = (abs(rating - 50), start) for node in same_item_nodes: if abs(rating + graph.edge_matrix[start][node].mean_of_diffs - 50) < best_diff_so_far[0]: best_diff_so_far = ( rating + graph.edge_matrix[start][node].mean_of_diffs - 50, node) best_rating_so_far = rating + graph.edge_matrix[start][ node].mean_of_diffs if best_diff_so_far[1] == start: return (best_diff_so_far[1], best_rating_so_far, confidence, length_of_path, expanded) return (best_diff_so_far[1], best_rating_so_far, confidence * graph.edge_matrix[start][best_diff_so_far[1]].confidence, length_of_path + 1, expanded) # push node on heap if appropriate, unless node is same item as the start node for neighbor in graph.neighbors_lst[v]: if dist[neighbor] > dist[v] + graph.edge_matrix[v][ neighbor].cost and neighbor not in same_item_nodes: dist[neighbor] = dist[v] + graph.edge_matrix[v][neighbor].cost Q.push(neighbor, dist[neighbor]) prev[neighbor] = v
def test_is_empty(self): pq = pqueue.PriorityQueue() self.assertTrue(pq.is_empty()) pq.insert(3) pq.insert(4) pq.insert(2) self.assertFalse(pq.is_empty()) pq.remove() pq.remove() pq.remove() self.assertTrue(pq.is_empty())
def __init__(self) -> None: ''' Check for dat file, serializes all dag file DAG objects, sets dags set class attribute ''' signal.signal(signal.SIGINT, lambda x, y: sys.exit(0)) self.db = {} self.dags = pqueue.PriorityQueue() self.tsq = Queue() self.lock = mt.Lock() self.store_dags() self.bus = Bus(self.lock, self.tsq, self.db, self.dags) self.bus.start() self.printdb() self.seat_sections()
def astar(user, start): g = {} f = {} prev = {} same_item_nodes = [] for node in graph.neighbors_lst[start]: if graph.edge_matrix[start][node].same_item: same_item_nodes.append(node) for node in graph.neighbors_lst: f[node] = float("inf") f[start] = 0 g[start] = 0 Q = pqueue.PriorityQueue() Q.push(start, 0) expanded = 0 while not Q.is_empty(): v = Q.pop() expanded += 1 if v in user.node_rating_dict: rating = user.node_rating_dict[v] current = v confidence = 1 length_of_path = 0 while current is not start: rating += graph.edge_matrix[current][prev[current]].mean_of_diffs confidence *= graph.edge_matrix[current][prev[current]].confidence length_of_path += 1 current = prev[current] best_rating_so_far = rating best_diff_so_far = (abs(rating - 50), start) for node in same_item_nodes: if abs(rating + graph.edge_matrix[start][node].mean_of_diffs - 50) < best_diff_so_far[0]: best_diff_so_far = (rating + graph.edge_matrix[start][node].mean_of_diffs - 50, node) best_rating_so_far = rating + graph.edge_matrix[start][node].mean_of_diffs if best_diff_so_far[1] == start: return (best_diff_so_far[1], best_rating_so_far, confidence, length_of_path, expanded) return (best_diff_so_far[1], best_rating_so_far, confidence*graph.edge_matrix[start][best_diff_so_far[1]].confidence, length_of_path+1, expanded) for neighbor in graph.neighbors_lst[v]: # update real cost so far g[neighbor] = g[v] + graph.edge_matrix[v][neighbor].cost if f[neighbor] > g[neighbor] + heuristic(user, neighbor) and neighbor not in same_item_nodes: # add heuristic to real cost to get total cost f[neighbor] = g[neighbor] + heuristic(user, neighbor) Q.push(neighbor, f[neighbor]) prev[neighbor] = v
def A_STAR(puzzle, score_func=fscore_hamming): puzzle.score = score_func(puzzle) queue = pqueue.PriorityQueue(score_func) queue.push(puzzle) visited = {} while queue: cur = queue.pop() visited[str(cur.state)] = True if cur.state == cur.solution: cur.printSolution() return children = cur.expand() for child in children: child.score = score_func(child) if str(child.state) not in visited: queue.push(child)
def UCS(puzzle): puzzle.score = puzzle.depth # Assign score to depth queue = pqueue.PriorityQueue(lambda node: node.depth) # Initialize queue with depth as prio. func. queue.push(puzzle) # Push initial puzzle state visited = {} # Initialize visited dictionary to prevent dup. states while queue: cur = queue.pop() # Visit the current node visited[str(cur.state)] = True if cur.state == cur.solution: cur.printSolution() return children = cur.expand() # Expand children and score based on depth for child in children: # Add them to the queue if unvisited child.score = child.depth # The queue will maintain depth priorty for poped node if str(child.state) not in visited: queue.push(child)
def test_instance(graph_file, seed, algorithm, output_file): graph = nx.read_adjlist(graph_file) graph = graphutils.convert_nodes_to_integers(graph) random.seed(seed) if algorithm["type"] == "sleepwell": Node = sleepwell.SleepWellNode elif algorithm["type"] == "solo": Node = solo.SoloNode solo.ALPHA = algorithm["alpha"] elif algorithm["type"] == "solo2": Node = solo2.SoloNode solo2.ALPHA = algorithm["alpha"] elif algorithm["type"] == "desync": Node = desync.DesyncNode desync.ALPHA = algorithm["alpha"] queue = pq.PriorityQueue() num_nodes = len(graph) offset_list = [random.randint(0, INTERVAL - 1) for _ in range(num_nodes)] node_list = [Node(i, queue) for i in range(num_nodes)] for i, node in enumerate(node_list): node.set_links([node_list[j] for j in graph.neighbors(i)]) queue.add_task((node.start, (None, )), offset_list[i]) while queue.current < SIMULATION_DURATION: func, argv = queue.pop_task() func(*argv) log = [] for i, node in enumerate(node_list): log += node.log log = sorted(log) log = ["%d,%d,%s,%s" % tup for tup in log] with open(output_file, "w") as fo: fo.write("\n".join(log) + "\n") print("Log saved in ./%s." % output_file)
def GREEDY(puzzle, heuristic=heuristics.hamming): puzzle.score = heuristic(puzzle) # Set initial score using heuristic queue = pqueue.PriorityQueue( heuristic) # Initialize queue with given heuristic for priority queue.push(puzzle) # Add first puzzle to queue visited = {} # Initialize dictionary to keep track of visited states while queue: cur = queue.pop( ) # Pop the item with the best heuristic score (located at front) visited[str(cur.state)] = True # Mark current state as visiteed if cur.state == cur.solution: # Check for solution, if so exit cur.printSolution() return children = cur.expand( ) # Expand the current node, assign scores, and push to queue for child in children: # the queue will maintain the best puzzle at the top to be poped child.score = heuristic(child) if str(child.state) not in visited: queue.push(child) print("No Solution") # No solution found (puzzle insolvable)
def setUp(self): self.q = pqueue.PriorityQueue()
def test_insert(self): pq = pqueue.PriorityQueue() pq.insert(3) pq.insert(4) pq.insert(2) self.assertEqual(str(pq), '[3, 4, 2]')
def test_create_empty_queue(): pq = PriorityQueue.PriorityQueue() assert pq.is_empty()
def perimeter_search(user, start, limit): # initialize goal sides' arrays, dicts, queues prevEnds = [None for i in range(len(user.node_rating_dict))] distEnds = [None for i in range(len(user.node_rating_dict))] visitedEnds = [None for i in range(len(user.node_rating_dict))] queueEnds = [None for i in range(len(user.node_rating_dict))] goals = list(user.node_rating_dict.keys()) for i in range(len(user.node_rating_dict)): prevEnds[i] = {} distEnds[i] = {} visitedEnds[i] = {} for node in graph.neighbors_lst: distEnds[i][node] = float('inf') distEnds[i][goals[i]] = 0 queueEnds[i] = pqueue.PriorityQueue() queueEnds[i].push(goals[i], 0) # initialize start side distStart = {} visitedStart = {} nodesExpanded = 0 intersection = None best_path = float("inf") for node in graph.neighbors_lst: distStart[node] = float('inf') prevStart = {} distStart[start] = 0 g = {} g[start] = 0 queueStart = pqueue.PriorityQueue() queueStart.push(start, 0) same_item_nodes = graph.get_same_nodes(start) while while_condition(queueStart, queueEnds): # if have already found a path, greedily take it if best_path != float("inf"): rating = user.node_rating_dict[goals[intersection[1]]] confidence = 1 length_of_path = 0 if intersection is None: raise ValueError("intersection is None") current = intersection[0] # aggregate ratings and confidences across path while current is not start: rating += graph.edge_matrix[current][ prevStart[current]].mean_of_diffs confidence *= graph.edge_matrix[current][ prevStart[current]].confidence length_of_path += 1 current = prevStart[current] current = intersection[0] i = intersection[1] while current is not goals[i]: rating -= graph.edge_matrix[current][prevEnds[i] [current]].mean_of_diffs confidence *= graph.edge_matrix[current][prevEnds[i] [current]].confidence length_of_path += 1 current = prevEnds[i][current] # decide whether to take a fake edge from the start or not (just like UCS) best_rating_so_far = rating best_diff_so_far = (abs(rating - 50), start) for node in same_item_nodes: if abs(rating + graph.edge_matrix[start][node].mean_of_diffs - 50) < best_diff_so_far[0]: best_diff_so_far = ( rating + graph.edge_matrix[start][node].mean_of_diffs - 50, node) best_rating_so_far = rating + graph.edge_matrix[start][ node].mean_of_diffs if best_diff_so_far[1] == start: return (best_diff_so_far[1], best_rating_so_far, confidence, length_of_path, nodesExpanded) return (best_diff_so_far[1], best_rating_so_far, confidence * graph.edge_matrix[start][best_diff_so_far[1]].confidence, length_of_path + 1, nodesExpanded) # expand from start's side v = queueStart.pop() visitedStart[v] = True nodesExpanded += 1 for neighbor in graph.neighbors_lst[v]: g[neighbor] = g[v] + graph.edge_matrix[v][neighbor].cost if distStart[neighbor] > g[neighbor] + heuristic( user, neighbor) and neighbor not in same_item_nodes: distStart[neighbor] = g[neighbor] + heuristic(user, neighbor) queueStart.push(neighbor, distStart[neighbor]) prevStart[neighbor] = v for i in range(len(visitedEnds)): if neighbor in visitedEnds[i]: if (best_path > distStart[v] + graph.edge_matrix[v][neighbor].cost + distEnds[i][neighbor] and neighbor not in same_item_nodes): best_path = distStart[v] + graph.edge_matrix[v][ neighbor].cost + distEnds[i][neighbor] intersection = (neighbor, i) prevStart[neighbor] = v # expand from every goal's side for i in range(len(visitedEnds)): u = queueEnds[i].pop() visitedEnds[i][u] = True nodesExpanded += 1 for neighbor in graph.neighbors_lst[u]: if neighbor in visitedStart: if (best_path > distEnds[i][u] + graph.edge_matrix[u][neighbor].cost + distStart[neighbor] and neighbor not in same_item_nodes): best_path = distEnds[i][u] + graph.edge_matrix[u][ neighbor].cost + distStart[neighbor] intersection = (neighbor, i) prevEnds[i][neighbor] = u # make sure to never push anything on the queue if it has a cost higher than the threshold of perimeter search if distEnds[i][neighbor] > distEnds[i][u] + graph.edge_matrix[u][ neighbor].cost and distEnds[i][u] + graph.edge_matrix[u][ neighbor].cost <= limit and neighbor not in same_item_nodes: distEnds[i][neighbor] = distEnds[i][u] + graph.edge_matrix[ u][neighbor].cost queueEnds[i].push(neighbor, distEnds[i][neighbor]) prevEnds[i][neighbor] = u