def main(): tasks = Dispenser(why_not) time = 0 cmd, args = get_cmd( COMMANDS ) while cmd != QUIT_CMD: if cmd == TICK_CMD: time += 1 if not tasks.isEmpty(): current = tasks.peek() current.time_left -= 1 if current.time_left == 0: print( "\nTask '" + current.name + \ "' completed at time " + str( time ) + "." ) tasks.remove() if not tasks.isEmpty(): print( "New task is '" + tasks.peek().name + "'." ) else: print( "Nothing else to do." ) else: print( "Nothing to do." ) elif cmd == ADD_CMD: new_task = Task( args[ 0 ], int( args[ 1 ] ) ) tasks.insert( new_task ) print( "\nAdded. Current task is '" + tasks.peek().name + \ "'." ) else: assert True, "PROGRAM ERROR" cmd, args = get_cmd( COMMANDS ) print( "\nTerminating the simulation." )
def adiciona_vertice(self, v): ''' Inclui um vértice no grafo se ele estiver no formato correto. :param v: O vértice a ser incluído no grafo. :raises VerticeInvalidoException se o vértice já existe ou se ele não estiver no formato válido. ''' if v in self.N: raise VerticeInvalidoException('O vértice {} já existe'.format(v)) if self.vertice_valido(v): if len(v) > self.__maior_vertice: self.__maior_vertice = len(v) self.N.append(v) # Adiciona vértice na lista de vértices self.M.append([]) # Adiciona a linha self.Mfila.append([]) self.quantidadeVertices += 1 # incrementa Quantidade de Vertices for k in range(len(self.N)): if k != len(self.N) -1: self.M[k].append(0) # adiciona os elementos da coluna do vértice self.Mfila[k].append(PriorityQueue()) self.M[self.N.index(v)].append('-') # adiciona os elementos da linha do vértice self.Mfila[self.N.index(v)].append(()) else: self.M[self.N.index(v)].append(0) # adiciona um zero no último elemento da linha self.Mfila[self.N.index(v)].append(PriorityQueue()) else: raise VerticeInvalidoException('O vértice ' + v + ' é inválido')
def dijkstra(start, C): openSet = PriorityQueue() openSet_check = {} closedSet = {} g = {} for i in range(len(start)): g[start[i]] = 0 for i in range(len(start)): openSet.put(start[i], 0) openSet_check[start[i]] = 1 while not openSet.empty(): currentState = openSet.get() closedSet[currentState] = 1 for nextState in get_successors(currentState): if nextState in closedSet: continue newCost = g[currentState] + get_cost(C, nextState) if nextState not in openSet_check: g[nextState] = newCost openSet.put(nextState, g[nextState]) openSet_check[nextState] = 1 elif newCost >= g[nextState]: continue else: g[nextState] = newCost openSet.update(nextState, g[nextState]) openSet_check[nextState] = 1 temp = '' #For printing the H as a grid: '''for i in range(N): for j in range(N): if j==0: temp +=str(g[(i,j)]) else: temp +=','+str(g[(i,j)]) temp += "\n" print temp''' #For writing the H onto a file f = open('heuristic.txt', 'w') temp = '' for i in range(N): temp = '' for j in range(N): if j == 0: temp += str(g[(i, j)]) else: temp += ',' + str(g[(i, j)]) if i == 0: f.write(temp) else: f.write('\n' + temp) f.close() return False
def getWay(start, end): """ Знаходить найкоротший шлях, між двома заданими вершинами графа @param start: початкова вершина @param end: кінцева вершина @return: список вершин шляху або порожній список, якщо шляху між вершинами не існує. """ sources = {start: -1} distances = [inf for _ in range(n)] distances[start] = 0 pq = PriorityQueue() pq.insert(start, 0) while not pq.empty(): i = pq.extractMinimum() if i == end: break for j in graph[i]: if distances[i] + graph[i][j] < distances[j]: distances[j] = distances[i] + graph[i][j] sources[j] = i if j in pq: pq.updatePriority(j, distances[j]) else: pq.insert(j, distances[j]) if distances[end] == inf: return [] path = [end] while end != start: end = sources[end] path.append(end) path.reverse() return path
def test_dict(self): '''Push a dictionary''' pq = PriorityQueue() d = {'a':10, 'b':4} pq.push(0, d) self.assertEqual(pq.pop()[1], d)
def gready_search_algorithm(self, initial_state): start_node = Node(initial_state, None, None, 0, initial_state.index(0)) if start_node.goal_test().all(): return start_node.find_solution() frontier = PriorityQueue() ## List queue frontier.push(start_node, frontier.h(start_node.state, start_node.goal_state())) explored = set() ## Needs changing, change to set(). star = "**********************************" print("\nInitial State ---------- Depth: {0}".format(start_node.depth)) while not (frontier.is_empty()): v = frontier.pop() node = v[-1] print("--------------------------------------------------") if node.goal_test().all(): print("***************GOAL STATE FOUND*******************") print("\n") print(node.display()) return node.find_solution() print("Depth = {0} \n".format(node.depth)) print("{0}".format(node.display())) print(star) explored.add(tuple(node.state)) children = node.generate_child() for child in children: if tuple(child.state) not in explored: frontier.push(child, frontier.h(child.state, child.goal_state())) return
def singleTaskAssignment(self, task: Task, employeeList: [], maxCapacity=1000): availableEmployee = employeeList PQ = PriorityQueue([]) it = 0 for employee in availableEmployee: matchDept = self.compareList(employee.department, task.department) matchSkill = self.compareList(employee.skillSet, task.skillSet) if employee.capacity >= maxCapacity or matchDept == 0 or matchSkill == 0: continue evaluation = self.evaluation(matchDept, matchSkill, maxCapacity - employee.capacity) PQ.add((-evaluation, it, employee)) it = it + 1 assignedEmployee = [] for i in range(min(len(availableEmployee), task.assignedNeeded)): employee = PQ.pop() assignedEmployee.append(employee) return assignedEmployee
def test_in_fucntionality(self): pq = PriorityQueue() assert 1 not in pq pq.enqueue(1) assert 1 in pq assert 2 not in pq
def test_uselist(self): '''Push a list onto queue and them remove it''' pq = PriorityQueue() l = [] pq.push(0,range(0, 10)) self.assertEqual(pq.pop()[1], range(0, 10))
def a_star_search_visualize(app, grid, start, goal): frontier = PriorityQueue() frontier.add(start, 0) came_from = {} g_score = {start: 0} f_score = {start: heuristic(start, goal)} while not frontier.is_empty(): current = frontier.pop() if current == goal: return reconstruct_path(came_from, current) for neighbour in grid.neighbours(current): tentative_g_score = g_score[current] + grid.distance(current, neighbour) if neighbour not in g_score or tentative_g_score < g_score[neighbour]: came_from[neighbour] = current g_score[neighbour] = tentative_g_score f_score[neighbour] = tentative_g_score + heuristic(neighbour, goal) if not frontier.exist(neighbour): frontier.add(neighbour, f_score[neighbour]) for item in frontier.get_queue(): if item != goal and app.grid.get_color(item) != BLUE: app.grid.set_color(item, SKY_BLUE) if current != start: app.grid.set_color(current, BLUE) app.draw_graph(FAST) return []
def __init__(self, initialpuzzle): initialtime = time.time() explored = [] # explored nodes,expanded and open node1 = node.Node(0, 0, initialpuzzle, 0) node1.puzzle.printPuzzle() self.heuristic1(node1.puzzle) print self.heuristic1(node1.puzzle) priorityQueue = PriorityQueue() priorityQueue.push(node1.puzzle, self.heuristic1(node1.puzzle) + node1.puzzle.depth) print priorityQueue.isEmpty() while not priorityQueue.isEmpty(): k = priorityQueue.pop() #k.printPuzzle() if k.checkPuzzle(): print "corect" print str(time.time() - initialtime) break else: for move in k.moves: aux = copy.deepcopy(k) #this is a copy of our puzzle aux.doMove(move) aux.depth += 1 #aux.printPuzzle() priorityQueue.push(aux, self.heuristic1(aux))
def Astar(start, goal, C, im): """Input: Start state, Goal State, Cost map and original map Output: Bool value False after completion of the algorithm This function performs the A-Star algorithm to find the shortest path to the goal """ openSet = PriorityQueue() openSet.put(start, 0) openSet_check = {} openSet_check[start] = 1 closedSet = {} plan = {} g = {} g[start] = 0 f = {} j = 0 f[start] = get_heuristic(start, goal) p = 0 while not openSet.empty(): currentState, fpop = openSet.get() if currentState == goal: print "Path found!" path = reconstruct_path(plan, currentState) path.reverse() get_totalCost(path, C) visualize(path, C, im) #for i in range(len(path)): # print path[i] break closedSet[currentState] = 1 for nextState in get_successors(currentState): j = j + 1 if nextState in closedSet: continue newCost = g[currentState] + get_cost(C, nextState) if nextState not in openSet_check: plan[nextState] = currentState g[nextState] = newCost f[nextState] = g[(nextState)] + get_heuristic( currentState, nextState) openSet.put(nextState, f[nextState]) openSet_check[nextState] = 1 continue elif newCost >= g[nextState]: openSet_check[nextState] = 1 continue plan[nextState] = currentState g[nextState] = newCost f[nextState] = g[(nextState)] + get_heuristic( currentState, nextState) openSet.put(nextState, f[nextState]) openSet_check[nextState] = 1 return False
def test_pushpop(self): '''Push items onto queue and then remove them''' pq = PriorityQueue() for i in range(0, 10): pq.push(0,i) for i in range(0, 10): self.assertEqual(pq.pop()[1], i)
def run(self, gridMap, defStartNode=None, defEndNode=None, distanceType=PFA.DIS_TYPE_MANHATTAN): if not gridMap: return (PFA.RSLT_GRIDMAP_ERR,) startNode = defStartNode if not startNode: startNode = gridMap.getStartGridNode() if not startNode: return (PFA.RSLT_NO_START_NODE,) endNode = defEndNode if not endNode: endNode = gridMap.getEndGridNode() if not endNode: return (PFA.RSLT_NO_END_NODE,) hdis = self.getDistance(startNode, endNode, distanceType) if hdis < 0: return (PFA.RSLT_DIS_INVALID,) self.gridMap = gridMap self.initPathMap(gridMap, distanceType) openSet = PQ() startPathNode = self.pMap[startNode.x][startNode.y] openSet.push(startPathNode) endPathNode = self.pMap[endNode.x][endNode.y] ret = (PFA.RSLT_NONE,) jumpPoint = [] while not openSet.isEmpty() and ret[0] == PFA.RSLT_NONE: currNode = openSet.pop() jumpPoint.append(currNode) currNode.isInClose = True currGridNode = currNode.gridNode if gridMap.isEndGridNode(currGridNode.x, currGridNode.y): ret = (PFA.RSLT_OK, self.genValidPath(gridMap), self.genAllVisNodeSet(gridMap), jumpPoint) break for i in range(len(self.visMap)): for j in range(len(self.visMap[i])): self.visMap[i][j] = False for dv in PFA.DIR_VECTOR: if not self.isOkPos(currGridNode, dv): continue jumpNode = self.findJumpNode(currNode, currNode, self.getPathNode(currGridNode, dv), openSet) if jumpNode: self.updateJumpNode(currNode, jumpNode, openSet) return ret
def __init__(self, queue, randoms): self.queues = {} self.event_queue = PriorityQueue() self.clg = clg() self.output = OutputHandler(queue) self.randoms = randoms self.time = 0. self.loss = 0 self.randoms_used = 0
def pg_srot(C): n = len(C) P = PriorityQueue() for j in range(n): element = C.delete(C.first()) P.add(element, element) for j in range(n): (k, v) = P.remove_min() C.add_last(v)
class PriorityEdgeList: def __init__(self): self.edges = [] self.priorityEdges = PriorityQueue() self.empty = True def InsertEdge(self, y, w): self.priorityEdges.add_task(y, w) self.edges.append(Graphs.Edge(y, w)) self.empty = False
class PriorityEdgeList: def __init__(self): self.edges = [] self.priorityEdges = PriorityQueue() self.empty = True def InsertEdge(self, y, w): self.priorityEdges.add_task(y, w) self.edges.append( Graphs.Edge(y,w)) self.empty = False
def findPath(self, s, t): # finds the maximum capacity path from s -> t in G PQ = PriorityQueue() for node in self.G.nodes(): PQ.add(node, 0) self.label[node] = 0 # increase the priority of source to infinity PQ.add(s, -float('inf')) self.label[s] = float('inf') while PQ.entry_finder: v = PQ.pop() for w in self.G.out_adj(v): if min(self.label[v], self.G.get_edge_weight( (v, w))) > self.label[w]: self.label[w] = min(self.label[v], self.G.get_edge_weight((v, w))) PQ.add(w, -self.label[w]) self.edgeTo[w] = v self.printMaxCapacityPath(s, t) print("The capacity of the maximum capacity path is %d" % self.label[t])
def findShortestPathwithFewestHops(self): # returns the shortest path with the fewest hops; 2 shortest paths of equal length # can differ in the number of hops. hops = {} PQ = PriorityQueue() for node in self.G.nodes(): # add all nodes to the priority queue with infinite priority PQ.add(node, float('inf')) self.label[node] = float('inf') hops[node] = float('inf') # reduce source priority to zero PQ.add(self.s, 0) self.label[self.s] = 0 hops[self.s] = 0 while PQ.entry_finder: v = PQ.pop() # gets the entry with the least priority for w in self.G.out_adj(v): edge_weight = self.G.get_edge_weight((v,w)) if self.label[w] > self.label[v] + edge_weight or \ self.label[w] == self.label[v] + edge_weight and hops[w] > hops[v] + 1: self.label[w] = self.label[v] + edge_weight PQ.add(w, self.label[w]) self.edgeTo[w] = v hops[w] = hops[v] + 1
def get_char_freq(file_name): """ gets the sorted list of character frequencies :param file_name: the file to parse through :type file_name: str :return: the huffman tree and char count """ char_frequency = {} with open(file_name) as to_encode: cur_char = to_encode.read(1) while cur_char: if char_frequency.has_key(cur_char): char_frequency[cur_char] += 1 else: char_frequency[cur_char] = 1 cur_char = to_encode.read(1) # create the huffman list of nodes sorted by count nodes = PriorityQueue() # adds the initial nodes to the list for node_char, node_freq in char_frequency.iteritems(): nodes.put(h_node(None, None, node_freq, node_char), node_freq) # create the tree of nodes required to get the character codes while nodes.count() > 1: # get the two smallest nodes h_node_a = nodes.get() h_node_b = nodes.get() freq_sum = h_node_a.frequency + h_node_b.frequency nodes.put(h_node(h_node_a, h_node_b, freq_sum, None), freq_sum) return nodes.get()
def dijkstra(graph, source): '''Apply the Dijkstra algorithm and return the a list where each position represents a vertice and its content represents the predecessor''' vertices = [] #list of vertices Q = PriorityQueue() #priority queue #fills 'vertices' and 'Q', each vertex receive the distance iquals infinity for v in range(len(graph)): vertices.append(Vertex(v)) Q.add_with_priority(v, vertices[v].dist) #the source vertex receive the distance zero vertices[source] = Vertex(num=source, dist=0) Q.decrease_priority(source, 0) while len(Q) != 0: u = Q.extract_min() for neighbor in get_adjacent(graph, u.num): alt = graph[u.num][neighbor] + u.dist Alt = Vertex(neighbor, alt) if vertices[neighbor].greater_than(Alt): vertices[neighbor].dist = alt vertices[neighbor].prev = u.num Q.decrease_priority(neighbor, alt) return [v.prev for v in vertices]
def primsAlgorithm(graph, start, surface): for v in graph: v.setStatus(0) v.setParent(None) pq = PriorityQueue() #heapq.heappush(pq, (0, start)) pq.enQueue((0, start)) while (not pq.isEmpty()): current = pq.deQueue()[1] current.setStatus(2) if(current.getParent() != None): graph.drawEdge(current.getParent(), current, surface, "yellow") time.sleep(0.5) #print(str(current.getParent().getId()) + "->" + str(current.getId())) for neighbour in current.getNeighbours(): if (neighbour.getStatus() == 0): neighbour.setStatus(1) neighbour.setParent(current) neighbour.setpqWeight(current.neighbours[neighbour]) #print(str(neighbour.getpqWeight())) pq.enQueue((neighbour.getpqWeight(), neighbour)) elif (neighbour.getStatus() == 1): if (neighbour.getpqWeight() > current.neighbours[neighbour]): old = (neighbour.getpqWeight(), neighbour) neighbour.setpqWeight(current.neighbours[neighbour]) pq.updatePriority(old, (neighbour.getpqWeight(), neighbour)) neighbour.setParent(current) """
def dijkstras(self, source, destination): priorityQueue = PriorityQueue() source.setDistance(0) unvisitedQueue = [(self.vertices[v].getDistance(), self.vertices[v].getId()) for v in self.vertices if self.verticesStatus[v] == "UP"] priorityQueue.buildPQ(unvisitedQueue) while len(priorityQueue) - 1: closestVertex = priorityQueue.deleteMinimum() closestVertex = self.getVertex(closestVertex[1]) closestVertex.setVisited() for nextVertex in closestVertex.adjacent: #checking if both the vertex and the edge are UP if self.verticesStatus[ nextVertex] == "UP" and closestVertex.adjacent[ nextVertex][1] == "UP": nextVertex = self.getVertex(nextVertex) if nextVertex.visited: continue newDistance = closestVertex.getDistance() + float( closestVertex.getWeight( nextVertex.id)) #update distance if newDistance < nextVertex.getDistance(): nextVertex.setDistance(newDistance) #update distance nextVertex.setPrevious(closestVertex) while len(priorityQueue) - 1: priorityQueue.deleteMinimum() unvisitedQueue = [(self.vertices[v].getDistance(), self.vertices[v].getId()) for v in self.vertices if not self.vertices[v].visited] priorityQueue.buildPQ(unvisitedQueue)
def prims(self, graph, start, canvas): for v in graph: v.setStatus(0) v.setParent(None) pq = PriorityQueue() pq.enQueue((0, start)) while (not pq.isEmpty()): current = pq.deQueue()[1] current.setStatus(2) if(current.getParent() != None): graph.drawEdge(current.getParent(), current, canvas, "yellow") canvas.update() time.sleep(0.5) for neighbour in current.getNeighbours(): if (neighbour.getStatus() == 0): # Encountered a new vertex neighbour.setStatus(1) neighbour.setParent(current) neighbour.setpqWeight(current.neighbours[neighbour]) pq.enQueue((neighbour.getpqWeight(), neighbour)) elif (neighbour.getStatus() == 1): if (neighbour.getpqWeight() > current.neighbours[neighbour]): # Found smaller weight, update accordingly old = (neighbour.getpqWeight(), neighbour) neighbour.setpqWeight(current.neighbours[neighbour]) pq.updatePriority(old, (neighbour.getpqWeight(), neighbour)) neighbour.setParent(current)
def algorithm_Prim(self, start_position): priority_queue = PriorityQueue(self.size) self.visited = [False] * (self.size + 1) self.visited[start_position] = True self.insert_to_priority_queue_from(start_position, priority_queue) while self.visited.count(True) < len(self.nodes): target = priority_queue.get() self.visited_history.append((target[1], target[0])) position = target[0] self.visited[position] = True self.insert_to_priority_queue_from(position, priority_queue) self.__show_graph__()
def test_neg_priority(self): '''Negative priorities''' pq = PriorityQueue() for i in range(-5, 5): pq.push(i,i) for i in range(-5, 5): pri, item = pq.pop() # Priorities match self.assertEqual(pri, i) # Values match self.assertEqual(item, i)
def test_priority(self): '''Test the priority portion of the priority queue''' pq = PriorityQueue() for i in range(0, 10): pq.push(i,i) for i in range(0, 10): pri, item = pq.pop() # Priorities match self.assertEqual(pri, i) # Values match self.assertEqual(item, i)
def alternateRoute(self, num, optimal_path): '''To obtain a ranked list of less-than-optimal solutions, the optimal solution must first calculated. This optimal solution is passed in as ``optimal_path``. A single edge appearing in the optimal solution is removed from the graph, and the optimum solution to this new graph is calculated. Each edge of the original solution is suppressed in turn and a new shortest-path calculated. The secondary solutions are then ranked and the ``num`` best sub-optimal solutions are returned. If less than ``num`` solutions exist for the given graph, less than ``num`` solutions will be returned. The results are a list of tuples of form: ``((cost, path), (cost2, path2), ...)`` An example of finding alternate routes:: search = Pathfinding() # find optimal route optimal_path = search.shortestPath("A", "E") # returns ["A", "C", "E"] cost = search.pathCost(optimal_path) # returns 3 alt_paths = search.alternateRoute(2, optimal_path) # returns ((4, ["A", "B", "D", "E"]), (4, ["A", "B", "F", "E"])) ''' # Store the paths by their weights in a priority queue. The paths with # the lowest cost will move to the top. At the end, pop() the queue # once for each desired alternative. minheap = PriorityQueue() start, goal = optimal_path[0], optimal_path[-1] # Don't remove the start or goal nodes for i in range(1, len(optimal_path) - 1): y = optimal_path[i] log.info("Look for sub-optimal solution with vertex {} removed".\ format(y)) path = self.shortestPath(start, goal, [y]) #path = self.shortestPath(start, goal) cost = self.pathCost(path) log.debug("Cost of path with vertex %s removed is %g" \ % (y, cost)) minheap.push(cost, path) alternatives = [] for i in range(0, min(num, len(minheap))): cost, path = minheap.pop() alternatives.append((cost,path)) log.debug("Cost of #%d sub-optimal path is %g" % (i+1, cost)) return alternatives
def test_lambda_function_enqueue(self): pq = PriorityQueue(min, lambda x: 2 * x) pq.enqueue(1) assert pq.items[0][0] == 2 pq.enqueue(2) assert pq.items[0][0] == 4 assert pq.items[1][0] == 2 npq = PriorityQueue(min, lambda x: -x) npq.enqueue(1) npq.enqueue(2) assert npq.items[0][0] == -1 assert npq.items[1][0] == -2
class PriorityQueueTest(unittest.TestCase): def setUp(self): self.p_queue = PriorityQueue() def test(self): elements = [] for i in range(1000): x = random() elements.append(x) self.p_queue.insert(x) elements.sort(reverse=True) for elem in elements: self.assertEqual(elem, self.p_queue.pop())
def __init__(self): # Initial Constructor of the Scheduler. self.lines = open('processes.txt', 'r').readlines() self.ready = PriorityQueue() self.all = [] self.i = 0 self.finished = 0 self.program_counter = 0 self.load_time = [] self.load_var = 0 self.averageT = 0 self.averageW = 0 self.throughput = 0
def Astar(start, goal, C): openSet = PriorityQueue() openSet.put(start, 0) openSet_check = {} openSet_check[start] = 1 closedSet = {} plan = {} g = {} g[start] = 0 f = {} j = 0 f[start] = get_heuristic(start) p = 0 while not openSet.empty(): currentState, fpop = openSet.get() if currentState in goal: path = reconstruct_path(plan, currentState) path.reverse() get_totalCost(path, C) visualize(path, C) for i in range(len(path)): print path[i] break closedSet[currentState] = 1 for nextState in get_successors(currentState): j = j + 1 if nextState in closedSet: continue newCost = g[currentState] + get_cost(C, nextState) if nextState not in openSet_check: plan[nextState] = currentState g[nextState] = newCost f[nextState] = g[(nextState)] + get_heuristic(nextState) openSet.put(nextState, f[nextState]) openSet_check[nextState] = 1 continue elif newCost >= g[nextState]: openSet_check[nextState] = 1 continue plan[nextState] = currentState g[nextState] = newCost f[nextState] = g[(nextState)] + get_heuristic(nextState) openSet.put(nextState, f[nextState]) openSet_check[nextState] = 1 return False
def dijkstra(start, C): """Input: Start state and Cost map Output: The cost of each cell as a dictionary This function performs the Dijkstra algorithm to find the cost of each cell in the map """ openSet = PriorityQueue() openSet_check = {} closedSet = {} g = {} for i in range(len(start)): g[start[i]] = 0 openSet.put(start[i], 0) openSet_check[start[i]] = 1 while not openSet.empty(): currentState = openSet.get() closedSet[currentState] = 1 for nextState in get_successors(currentState): if nextState in closedSet: continue newCost = g[currentState[0]] + get_cost(nextState) if nextState not in openSet_check: g[nextState] = newCost openSet.put(nextState, g[nextState]) openSet_check[nextState] = 1 continue elif newCost >= g[nextState]: continue g[nextState] = newCost openSet.put(nextState, g[nextState]) openSet_check[nextState] = 1 # This writes the cost values onto a file which is accessed by the A-star algorithm # for the planning part f = open('heuristic.txt', 'w') temp = '' for i in range(M): temp = '' for j in range(N): if j == 0: temp += str(g[(i, j)]) else: temp += ',' + str(g[(i, j)]) if i == 0: f.write(temp) else: f.write('\n' + temp) f.close() return g
def computepaths(station, network): paths = [] station.durations = [float('inf') for _ in network.shapes] for i in range(len(network.shapes)): if network.shapes[i] == station.shape: station.durations[i] = 0 G = network.graph start = station.idt n = len(network.stations) p = len(network.lines) spanningForest = [None for _ in range(n * p)] dejaVu = [False for _ in range(n * p)] U = PriorityQueue(len(G)) closer = [None for _ in network.shapes] for i in range(p): U.push(start + n * i, 0) while U.length() != 0 and len([x for x in closer if x is None]) != 0: (u, k) = U.pop() if dejaVu[u]: continue else: for i in range(len(network.shapes)): if closer[i] is None and network.stations[u % n].shape == network.shapes[i]: closer[i] = u dejaVu[u] = True for (v, w) in G[u]: if - U.priority(v) > - k + w: U.changePrio(v, k - w) spanningForest[v] = u for i in range(len(network.shapes)): route = [] goal = closer[i] if not goal is None: station.durations[i] = - U.priority(goal) while goal is not None and goal % n != station.idt and len(route) < n: route.append((goal // n, goal % n)) goal = spanningForest[goal] paths.append(route) return paths
def search(self, start, end): frontier = PriorityQueue() frontier.put(0, start) cost_so_far = dict() cost_so_far[start] = 0 came_from = dict() came_from[start] = None while not frontier.is_empty(): pri, current = frontier.get() if current == end: self.paths[start].update(self.reconstruct_path(end, came_from)) break neighbors = [ neighbor.end for neighbor in self.graph.neighbors(current) ] for neighbor in neighbors: new_cost = cost_so_far[current] + self.graph.cost( current, neighbor) if neighbor not in cost_so_far.keys( ) or new_cost < cost_so_far[neighbor]: cost_so_far[neighbor] = new_cost came_from[neighbor] = current frontier.put(new_cost, neighbor)
def Prim(G, w, s): inf = float("inf") H = PriorityQueue() T = [] s.priorite = 0 H.add_task(s, 0) i = 1 for u in G.sommets: u.pred = None if u != s : H.add_task(u, inf) u.priorite = inf try: while True: u = H.pop_task() u.couleur = "noir" if u.priorite != inf: if u.pred is not None: T.append((u.pred, u)) for v in u.voisins: if v.couleur == "blanc": #v n'est pas sorti du tas if w[(u, v)] < v.priorite: v.priorite = w[(u, v)] H.add_task(v, v.priorite) v.pred = u except: pass return T
def dijkstra_search(graph, start, goal): frontier = PriorityQueue() frontier.put(start, 0) # different from first implementation in that it remembers # WHERE we came from, not just that we visited it came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): # from front of the queue current = frontier.get() # print("Visiting ", current) # main difference from implementation 2 if current == goal: break # get neighbors of current node # add it to back of frontier queue if not yet visited for next in graph.neighbors(current): new_cost = cost_so_far[current] + graph.cost(current, next) if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost frontier.put(next, priority) came_from[next] = current return came_from, cost_so_far
def a_star(self): # Genera camino usando el algoritmo A* frontier = PriorityQueue() frontier.put(self.start, 0) came_from = {} cost_so_far = {} came_from[self.start] = None cost_so_far[self.start] = 0 # comienza la busqueda while not frontier.empty(): current = frontier.get() # termina si llega a la meta if current == self.goal: break # busca en sus vecinos for next in self.graph.neighbors(current): new_cost = cost_so_far[current] + self.graph.cost( current, next) if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost + self.cost(self.posiciones[self.goal], self.posiciones[next]) frontier.put(next, priority) came_from[next] = current # ordena el plan current = self.goal path = [current] while current != self.start: current = came_from[current] path.append(current) # invierte el camino para empezar al inicio path.reverse() self.plan = path
def a_star_search(self, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start.get_key()] = None cost_so_far[start.get_key()] = 0 while not frontier.empty(): current = frontier.get() if current == goal: break for point in self.graph.neighbors(current): move_cost = self.graph.cost(current, point) new_cost = cost_so_far[current.get_key()] + move_cost if point is None: continue if point.get_key( ) not in cost_so_far or new_cost < cost_so_far[ point.get_key()]: cost_so_far[point.get_key()] = new_cost priority = new_cost + self.heuristic(goal, point) frontier.put(point, priority) came_from[point.get_key()] = current #return came_from, cost_so_far return came_from
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]
def FindDirections(self, curState): pq = PriorityQueue(["dist", "changeDir"]) pq.add({"state": curState, "prev": None, "dist": 0 + self.heuristics(curState), "changeDir": 0, "step": 0}) cnt = 0 while True: elem = pq.pop() #print("Dir:", elem["state"].snake.curDir, "step:", elem["step"], "cnt: ", cnt) ok_dirs = self._get_ok_dirs_(elem["state"]) #print ok_dirs for d in ok_dirs: nextState = elem["state"].GetNextState(d) step = elem["step"] + 1 changeDir = 0 if d != elem["state"].snake.curDir: changeDir = 1 dist = step + self.heuristics(nextState) pq.add({"state": nextState, "prev": elem, "dist": dist, "changeDir":changeDir, "step": step} ) #if elem["step"] % 10 == 0: # print elem["step"] if pq.IsEmpty(): print "EMPTY!!!!", elem["step"] if len(pq.storage) > 0: elem = pq.storage.pop(0) pq.add(elem) """ while len(pq.storage) > 0: other = pq.storage.pop() print other["step"], elem["step"] if abs(other["step"] - elem["step"]) < elem["step"] * 0.1: break """ print elem["state"].IsAppleEaten(), elem["state"].apple.GetApplePos() #pq.add(other) cnt += 1 if cnt >= 2000 or self._is_goal(elem["state"]) and elem["step"] > 0: #print("step:", elem["step"], "cnt:", cnt, "empty:", pq.IsEmpty()) pq.clean() while True: self.directions.append(elem["state"].snake.curDir) elem = elem["prev"] if elem is None: break self.directions.pop() # remove the first direction (the state that already take a step) return self.directions
def FindDirections(self, curState): self.directions = [] pq = PriorityQueue(["dist"]) maxDepth = 5 pq.add({"state": curState, "dist": self.heuristics(curState), "step": 0, "prev": None}) cnt = 0 while not pq.IsEmpty(): elem = pq.pop() state = elem["state"] stack = [] stack.append({"state": state, "step": 0, "prev": elem["prev"]}) """ if cnt >= SCREEN_WITH + SCREEN_HEIGHT - 4 * SNAKE_WITH_HALH - 2: print "size of queue: ", len(pq.queue) cnt = 0 """ """ maxSize = max(len(pq.queue) / 2, len(pq.queue) - randint(10, 20)) reduceSize = min(maxSize, len(pq.queue) - 5) for i in range(reduceSize): pq.pop() """ if len(pq.queue) > 700: # TODO: if we cannnot find solution for so long a time, the size of queue should # be reduced to a pretty small number for i in range(randint(0,len(pq.queue)-1)): pq.pop() #print "size of queue: ", len(pq.queue) #print curState.snake.body #print curState.snake.GetBodyRects() continue while len(stack) > 0: el = stack.pop() stat = el["state"] if el["step"] >= maxDepth: pq.add({"state": stat, "dist": self.heuristics(stat), "step": el["step"], "prev": el["prev"]}) continue if stat.IsAppleEaten(): # guess if the snake can be dead by instinct stat.AddSnakeLen() if self._is_possible_dead_(stat): continue while el is not None: self.directions.append(el["state"].snake.curDir) el = el["prev"] self.directions.pop() return ok_dirs = self._arange_dirs_(stat, self._get_ok_dirs_(stat)) for d in ok_dirs: nextStat = stat.GetNextState(d) nextEl = {"state": nextStat, "step": el["step"]+1, "prev": el} stack.append(nextEl) self.directions.append(Direction.Stop)
def lowerBoundImprovementReversed(source, target) : """ Evolution of the normal label-setting algorithm, with a preprocessing that uses Dijkstra bicriteria algorithm @return number of loops """ visitedNodes = __dijkstraBiCrit(target, source, 0) # safest path bestDanger = source.danger for v in visitedNodes: v.resetValue(True) __dijkstraBiCrit(target, source, 1) # shortest path bestDistance = source.distance labelQueue = PriorityQueue() sourceLabel = (0, 0, source, None, 0, None) source.labelList.append(sourceLabel) labelQueue.put(sourceLabel, sourceLabel[0]) ending = False counter = 0 while not labelQueue.isEmpty() : actualLabel = labelQueue.getMin() distSoFar = actualLabel[0] dangSoFar = actualLabel[1] actualNode = actualLabel[2] parentIndex = actualLabel[4] for nearNode, weight in actualNode.neighbors : distance, danger = weight ownIndex = len(nearNode.labelList) newLabel = (distSoFar + distance, dangSoFar + danger, nearNode, actualNode, ownIndex, parentIndex) # creating of a new label useLabel = True if nearNode.bestLabel[0] is not None and nearNode.bestLabel[1] is not None : # if the best label is present, enter checkDistance = newLabel[0] + nearNode.bestLabel[0] checkDanger = newLabel[1] + nearNode.bestLabel[1] if checkDanger >= bestDanger and checkDistance >= bestDistance : # if the values are negative is useless to check continue #checkLabel = (newLabel[0] + checkDistance, newLabel[1] + checkDanger) else : checkLabel = newLabel else : checkLabel = newLabel if ending : if isDominated(checkLabel, target.labelList) : # if the newlabel + bestLabel is dominated is useless go on continue # restart 'for' loop with another nearNode for label in nearNode.labelList : if isDominated(newLabel, [label]) : useLabel = False break # if a value is useless (1st case) the loop - label in labelList - is interrupt, to jump some loops if useLabel : nearNode.labelList.append(newLabel) if nearNode != target : labelQueue.put(newLabel, newLabel[0]) else : ending = True counter += 1 return counter
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
def a_star_search(graph, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() if current == goal: break for next in graph.neighbors(current): new_cost = cost_so_far[current] + graph.cost(current, next) if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost + heuristic( goal, next ) # reduce priority for positions further away from goal frontier.put(next, priority) came_from[next] = current return came_from, cost_so_far
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()
def dijkstrasAlgorithm(graph, start): for v in graph: v.setStatus(0) #start.setStatus(2) start.setDistance(0) pq = PriorityQueue() #heapq.heappush(pq, (0, start)) pq.enQueue((0, start)) while (not pq.isEmpty()): current = pq.deQueue()[1] current.setStatus(2) #if(current.getParent() != None): # print(str(current.getParent().getId()) + "->" + str(current.getId())) for neighbour in current.getNeighbours(): if (neighbour.getStatus() == 0): neighbour.setStatus(1) neighbour.setParent(current) neighbour.setpqWeight(current.neighbours[neighbour]) neighbour.setDistance(current.getDistance() + current.neighbours[neighbour]) pq.enQueue((neighbour.getpqWeight(), neighbour)) elif (neighbour.getStatus() == 1): if (neighbour.getDistance()) > (current.getDistance() + current.neighbours[neighbour]): #old = (neighbour.getpqWeight(), neighbour) #neighbour.setpqWeight(current.neighbours[neighbour]) #pq.updatePriority(old, (neighbour.getpqWeight(), neighbour)) neighbour.setParent(current) neighbour.setDistance(current.getDistance() + current.neighbours[neighbour])
def a_star_search(self, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = start cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() if current.position_x == goal.position_x and current.position_y == goal.position_y: break for next in self.neighbors(current): next_cell = Cell(next[0], next[1]) if next_cell.position_x == goal.position_x and next_cell.position_y == goal.position_y: next_cell = goal new_cost = cost_so_far[current] + self.heuristic(current, next_cell) if next_cell not in cost_so_far or new_cost < cost_so_far[next_cell]: cost_so_far[next_cell] = new_cost priority = new_cost + self.heuristic(goal, next_cell) frontier.put(next_cell, priority) came_from[next_cell] = current return came_from # , cost_so_far
def search(self, startHex, goalHex): startNode = HexNode(startHex, None) goalNode = HexNode(goalHex, None) frontier = PriorityQueue() frontier.put(startNode, 0) cameFrom = {} currCost = {} cameFrom[startNode] = None currCost[startNode] = 0 while not frontier.empty(): currNode = frontier.get() if currNode.h == goalNode.h: break for nextNode in self.getNeighborNodes(currNode.h): newCost = currCost[currNode] + self.cost(currNode, nextNode) if nextNode not in currCost or newCost < currCost[nextNode]: currCost[nextNode] = newCost priority = newCost + HexMap.heuristic(goalNode, nextNode) frontier.put(nextNode, priority) cameFrom[nextNode] = currNode return cameFrom, currCost
def replan(self, location, heading): """ :type location: Position :param location: The current location of the robot :type heading: Direction :param heading: The current direction the robot is pointing """ open_nodes = PriorityQueue(lifo=False) closed_nodes = set() came_from = {} # The key is the end state, the value is a tuple of g, move, and start state initial_state = (location, heading) g = 0 h = self.heuristic.get_value(initial_state) f = g + h open_nodes.insert(f, initial_state) came_from[initial_state] = (g, None, None) current_state = initial_state while len(open_nodes) > 0: while current_state in closed_nodes: current_state = open_nodes.pop_min() closed_nodes.add(current_state) if self.heuristic.get_value(current_state) == 0: pol = self.create_policy(current_state, initial_state, came_from) return self.policy moves = self.get_possible_moves(current_state) for move in moves: new_state = self.get_move_result(current_state, move) if new_state in closed_nodes: continue g = came_from[current_state][0] + self.get_cost(move) h = self.heuristic.get_value(new_state) f = g + h if new_state not in open_nodes: open_nodes.insert(f, new_state) elif new_state in came_from and f >= open_nodes.get_priority(new_state): continue came_from[new_state] = (g, move, current_state) open_nodes.update_priority(new_state,f) return "No path to goal!"
def dijkstra(aGraph,start): pq = PriorityQueue() start.setDistance(0) pq.buildHeap([(v.getDistance(),v) for v in aGraph]) while not pq.isEmpty(): currentVert = pq.delMin() for nextVert in currentVert.getConnections(): newDist = currentVert.getDistance() + currentVert.getWeight(nextVert) if newDist < nextVert.getDistance(): nextVert.getDistance( newDist ) nextVert.setPred(currentVert) pq.decreaseKey(nextVert,newdist)
def dijkstraBi(self, start, goal, exceptions=None): '''Bi-Directional Dijkstra's algorithm. The search begins at the ``start`` node and at the ``goal`` node simultaneously. The search area expands radially outward from both ends until the two meet in the middle. In most cases this reduces the number of vertices which must be checked by half. .. image:: dijkstra.png .. image:: dijkstra-bidirectional.png Search area of Dijkstra's algorithm (left) vs search area of bi-directional Dijkstra's algorithm (right). .. seealso:: :func:`aStarPath`, :func:`dijkstra` ''' dist_f = {} # dictionary of final distances dist_b = {} # dictionary of final distances came_from_f = {} # dictionary of predecessors came_from_b = {} # dictionary of predecessors # nodes not yet found forward = PriorityQueue() backward = PriorityQueue() # The set of nodes already evaluated closedset_forward = [] closedset_backward = [] forward.push(0, start) backward.push(0, goal) while len(forward) + len(backward) > 0: if len(forward) > 0: done, stop = self.__dijkstraBiIter(start, goal, exceptions, dist_f, came_from_f, forward, closedset_forward, closedset_backward) if not done and len(backward) > 0: done, stop = self.__dijkstraBiIter(goal, start, exceptions, dist_b, came_from_b, backward, closedset_backward, closedset_forward) if done: #log.debug("came_from_f: " + str(came_from_f)) #log.debug("came_from_b: " + str(came_from_b)) pathf = self.reconstructPath(came_from_f, stop) #log.info("PathF: %s" % pathf) pathb = self.reconstructPath(came_from_b, stop) pathb.reverse() #log.info("PathB: %s" % pathb) return pathf + pathb[1:] return None
def fast_marching_method(graph,start): h = 1 def calculus_distance(node,graph,weights): neighbours = graph.get_neighbours(node); if 'y-1' in neighbours : if 'y+1' in neighbours: x1 = min(weights[neighbours['y-1']],weights[neighbours['y+1']]); else : x1 = weights[neighbours['y-1']]; else : if 'y+1' in neighbours: x1 = weights[neighbours['y+1']]; if 'x-1' in neighbours: if 'x+1' in neighbours: x2 = min(weights[neighbours['x-1']],weights[neighbours['x+1']]); else : x2 = weights[neighbours['x-1']]; else : if 'x+1' in neighbours: x2 = weights[neighbours['x+1']]; if 2*h**2-(x1-x2)**2>=0: return (x1+x2+(2*h**2-(x1-x2)**2)**0.5)/2 else: return min(x1,x2)+h frontier = PriorityQueue(); weights = graph.distances; explored = [] goals = numpy.where(graph.indicator_map==2) goals_x = goals[0] goals_y = goals[1] for i in range(goals_x.size): frontier.append([0,(goals_x[i],goals_y[i])]) weights[(goals_x[i],goals_y[i])] = 0 while frontier: node = frontier.pop(); explored.append(node[1]) #if node[1]==start: # return weights neighbours = graph.get_neighbours(node[1]); for neighbour in neighbours.itervalues(): if neighbour not in explored and graph.indicator_map[neighbour]: if not neighbour in frontier: frontier.append([calculus_distance(neighbour,graph,weights),neighbour]) weights[neighbour]=calculus_distance(neighbour,graph,weights) elif weights[neighbour] > calculus_distance(neighbour,graph,weights): frontier[neighbour][0]=calculus_distance(neighbour,graph,weights) weights[neighbour]=calculus_distance(neighbour,graph,weights) graph.distances = weights
def __init__(self, abilities, players): self.gm = players[0] self.errorAbility = ErrorAbility() self.eventQueue = PriorityQueue() self.parser = Parser() self.inbox = Inbox() self.outbox = Outbox() self.players = {} for player in players[1:]: self.players[player.getName().lower()] = player self.abilities = {} for ability in abilities: self.abilities[ability.getName().lower()] = ability
def dijkstra(self, G, start, end=None): D = {} # dictionary of final distances P = {} # dictionary of predecessors Q = PriorityQueue() # estimated distances of non-final vertices Q[start] = 0 # add zero cost for v in Q: D[v] = Q[v] if v == end: break for w in G.getVertex(v).adjacencies: vwLength = D.get(v) + G.vertexAdjacencies(v).get(w).getcost() if w in D: if vwLength < D.get(w): raise ValueError("Dijkstra: found better path to already-final vertex") elif w not in Q or vwLength < Q.get(w): Q[w] = vwLength P[w] = v return D, P
def test_multiple(self): '''Test that two different priority queues do not interfere with each other''' pq = PriorityQueue() pq.push(0, 'A') pq = PriorityQueue() self.assertEqual(len(pq), 0) with self.assertRaises(IndexError): pq.pop()
def dijkstra(self, start, goal, exceptions=None): '''Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. .. note:: Unmodified, Dijkstra's algorithm searches outward in a circle from the start node until it reaches the goal. It is therefore slower than other methods like A* or Bi-directional Dijkstra's. The algorithm is included here for performance comparision against other algorithms only. .. seealso:: :func:`aStarPath`, :func:`dijkstraBi` ''' dist = {} # dictionary of final distances came_from = {} # dictionary of predecessors # nodes not yet found queue = PriorityQueue() # The set of nodes already evaluated closedset = [] queue.push(0, start) while len(queue) > 0: #log.debug("queue: " + str(queue)) weight, x = queue.pop() dist[x] = weight if x == goal: #log.debug("came_from: " + str(came_from)) path = self.reconstructPath(came_from, goal) #log.info("Path: %s" % path) return path closedset.append(x) for y in self.neighborNodes(x): if y in closedset: continue if(exceptions is not None and y in exceptions): continue costxy = self.timeBetween(x,y) if not dist.has_key(y) or dist[x] + costxy < dist[y]: dist[y] = dist[x] + costxy queue.reprioritize(dist[y], y) came_from[y] = x #log.debug("Update node %s's weight to %g" % (y, dist[y])) return None
def a_star_search(self): self.clear_history() self.frontier = PriorityQueue() self.frontier.put(AStarNode(self.points[0], None, 0), 0) last_node = None # iterate until the frontier is empty while not self.frontier.empty(): snapshot = Snapshot(list(self.visited), self.frontier.getNodes(), uses_a_star_nodes=True) self.search_snapshots.append(snapshot) current = self.frontier.get() if current.my_point in self.visited: # Never mind, we didn't want that snapshot :) self.search_snapshots.remove(snapshot) continue self.visited.append(current.my_point) # end immediately if the goal is found if self.is_goal(current.my_point): last_node = current break # find out which point we're dealing with try: index = self.points.index(current.my_point) except: print >> sys.stderr, 'Vertex not found in points' return False # prepare qualified new neighbors to be added to frontier row = self.visibility_graph[index] index = 0 for item in row: neighbor = self.points[index] if item == 1 and neighbor not in self.visited: distance = current.cost distance += self.distance(neighbor, current.my_point) # distance so far est_distance_remaining = distance + self.distance(neighbor, self.points[1]) # est. distance to go self.frontier.put(AStarNode(neighbor, current, distance), est_distance_remaining) index += 1 # unwind path back to start while not last_node == None: self.path.insert(0, last_node.my_point) last_node = last_node.parent
def dijkstrasAlgorithm(graph, start, surface): pq = PriorityQueue() for v in graph: v.setStatus(0) v.setDistance(float("inf")) #print((v.getDistance(), v)) pq.enQueue((v.getDistance(), v)) #start.setStatus(2) start.setDistance(0) pq.updatePriority((float("inf"), start), (0, start)) #heapq.heappush(pq, (0, start)) #pq.enQueue((0, start)) #while (not pq.isEmpty()): for i in range(0, graph.order): current = pq.deQueue()[1] current.setStatus(2) if(current.getParent() != None): graph.drawEdge(current.getParent(), current, surface, "blue") time.sleep(0.5) #if(current.getParent() != None): # print(str(current.getParent().getId()) + "->" + str(current.getId())) for neighbour in current.getNeighbours(): """ if (neighbour.getStatus() == 0): neighbour.setStatus(1) neighbour.setParent(current) #neighbour.setpqWeight(current.neighbours[neighbour]) neighbour.setDistance(current.getDistance() + current.neighbours[neighbour]) pq.enQueue((neighbour.getDistance(), neighbour)) """ #elif (neighbour.getStatus() == 1): if (neighbour.getDistance()) > (current.getDistance() + current.neighbours[neighbour]): old = (neighbour.getDistance(), neighbour) #neighbour.setpqWeight(current.neighbours[neighbour]) #pq.updatePriority(old, (neighbour.getpqWeight(), neighbour)) neighbour.setParent(current) neighbour.setDistance(current.getDistance() + current.neighbours[neighbour]) pq.updatePriority(old, (neighbour.getDistance(), neighbour)) """