def get_vehicle(vehicle_type, zipcode): #Here we find the list of all available specified vehicles available_vehicles = [ v for v in vehicles if v['type'] == vehicle_type and v['available'] ] #If there are available vehicles if len(available_vehicles) > 0: g.reset_vertices() #resets our graph place = g.get_vertex(zipcode) #Returns Our Starting vertex dijkstra.dijkstra( g, place ) # setting distance of each node with respect to our starting vertex #Stores the distance of available vehicle from origin of request for av in available_vehicles: av['distance'] = g.get_vertex(av['zipcode']).get_distance() #Sorting the list of all the available vehicles, based on key with inline function Lambda(sorts based on Distances) #The below contains list of KEY, VALUE pairs available_vehicles = sorted(available_vehicles, key=lambda k: k['distance']) return available_vehicles #Sorted list of available vehicles
def test(): #disponivel http://www.fernandolobo.info/aed-II/teoricas/a24e25.print.pdf print 'Testando grafo de exemplo das aulas do prof. Fernando Lobo da universidade Algarve in Portugal.' g = grafo(direcionado=True) g.inserir_vertice('a') g.inserir_vertice('b') g.inserir_vertice('c') g.inserir_vertice('d') g.inserir_vertice('e') g.inserir_aresta('a','b',10) g.inserir_aresta('a','c',3) g.inserir_aresta('b','c',1) g.inserir_aresta('b','d',2) g.inserir_aresta('c','b',4) g.inserir_aresta('c','d',8) g.inserir_aresta('c','e',2) g.inserir_aresta('d','e',7) g.inserir_aresta('e','d',9) dijkstra(g,'a') for v in g.get_vertices(): caminho = [v.get_id()] caminho_minino(v, caminho) print 'O menor caminho é: %s com custo %d.' %(caminho[::-1], v.get_distancia())
def test_dijkstra(): ''' Test `dijkstra` function. This is an implementation of dijkstra's algorithm for finding shortest path distances to all nodes in a graph from a specified start node. ''' G = make_graph('test_data/undirected.txt') expected = {'A': 0, 'C': 3, 'B': 1, 'D': 4} dist, pred = dijkstra(G, 'A') assert dist == expected G = make_graph('test_data/directed.txt') dist, pred = dijkstra(G, 'A') assert dist == expected graph = {'a': {'b': 1}, 'b': {'c': 2, 'b': 5}, 'c': {'d': 1}, 'd': {}} dist, pred = dijkstra(graph, start='a') assert dist == {'a': 0, 'c': 3, 'b': 1, 'd': 4} assert pred == {'b': 'a', 'c': 'b', 'd': 'c'}
def dispatch(vehicle_type, zipcode): unassigned_vehicles = [ v for v in vehicles if int(v['T']) == vehicle_type and v['AVAILABILITY'] ] if len(unassigned_vehicles) > 0: g.reset_vertices( ) #vertex's distance = infinityvi; vextex.visited = False; vertex.previous = None will be done in reset_vertices() method place = g.get_vertex(zipcode) #Returns vert_dict dijkstra.dijkstra( g, place ) #passing the graph object and place into DIJKSTRA's method in Dijkstra's file #Calculating and storing the list of distances for all the available vehicles done by adding vertex and getting distance for vehicle in unassigned_vehicles: vehicle['DISTANCE'] = g.get_vertex(int( vehicle['ZIPCODE'])).get_distance() #Sorting the list of all the available vehicles, based on key with inline function Lambda(sorts based on Distances) #The below contains list of KEY, VALUE pairs unassigned_vehicles = sorted(unassigned_vehicles, key=lambda k: k['DISTANCE']) # vehicles[vehicles.index(availability[0])]['AVAILABILITY'] = False print("The ID of assigned vehicle is " + unassigned_vehicles[0]['SNUM'] + " and the shortest distance from the requested ZIPCODE is " + str(unassigned_vehicles[0]['DISTANCE'])) return
def run(do_print): f = open("runtime.txt", "w") print("Run dijkstra ...") # dijkstra t0 = time.clock() for i in range(n): dijkstra(i, Matrix, Neighbors, do_print=do_print) td = time.clock() - t0 print("Run bf ...") # bf t0 = time.clock() for i in range(n): bf(i, Matrix, Neighbors, do_print=do_print) tf = time.clock() - t0 print("Run fw ...") # fw t0 = time.clock() fw(Matrix, Neighbors, do_print=do_print) tw = time.clock() - t0 # print td = td / (n * n) tf = tf / (n * n) tw = tw / (n * n) f.write("Dijkstra: " + str(td) + " seconds\n") f.write("Bellman-Ford: " + str(tf) + " seconds\n") f.write("Floyd-Warshall: " + str(tw) + " seconds") f.close()
def johnson(g, w): vertexes_g = g.get_v() edges_g = g.get_e() s = NameVertex('s') vertexes_g1 = [s] + vertexes_g edges_g1 = edges_g.copy() for vertex in vertexes_g: edges_g1.append(Edge(s, vertex, 0)) graph2 = DirectedGraph(vertexes_g1, edges_g1) if bellman_ford(graph2, w, s) == False: print("the in put graph contains a negative_weight cycle") else: h = dict() for vertex in vertexes_g1: h[vertex] = vertex.d def weight1(edge): return w(edge) + h[edge.u] - h[edge.v] n = len(vertexes_g) d = dict() for u in vertexes_g: dijkstra(g, weight1, u) d[u] = dict() for v in vertexes_g: d[u][v] = v.d + h[v] - h[u] return d
def get_vehicle(vehicle_type, zipcode): #Here we are defining a new variable that stores all the available vehicles, It iterates over the variable 'VEHICLE' and #.. selects the vehicle only condition1: that vehicle type is present and condition2: the present vehicle is still available or not available_vehicles = [ v for v in vehicles if v['type'] == vehicle_type and v['available'] ] #If there are available vehicles if len(available_vehicles) > 0: g.reset_vertices( ) #vertex's distance = infinityvi; vextex.visited = False; vertex.previous = None will be done in reset_vertices() method place = g.get_vertex(zipcode) #Returns vert_dict dijkstra.dijkstra( g, place ) #passing the graph object and place into DIJKSTRA's method in Dijkstra's file #Calculating and storing the list of distances for all the available vehicles done by adding vertex and getting distance for av in available_vehicles: av['distance'] = g.get_vertex(av['zipcode']).get_distance() #Sorting the list of all the available vehicles, based on key with inline function Lambda(sorts based on Distances) #The below contains list of KEY, VALUE pairs available_vehicles = sorted(available_vehicles, key=lambda k: k['distance']) return available_vehicles #Sorted list of available vehicles
def test_graph_1(self): gg = Graph([ ('A', 'B', 3), ('A', 'C', 4), ('A', 'D', 7), ('B', 'C', 1), ('B', 'F', 5), ('C', 'D', 2), ('C', 'F', 6), ('D', 'E', 3), ('D', 'G', 6), ('E', 'F', 1), ('E', 'G', 3), ('E', 'H', 4), ('F', 'H', 8), ]) r""" . A---D---G . |\ / \ /| . | C E | . |/ \ / \| . B---F---H """ self.assertEqual( ['A', 'C', 'D', 'E', 'H'], dijkstra(gg, 'A', 'H'), ) self.assertEqual( ['B', 'C', 'D', 'G'], dijkstra(gg, 'B', 'G'), )
def test_graph_2(self): gg = Graph([ ('A', 'B', 14), ('A', 'G', 10), ('A', 'H', 17), ('B', 'C', 9), ('B', 'F', 10), ('B', 'G', 3), ('C', 'F', 2), ('F', 'I', 7), ('G', 'H', 6), ('G', 'I', 4), ('H', 'I', 1), ]) r""" . B---G . /|\ /|\ . C | A | \ . \| \| | . F H | . \ \| . `---I """ self.assertEqual(['C', 'F', 'I', 'H'], dijkstra(gg, 'C', 'H')) self.assertEqual(['A', 'G', 'I', 'F'], dijkstra(gg, 'A', 'F'))
def johnson(G, w): # 计算G' # 对G加入一源节点s # 使得(s, v) = 0 G1, s, w = compute_G(G, w) if False == bellman_ford(G1, w, s): raise "graph contain negative-weight cycle" else: # 计算h(v) h = {} for v in G1.V: h[v] = v.d # 更新w w1 = {} for u in G1.V: for v in G1.E[u]: w1[(u, v)] = w[u, v] + h[u] - h[v] n = len(G.V) D = [[0 for j in range(n)] for i in range(n)] # 使用Dijkstra算法 for u in G.V: dijkstra(G, w1, u) for v in G.V: D[u.value - 1][v.value - 1] = v.d + h[v] - h[u] return D
def test(): print 'Testando grafo de exemplo do livro Algoritmos 3rd (Cormen), página 480.' g = grafo(direcionado=True) g.inserir_vertice('a') g.inserir_vertice('b') g.inserir_vertice('c') g.inserir_vertice('d') g.inserir_vertice('e') g.inserir_aresta('a','b',10) g.inserir_aresta('a','c',5) g.inserir_aresta('b','d',1) g.inserir_aresta('b','c',2) g.inserir_aresta('c','b',3) g.inserir_aresta('c','e',2) g.inserir_aresta('c','d',9) g.inserir_aresta('d','e',4) g.inserir_aresta('e','a',7) g.inserir_aresta('e','d',6) dijkstra(g,'a') for v in g.get_vertices(): caminho = [v.get_id()] caminho_minino(v, caminho) print 'O menor caminho é: %s com custo %d.' %(caminho[::-1], v.get_distancia())
def get_shortest_path(g, initial, target): reset_shortest_path(g) print 'Origin: ', initial, 'Target: ', target dj.dijkstra(g, g.get_vertex(initial), g.get_vertex(target)) target = g.get_vertex(target) path = [target] dj.shortest(target, path) return list(reversed(path))
def test_dijkstra_int_vertices_negaitve(self): graph = Graph() graph.add_edge(Edge(Vertex(1), Vertex(2), 1)) graph.add_edge(Edge(Vertex(1), Vertex(4), 1)) graph.add_edge(Edge(Vertex(3), Vertex(4), 1)) graph.add_edge(Edge(Vertex(4), Vertex(2), 1)) self.assertEqual(dijkstra(graph, Vertex(5), Vertex(0)), float("inf")) self.assertEqual(dijkstra(graph, Vertex(1), Vertex(5)), float("inf"))
def single_timed_test(g, u, v, structure): '''runs a single instance of the Dijkstra algorithm on a graph g with starting node u and ending node v. structure refers to the type data structure used''' t0 = time() dijkstra.dijkstra(g, g.get_vertex(u), structure) target = g.get_vertex(v) path = [target.get_id()] dijkstra.shortest(target, path) t1 = time() return t1 - t0
def main(): G = Graph() t1 = datetime.now() G.createGraphG1() t2 = datetime.now() print("Time to create sparse graph G1 ", t2 - t1) print("Source, Destination", "\t\t\t", "Dijkstra With Heap", "\t\t\t", "Dijkstra without Heap ", "\t\t\t", "Kruskal") for i in range(5): num1 = random.randint(0, V - 1) num2 = random.randint(0, V - 1) if num1 == num2: continue t3 = datetime.now() bw = dijkstra(G, num1, num2) t4 = datetime.now() t5 = datetime.now() bw1 = dijkstraWithHeap(G, num1, num2) t6 = datetime.now() t7 = datetime.now() bw2 = Kruskal(G, num1, num2) t8 = datetime.now() print(num1, num2, "\t\t\t", bw, t4 - t3, "\t\t\t", bw1, t6 - t5, "\t\t\t", bw2, t8 - t7) t1 = datetime.now() T = Graph() T.createGraphG2() t2 = datetime.now() print("Time to create dense graph G2 ", t2 - t1) print("Source, Destination", "\t\t\t", "Dijkstra With Heap", "\t\t\t", "Dijkstra without Heap", "\t\t\t", "Kruskal") for i in range(5): num1 = random.randint(0, V - 1) num2 = random.randint(0, V - 1) if num1 == num2: continue t3 = datetime.now() bw = dijkstra(T, num1, num2) t4 = datetime.now() t5 = datetime.now() bw1 = dijkstraWithHeap(T, num1, num2) t6 = datetime.now() t7 = datetime.now() bw2 = Kruskal(T, num1, num2) t8 = datetime.now() print(num1, num2, "\t\t\t", bw, t4 - t3, "\t\t\t", bw1, t6 - t5, "\t\t\t", bw2, t8 - t7)
def johnson(graph: Graph, type: str = 'copy'): def transform_vertices(graph_matrix: list, distance: list): for i in range(len(graph_matrix)): for j in range(len(graph_matrix[i])): graph_matrix[i][j] += distance[i] - distance[j] def rollback_vertices(graph_matrix: list, distance: list): for i in range(len(graph_matrix)): for j in range(len(graph_matrix[i])): graph_matrix[i][j] += -distance[i] + distance[j] total_v = graph.get_total_v() new_graph = add_vertice(graph,[0]*(total_v + 1)) new_total_v = new_graph.get_total_v() distance_bf = bellman_ford(new_graph, new_total_v - 1) graph_matrix = graph.get_matrix(type) transform_vertices(graph_matrix, distance_bf) result = [] for i in range(len(graph_matrix)): result.append(dijkstra(Graph(graph_matrix), i)) rollback_vertices(result, distance_bf) return result
def johnson(graph): """ All pair shortest path algorithm with complexity O(nmlogn) for graph with negative edges - Create a new graph with a grounded node which has oneway connections to all other nodes - First use bellman_ford to reweight c_uv' = c_uv + p(v) - p(u) AND to detect negative cost cycles if present - Then apply Dijkstra on the reweighted graph to find shortest path - Then transformed shortest path values back to the unweighted values c_uv = c_uv' + p(u) - p(v) """ V = list(set([k for v in graph.values() for k in v] + graph.keys())) grounded_graph = deepcopy(graph) grounded_graph['ground'] = {v: 0 for v in V} weights = bellman_ford(grounded_graph, 'ground') if not weights: # ncc detected return None reweighted_graph = { u: {v: c + weights[u] - weights[v] for v, c in d.iteritems()} for u, d in graph.iteritems() } # dijkstra n times apsp = {v: dijkstra(reweighted_graph, v) for v in V} # unweight apsp = { u: {v: c - weights[u] + weights[v] for v, c in d.iteritems()} for u, d in apsp.iteritems() } return apsp
def johnson(graph, num_vertices): shortest_distances = {} # add a new vertex 0 to the graph that is # connected to all of the other vertices with weight 0 for i in range(1, num_vertices): graph[i][0] = 0 # run the Bellman-Ford algorithm on the graph with vertex 0 as the source # to find the shortest path distances from the source vertex to each of the # other vertices. If a negative cycle is detected, terminate the algorithm try: distances, predecessors = bellman_ford(graph, num_vertices, 0) # remove the vertex 0 from the graph for i in range(1, num_vertices): del graph[i][0] reversed_graph = reverse_graph(graph) for i in range(1, num_vertices): # re-weight the edges of the original graph using the values # computed by the Bellman-Ford algorithm, to w(u, v) + h(u) - h(v) for tail in graph[i]: graph[i][tail] += distances[tail] - distances[i] # run Dijkstra's algorithm n times to find the shortest path # distances from each vertex to every other vertex shortest_distances[i] = dijkstra(reversed_graph, num_vertices, i) return shortest_distances except AssertionError as err: print(str(err))
def test_dijkstra_1(): paths = dijkstra( create_graph( ["A", "B", "C", "D", "E", "F", "G", "H"], [ ("A", "B", 4), ("A", "C", 8), ("A", "D", 1), ("B", "C", 3), ("C", "D", 9), ("C", "F", 5), ("C", "H", 4), ("D", "E", 2), ("E", "F", 3), ("F", "G", 2), ("G", "H", 3), ], directed=False, ), "A", ) expected = { "B": ("A", "B"), "C": ("A", "B", "C"), "D": ("A", "D"), "E": ("A", "D", "E"), "F": ("A", "D", "E", "F"), "G": ("A", "D", "E", "F", "G"), "H": ("A", "B", "C", "H"), } for v in expected: assert set(paths[v]) == set(expected[v])
def test_graph_3(self): # https://es.wikipedia.org/wiki/Anexo:Ejemplo_de_Algoritmo_de_Dijkstra gg = Graph([ ('A', 'B', 16), ('A', 'C', 10), ('A', 'D', 5), ('B', 'C', 2), ('B', 'F', 4), ('B', 'G', 6), ('C', 'D', 4), ('C', 'E', 10), ('C', 'F', 12), ('D', 'E', 15), ('E', 'F', 3), ('E', 'Z', 5), ('F', 'G', 8), ]) r""" . B---,---G . / \ \ / \ . A---C---F---Z . \ / \ / / . D---E--- """ self.assertEqual(['A', 'D', 'C', 'B', 'F', 'E', 'Z'], dijkstra(gg, 'A', 'Z'))
def main(): f = open("cal.cedge", "r") data = [] for line in f: data.append(line) G = graph() for edge in data: edge = edge.split(" ") edge[3] = edge[3][:-1] G.add_edge(edge[1], edge[2], float(edge[3])) sorted_l = sorted(G.matrix, key=lambda x: len(G.matrix[x]), reverse=True) # print(G.node_ranking('5')) # print(G.printGraph()) # init_hop_doubling_label(G) # update_hop_doubling(G) with open('hop_doubling.txt', encoding='utf8') as f: index = f.readlines()[0] index = ast.literal_eval(index) result = query(index, '10000', '10010', [], 0) print(result) d, p = dijkstra(G, '0') print(d['14'])
def cheater(graph, s, t): g_reverse = graph.reverse(copy=True) _, pi = dijkstra(g_reverse, t) distances = defaultdict(constant_factory(float("+inf"))) parents = {} queue = PriorityQueue() queue.insert(s, pi[s]) distances[s] = 0 settled = 0 relaxed = 0 while not queue.is_empty(): u, r = queue.extract_min() settled += 1 if u == t: break for node, edge_details in graph[u].items(): if distances[u] + edge_details['weight'] < distances[node]: relaxed += 1 distances[node] = distances[u] + edge_details['weight'] parents[node] = u if queue.contains(node): queue.decrease_key(node, distances[node] + pi[node]) else: queue.insert(node, distances[node] + pi[node]) return distances[t], settled, relaxed, [ parents.keys(), [] ]
def graph_tools_runner(g, input_file): start = g.get_start() finish = g.get_finish() target = g.get_vertex(finish) # Destination point path = [target.get_id()] dijkstra(g, g.get_vertex(start), g.get_nearby()) shortest_path(target, path) # Find a shortest path to finish path_output = ' -> '.join(path[::-1]) + ': ' + str(target.get_distance()) # Build reachable destiations string from Dictionary reachable_destinations = ', '.join( "%s: %r" % (key, val) for (key, val) in g.get_vertex(start).get_reachable_for_time().iteritems()) return path_output, reachable_destinations
def atividade1(): # Exercicio 1: print('Exercicio 1 (Funções De Grafos):') graph_path = "./instances/caminho_minimo/fln_pequena.net" graph = buildGraphFromFile(graph_path) test_graph(graph_path, graph) # Exercicio 2: print('\nExercicio 2 (Busca em largura):\n') print(breadthFirstSearch(graph, '1')[0]) # Exercicio 3: print('\nExercicio 3 (Ciclo Euleriano):\n') graph_path = "./instances/ciclo_euleriano/ContemCicloEuleriano.net" graph = buildGraphFromFile(graph_path) print(getEulerianTour(graph)) # Exercicio 4: print('\nExercicio 4 (Dijkstra):\n') graph_path = "./instances/caminho_minimo/fln_pequena.net" graph = buildGraphFromFile(graph_path) print(dijkstra(graph, '1', True)) # Exercicio 5: print('\nExercicio 5 (Floyd-Warshall):\n') graph_path = "./instances/caminho_minimo/fln_pequena.net" graph = buildGraphFromFile(graph_path) print(floydWarshall(graph))
def johnson(G): duv = [[0 for i in range(len(G))]for j in range(len(G))] _G = copy.copy(G) x = len(G) tmp = {} for i in G.keys(): tmp.update({i:0}) _G.update({x:tmp}) d = bellman_ford(_G,x) if d == False: print "the input graph contains a negative-weight cycle" return else: h = {} for i in _G.keys(): h.update({i:d[i]}) #print 'h:',h for u in _G.keys(): for v in _G[u]: _G[u][v] = _G[u][v] + h[u] - h[v] #print _G for u in G.keys(): d = dijkstra(_G,u) #print u,d for v in G.keys(): duv[u][v] = d[v] + h[v] - h[u] return duv
def main(): bpath = "board-2-4.txt" board = Board(bpath) b, o, c = dijkstra(board) board.board_to_image_e(b, o, c) print("Opened: " + str(len(o))) print("Closed: " + str(len(c)))
def main(): grafo = Grafo() archivo = "map.osm" depurar(archivo) print("fin de depuracion") archivo2 = "modificado.xml" grafo = Grafo() grafo = grafoOSM(archivo2) print("fin de procesamiento de datos OSM") # PRUEBA arbol = kruskal(grafo) print("fin de kruskal") idA = encuentra_punto(grafo, -12.066159, -77.073635) # -12.071697, -77.076262) assert idA in grafo.dic_vertices.keys( ), "idA no se encuentra dentro del grafo" idB = encuentra_punto( grafo, -12.072115, -77.072334) # -12.070534, -77.066984) # -12.086531, -77.063292) assert idB in grafo.dic_vertices.keys( ), "idB no se encuentra dentro del grafo" camino = dijkstra(grafo, arbol, idA, idB) print("fin de dijkstra") mapeoarbol(grafo, arbol, camino) print("fin de grafico de mapa") print("FIN")
def findNewPath(self, startVertices, endVertices, newRoutes, matrixPshort, gamma, lohse, dk): """ This method finds the new paths for all OD pairs. The Dijkstra algorithm is applied for searching the shortest paths. """ newRoutes = 0 for start, startVertex in enumerate(startVertices): endSet = set() for end, endVertex in enumerate(endVertices): if startVertex._id != endVertex._id and matrixPshort[start][end] > 0.: endSet.add(endVertex) if dk == 'boost': D, P = dijkstraBoost(self._boostGraph, startVertex.boost) elif dk == 'plain': D, P = dijkstraPlain(startVertex, endSet) elif dk == 'extend': D, P = dijkstra(startVertex, endSet) for end, endVertex in enumerate(endVertices): if startVertex._id != endVertex._id and matrixPshort[start][end] > 0.: helpPath = [] helpPathSet = set() pathcost = D[endVertex] / 3600. ODPaths = self._paths[startVertex][endVertex] for path in ODPaths: path.currentshortest = False vertex = endVertex while vertex != startVertex: helpPath.append(P[vertex]) helpPathSet.add(P[vertex]) vertex = P[vertex]._from helpPath.reverse() newPath, smallDiffPath = self.checkSmallDiff( ODPaths, helpPath, helpPathSet, pathcost) if newPath: newpath = Path(startVertex, endVertex, helpPath) ODPaths.append(newpath) newpath.getPathLength() for route in ODPaths: route.updateSumOverlap(newpath, gamma) if len(ODPaths) > 1: for route in ODPaths[:-1]: newpath.updateSumOverlap(route, gamma) if lohse: newpath.pathhelpacttime = pathcost else: newpath.actpathtime = pathcost for edge in newpath.edges: newpath.freepathtime += edge.freeflowtime newRoutes += 1 elif not smallDiffPath: if lohse: path.pathhelpacttime = pathcost else: path.actpathtime = pathcost path.usedcounts += 1 path.currentshortest = True return newRoutes
def way(self, from_node, to_node, seen_nodes=[]): edges = [] for node, n_nodes in self.nodes.items(): for n_node in n_nodes: edges.append((node, n_node, 1)) way = dijkstra(edges, from_node, to_node, seen_nodes) return way
def johnson(edgedict,n): """ one Bellman-Ford O(mn), n Dijkstra O(n*m*log(n)), n^2 pairwise distances O(n^2). """ # 1. create G' by adding a new source Gprime = copy.deepcopy(edgedict) for i in range(n): Gprime[(n,i)] = 0 # 2. compute shortest path via bellman-ford, if negative cycle, halt reweight = bellman_ford(Gprime,n+1,s=n) if reweight is None: return reweight reweight = reweight[0:-1] # 3. create adjacency list with modified edge lengths adjlist = [[] for i in range(n)] lengths = [[] for i in range(n)] for (i,j),value in edgedict.items(): adjlist[i].append(j) lengths[i].append(value + reweight[i] - reweight[j]) # 4. repeat Dijkstra for every sources dist = [] for s in range(n): temp = dijkstra.dijkstra(adjlist, lengths, s) dist.append(temp) # 5. recover real distance for i in range(n): for j in range(n): dist[i][j] += reweight[j] - reweight[i] return dist
def display_path() -> None: """ displays path """ pygame.draw.rect(window, BG, ((MIN + 1, 120), (MAX - MIN, 50))) file = f"export\maze[{ROWS}x{COLS}].txt" s = "searching path, please wait ..." s_label = FONT.render(s, True, (255, 255, 255)) window.blit(s_label, (SEP, 120)) pygame.display.flip() a = time() path = dijkstra(file) b = time() pygame.draw.rect(window, BG, ((MIN + 1, 120), (MAX - MIN, 50))) s = f"path of lenght {(len(path)-1)//2}" s_label = FONT.render(s, True, (255, 255, 255)) window.blit(s_label, (SEP, 120)) s = f"found in {round(b-a, 3)}s" s_label = FONT.render(s, True, (255, 255, 255)) window.blit(s_label, (SEP, 130)) pygame.display.flip() for i in range(len(path) - 1): x1, y1 = path[i] x2, y2 = path[i + 1] pygame.draw.line(window, HG, (y1 * W / 2, x1 * W / 2), (y2 * W / 2, x2 * W / 2))
def post_dijkstra(): response.content_type = 'application/json' node1 = Node.find(request.json['start']) node2 = Node.find(request.json['end']) tm_start = time.perf_counter() route = dijkstra(node1, node2) print('time: {0:.3f} ms'.format(1000 * (time.perf_counter() - tm_start))) return json.dumps([x.id for x in route])
def testFloydWarshall(self): for i in range(50): adjList = self.randG.randomGnmGraph(n=50, M=1000, isWeighted=True) nodes, edges = self.randG.toNodeEdges(adjList) src = random.choice(list(adjList.keys())) dist1, prev1 = dijkstra(adjList, src) dist2, prev2 = floyd_warshall(nodes, edges) self.assertEqual(dist1, dist2[src])
def test_large_example(self): file_name = self.file_path + 'large.txt' start, finish = 13,5 expected = 26 G = file_to_graph(file_name) final_dist = dijkstra(G,start) result = final_dist[finish] self.assertEqual(expected, result)
def test_small_example(self): file_name = self.file_path + 'small.txt' start, finish = 1, 4 expected = 2 G = file_to_graph(file_name) final_dist = dijkstra(G,start) result = final_dist[finish] self.assertEqual(expected, result)
def test_medium_example(self): file_name = self.file_path + 'medium.txt' start, finish = 1,7 expected = 5 G = file_to_graph(file_name) final_dist = dijkstra(G,start) result = final_dist[finish] self.assertEqual(expected, result)
def take_train(self, origin, destination): """ :param origin: Original train station from the location where the journey will begin. :param destination: Destination is where the passenger has already begun. :return: a tuple of list of stations and time if time_between stations was given. :Note: This function will behave fine with weighted and non wighted graphs. """ return dijkstra(self.network, origin, destination)
def main(): file_location = 'highways.txt' graph = build_graph(file_location) start = 'Atlanta' destinations = ['New_York', 'Dallas', 'Chicago'] dists, paths = dijkstra(graph, start) for dest in destinations: print(dest, dists[dest], ' -> '.join(paths[dest]))
def test_dijkstra_against_scipy(): W = np.random.random((100, 100)) W += W.transpose() W[W<1.0] = np.inf W = scipy.sparse.csr_matrix(W) for seed in [0,1,2]: result0 = dijkstra.dijkstra(W, seed) result1 = scipy.sparse.csgraph.dijkstra(W, indices = [seed])[0] assert all(result0 == result1)
def Johnson(num_nodes, edges): """Given the graph nodes (labeled from 1 to num_nodes), and graph edges( in form of {(tail, head): edge_dist}, computes the all pairs shortest path if graph does not contain negative cycle. An additional 'new_node' is added to the graph G, and then Bellman_Ford algorithm runs on the new graph G' to detect negative cycles, and computes the shortest path form the 'new_node' to all nodes of G if no negative cycle exists. The shortest path is then used to compute a weighted edge for each edge in G, so that with weighted edges, which are all non-negative, the fast Dijkstra's algorithm can be used to compute single source shortest path for each source node. Note in Dijkstra, a PriorityQueue 'pq' requires a heap initialization for every source. And different from the 'edges' that Johnson has as input, the 'edges' for Dijkstra is in a form of {tail:[(head, edge_dist), ...]}, so 'dijkstra_edges' needs to be constructed first. After Dijkstra's algorithm computes the shortest path, the shortest path distance is corrected by the shortest path from 'new_node' in G'. Algorithm has 1 invocation of Bellman_Ford(Big-O(nm)) and n invocations of Dijkstra (Big-O(mnlogn)), so the overall running time is O(mnlogn).""" all_pairs_shortest_path = {} new_node = num_nodes + 1 new_edges = edges.copy() dijkstra_edges = defaultdict(list) #--------------------Bellman Ford------------------------ for node in range(1, num_nodes + 1): new_edges[(new_node, node)] = 0 bf = Bellman_Ford(new_node, num_nodes + 1, new_edges) if bf == "Graph has negative circle!": return bf #-------------------------------------------------------- #--------------weighted edges and Dijkstra edges----------- for ((tail, head), dist) in edges.items(): weighted_dist = dist + bf[tail] - bf[head] dijkstra_edges[tail].append((head, weighted_dist)) #---------------------------------------------------------- for source in range(1, num_nodes + 1): source_edges = dict(dijkstra_edges[source]) heap = [] #----------------priority queue initialization--------------- for node in range(1, num_nodes + 1): if node != source: if node in source_edges.keys(): heap.append([source_edges[node], node]) else: heap.append([float('inf'), node]) pq = dijkstra.PriorityQueue(heap) #------------------------------------------------------------ shortest_path_dict = dijkstra.dijkstra(source, pq, dijkstra_edges) for (node, dist) in shortest_path_dict.items(): all_pairs_shortest_path[(source, node)] = dist - bf[source] + bf[node] return min(all_pairs_shortest_path.values())
def test_one_node(self): """Graph with a unique vertice.""" node_1 = (0, 0) graph = { node_1: {"neighbors": []} } path, distance = dijkstra(graph, node_1, node_1) self.assertEqual(path, [(0, 0)]) self.assertEqual(distance, 0.0)
def test_two_nodes(self): node_1 = (0, 0) node_2 = (0, 1) graph = { node_1: {"neighbors": [node_2]}, node_2: {"neighbors": [node_1]} } path, distance = dijkstra(graph, node_1, node_2) self.assertEqual(path, [(0, 0), (0, 1)]) self.assertEqual(distance, 1.0)
def test_dykstra_5(): graph1 = guido_graph.Graph() graph1.add_edge('A', 'B', 20) graph1.add_edge('A', 'C', 3) graph1.add_edge('C', 'D', 2) graph1.add_edge('C', 'E', 1) graph1.add_edge('D', 'F', 1) graph1.add_edge('F', 'B', 5) path, distance = dijkstra(graph1, 'A', 'B') assert path == ['A', 'C', 'D', 'F', 'B'] assert distance == 11
def update_routing_table(self): dist = {} if 1 == len(self.received_packets): self.routing_table = {self.name:[self.name]} return for packet, seq_num, node, age in self.received_packets.values(): for neighbor, distance in packet.values(): dist[(node.name,neighbor.name)] = distance dist[(neighbor.name,node.name)] = distance if len(dist) == 0: print self.received_packets dist[(self.name,self.name)] = 0 # IMPORTANT self.routing_table = dijkstra.dijkstra(self.name,dist)
def test_dkystra_4(): graph1 = guido_graph.Graph() graph1.add_edge('A', 'B', 2) graph1.add_edge('A', 'C', 10) graph1.add_edge('C', 'F', 1) graph1.add_edge('B', 'D', 3) graph1.add_edge('D', 'E', 5) graph1.add_edge('E', 'F', 2) graph1.add_edge('D', 'C', 1) path, distance = dijkstra(graph1, 'B', 'C') assert path == ['B', 'D', 'C'] assert distance == 4
def test_dijkstra(self): graph = { "a": {"b": 7, "c": 9, "f": 14}, "b": {"a": 7, "c": 10, "d": 15}, "c": {"a": 9, "b": 10, "d": 11, "f": 2}, "d": {"b": 15, "c": 11, "e": 6}, "e": {"d": 6, "f": 9}, "f": {"a": 14, "c": 2, "e": 9}, } x, y = "a", "e" # shortest distance from 'a' to 'e' distance, path = dijkstra(graph, x, y) self.assertEqual(distance, 20) self.assertListEqual(path, ["a", "c", "f", "e"])
def main(): r = 10 m = 15 n = 10 edges = [] random.seed() print "EDGES:" for i in xrange(m): s = '' for j in xrange(n): d = Edge.Edge( (i,j), (i+1,j), random.randint(1, r) ) edges.append(d) s += ' ' + str(d) d = Edge.Edge( (i,j), (i,j+1), random.randint(1, r) ) edges.append(d) s += ' ' + str(d) print s print s = Vertex.Vertex((0, 0)) s.distance = 0 dijkstra.dijkstra(edges, s)
def test_three_nodes_2(self): """Tres nodos encadenados en linea recta.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (2, 0) graph = { node_1: {"neighbors": [node_2]}, node_2: {"neighbors": [node_3]}, node_3: {"neighbors": [node_2]} } path, distance = dijkstra(graph, node_1, node_3) self.assertEqual(path, [(0, 0), (1, 0), (2, 0)]) self.assertEqual(distance, 2.0)
def test_three_nodes_1(self): """Tres nodos equidistantes.""" node_1 = (0, 0) node_2 = (0, 1) node_3 = (1, 0) graph = { node_1: {"neighbors": [node_2, node_3]}, node_2: {"neighbors": [node_1, node_3]}, node_3: {"neighbors": [node_1, node_2]} } path, distance = dijkstra(graph, node_1, node_2) self.assertEqual(path, [(0, 0), (0, 1)]) self.assertEqual(distance, 1.0)
def _compute_path(self): search_algo = dijkstra.dijkstra(self.graph) self.path = search_algo.search(self.source_vertex, self.target_vertex) if self.path: # stats stats = search_algo print 'search takes: %f s (%d -> %d : %d)' % (stats._takes, self.source_vertex, self.target_vertex, len(self.path)) print ' iterations: %d' % (stats._iteration, ) self._fill_drawable_path() self.widget.update() else: self.path = [] print 'search failed'
def test_four_nodes_1(self): """Grafo de 4 nodos, todos interconectados.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (0, 1) node_4 = (1, 1) graph = { node_1: {"neighbors": [node_2, node_3, node_4]}, node_2: {"neighbors": [node_1, node_3, node_4]}, node_3: {"neighbors": [node_1, node_2, node_4]}, node_4: {"neighbors": [node_2, node_3, node_1]} } path, distance = dijkstra(graph, node_1, node_4) self.assertEqual(path, [(0, 0), (1, 1)]) self.assertEqual(round(distance, 5), 1.41421)
def test_answer(): ''' Get the shortest-path distances to the following ten vertices from the graph specified in `test/data.txt`, in order: 7,37,59,82,99,115,133,165,188,197. Returns a comma-separated string of integers containing the results for each vertex in the specified order. ''' G = make_graph('test_data/data.txt') dist, pred = dijkstra(G, '1') ends = [7, 37, 59, 82, 99, 115, 133, 165, 188, 197] # ending vertices results = [str(dist[str(x)]) for x in ends] answer = ','.join(results) expected = '2599,2610,2947,2052,2367,2399,2029,2442,2505,3068' assert answer == expected
def test_four_nodes_2(self): """Grafo de 4 nodos, interconectados como un cuadrado.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (0, 1) node_4 = (1, 1) graph = { node_1: {"neighbors": [node_2, node_3]}, node_2: {"neighbors": [node_1, node_4]}, node_3: {"neighbors": [node_1, node_4]}, node_4: {"neighbors": [node_2, node_3]} } path, distance = dijkstra(graph, node_1, node_4) self.assertEqual(path, [(0, 0), (1, 0), (1, 1)]) self.assertEqual(distance, 2.0)
def find_path(self, node_origin, node_goal, algorithm='a_algorithm'): """ Finds the shortest path between node_origin and node_goal :param: node_origin: starting point :param: node_goal: target point :param: algorithm: algorithm used for finding the shortest path 'a_algorithm' -> A* algorithm 'dijkstra' -> Dijkstra's algorithm :return: A list of points containing the shortest path and the graph extended with origin and goal nodes """ # Put origin and goal in the graph graph_nodes = list(self.nodes) graph_nodes.insert(0, node_origin) graph_nodes.append(node_goal) # Recalculate connection matrix: size = len(graph_nodes) connection_matrix = np.zeros((size, size)) connection_matrix[1:-1,1:-1] = self.distance_matrix for j, end in enumerate(graph_nodes): # Calculate connections to origin node: dist_origin = np.linalg.norm(np.array(graph_nodes[0]) - np.array(end)) if dist_origin <= self.threshold_neighbors and self.environment.is_line_valid(graph_nodes[0], end): connection_matrix[0, j] = dist_origin else: connection_matrix[0, j] = -1 # Calculate connections to goal node: dist_goal = np.linalg.norm(np.array(graph_nodes[-1]) - np.array(end)) if dist_goal <= self.threshold_neighbors and self.environment.is_line_valid(graph_nodes[-1], end): connection_matrix[j, -1] = dist_goal else: connection_matrix[j, -1] = -1 if algorithm == 'a_algorithm': # Calculate shortest path using A* path = a_algorithm(0, len(graph_nodes)-1, graph_nodes, connection_matrix) elif algorithm == 'dijkstra': # Calculate shortest path using dijkstra path = dijkstra(0, len(graph_nodes)-1, connection_matrix, graph_nodes) return path, [ (int(i[0]), int(i[1])) for i in graph_nodes]
def _find_shortest_paths(self, gauge, graph): """Find shortest paths for each possible pair of nodes. Args: gauge: Name of the gauge to calculate shortest paths. """ paths = {} # get nodes with access to the gauge nodes = graph.keys() nodes.sort() # calcualte total paths total_paths = len(nodes) ** 2 print total_paths, "paths will be calculated" for node_a in nodes: # create dictionary for node a in paths paths[node_a] = {} for node_b in nodes: # create dictionary for node b in node a paths[node_a][node_b] = {} # if is the same node, there is no path if node_a == node_b: paths[node_a][node_b]["distance"] = 0.0 paths[node_a][node_b]["path"] = None # if nodes are different, find shortest path else: # use dijkstra to calculate minimum path from a to b distance, path = dijkstra(graph, node_a, node_b) # store results in paths paths[node_a][node_b]["distance"] = distance paths[node_a][node_b]["path"] = path return paths
def test_six_nodes(self): """Ejemplo copiado de la Wikipedia.""" node_1 = (1, 0) node_2 = (0, 1) node_3 = (2, 1) node_4 = (2, 3) node_5 = (4, 2) node_6 = (3, 0) graph = {node_1: {"neighbors": [node_2, node_3, node_6]}, node_2: {"neighbors": [node_1, node_3, node_4]}, node_3: {"neighbors": [node_1, node_2, node_4, node_6]}, node_4: {"neighbors": [node_2, node_3, node_5]}, node_5: {"neighbors": [node_4, node_6]}, node_6: {"neighbors": [node_1, node_3, node_5]} } path, distance = dijkstra(graph, node_1, node_5) self.assertEqual(path, [(1, 0), (3, 0), (4, 2)]) self.assertEqual(round(distance, 5), 4.23607)
def ask_for_prediction(algorithm, user, node, limit=None): same_nodes = graph.get_same_nodes(node) same_nodes.append(node) max_conf = None best_result = None result = None expanded = 0 # repeat algorithm for every size of start item for node in same_nodes: if algorithm == "dijkstra": result = dijkstra(user, node) if result is not None: expanded += result[4] elif algorithm == "astar": result = astar(user, node) if result is not None: expanded += result[4] elif algorithm == "kdirectional": result = kdirectionalDijkstra(user, node) if result is not None: expanded += result[4] elif algorithm == "perimeter_search": result = perimeter_search(user, node, limit) if result is not None: expanded += result[4] elif algorithm == "beam_search": result = beam_search(user, node) if result is not None: expanded += result[4] if result is not None: if best_result is None or result[2] > max_conf: max_conf = result[2] best_result = result # pick best result out of all starting sizes print(algorithm) if best_result is None: print("Path does not exist") else: (best_node, predicted_rating, confidence, length_of_path, _) = best_result print("best_node: ", best_node, " predicted_rating: ", predicted_rating, " confidence: ", confidence, " length_of_path: ", length_of_path, " expanded nodes: ", expanded) print("")
def find_shortest_path(self, node_a, node_b, graphs, restrictions=None): """Find shortest paths for each possible pair of nodes, by gauge.""" paths = {} gauge_names = graphs.keys() for gauge in gauge_names: # prepare graph removing restrictions graph = graphs[gauge] self._remove_restricted_nodes_and_links(graph, restrictions) # find shortest path for the gauge if (node_a in graph) and (node_b in graph): distance, path = dijkstra(graph, node_a, node_b) paths[gauge] = {} paths[gauge]["distance"] = distance paths[gauge]["path"] = path return paths
def next_road(self, network, intersection): """Intersection decision process: direct cars to the nearest exit. Args: network: The queueing network (QueueingNetwork). intersection: Intersection where the decision is being made. Returns: The road (Queue) that the car should turn onto at this intersection. """ # Return answer if it is memoized. if intersection.id in self.shortest_paths: # Answer is memoized. return self.shortest_paths[intersection.id] # Compute all shortest paths from this intersection. shortest_paths = dijkstra.dijkstra(network, intersection) # Pick path to nearest exit. shortest_exit_path = None min_cost = float('inf') for dest, path_and_cost in shortest_paths.items(): path, cost = path_and_cost # Check if destination is exit point. if network.servers[dest].__class__ == qn.ServerTypes.EXIT_POINT: # Update path choice if cost is less. if cost < min_cost: min_cost = cost shortest_exit_path = path # Make sure there is an exit path. assert (shortest_exit_path is not None) # Note: first node in path is the source node. next_intersection_id = shortest_exit_path[1] # Return the next road. for road in network.queues_out[intersection.id]: if road.id_to == next_intersection_id: # Memoize result. self.shortest_paths[intersection.id] = road return road