def KesimoMenorSimples(w, k, vi, vj): C = [None] Delta = [] (c, T) = Dijkstra(w, vi) if T[vj] != None: Delta = [ (c[vj], ObterCamMinDeArv(T, vj), 1, []) ] #(comprimento, caminho mínimo, base, vizinhos que devem ser ignorados) i = 1 while len(Delta) > 0 and i <= k: (c, delta, p, Nlin) = RemoverCamMinDeDelta(Delta) C.append((delta, c)) j = len(delta) for q in range(p, j): IgnViz = Nlin + [delta[q]] if p == q else [delta[q]] wq = ObterDq(w, delta, q, IgnViz) (c, T) = Dijkstra(wq, delta[q - 1]) if T[vj] != None: Clin1 = delta[:q - 1] Clin2 = ObterCamMinDeArv(T, vj) Clin = Clin1 + Clin2 cClin = sum( [w[Clin[i - 1]][Clin[i]] for i in range(1, len(Clin))]) Delta.append((cClin, Clin, q, IgnViz)) i = i + 1 return C[k] if i > k else (None, None)
def shortestCouriertrip(self, latitude, longitude, canTravel, origin, dest): if (self._validateInput(latitude, longitude, canTravel, origin, dest) == True): edges = [] airports = [] """ Precomputes distances and stores in edges edges = [{1: 200, 2: 300},{2: 600, 3: 400}] means distance between airport 0 and 1 is 200 units 0 and 2 is 300 units 1 and 2 is 600 units 1 and 3 is 400 units """ for airport, adjAirports in enumerate(canTravel): adjVertices = adjAirports.split(" ") weights = {} for adjVertex in adjVertices: weights[adjVertex] = self.radius * math.acos( math.sin(latitude[int(airport)]) * math.sin(latitude[int(adjVertex)] * math.cos(latitude[int(airport)]) * math.cos(latitude[int(adjVertex)]) * math.cos(longitude[int(airport)] - longitude[int(adjVertex)]))) edges.append(weights) airports.append(airport) """ creates Graph object for the given data """ G = Graph(edges, airports) D = Dijkstra() print D.singleSourceToDest(G, origin, dest) print "\n"
def __init__(self, graph, agents, model_name, volume_conflict_table, min_cost_table=0): self.graph = graph self.volume_conflict_table = volume_conflict_table if min_cost_table != 0: self.min_cost_path_table = min_cost_table else: try: with open(model_name + '.mct', 'r') as f: data = f.read() if data != '': self.min_cost_path_table = ast.literal_eval(data) except FileNotFoundError: dj = Dijkstra(graph) dj.traverse() self.min_cost_path_table = dj.paths with open(model_name + '.mct', 'w') as f: f.write(str(self.min_cost_path_table)) self.agents = agents self.agent_dict = {} self.make_agent_dict() self.constraints = Constraints() self.constraint_dict = {} self.a_star = AStar(self)
def __init__(self): self.portForReceiving = 0 self.portForSending = 0 self.id = 0 self.printer = Printer() # Green node comunication points. self.agentForReceiving = None self.agentForSending = None self.fromGreenNodeDispatcher = FromGreenNodeDispatcher(self.printer) # Spanning Tree self.spanningTreeMiniDispatcher = SpanningTreeMiniDispatcher( self.printer) self.sharedNotifier = SharedNotifier() self.spanningTreeSendingSide = SpanningTreeSendingSide(self.printer) self.spanningTreeReceivingSide = SpanningTreeReceivingSide( self.printer) self.spanningTreeUpdatesNotifier = SpanningTreeUpdatesNotifier() self.spanningTreeDisconnectionHandler = SpanningTreeDisconnectionHandler( self.printer) self.dijkstraModule=Dijkstra()
def correctness(self): #initialize the boolean value for testing Dijkstra's correctness boolean = True print("testing for correctness of Dijkstra...") #looping through graphs from my graphs and graphs by networkx for answer, my_graph in zip(self.test_list, self.compare_list): # if the graph has no nodes, break, automatically true if len(answer.nodes) > 0: #pick the smallest id to be source source = min(answer.nodes()) #run networkx's dijkstra length, path = nx.single_source_dijkstra(answer, source, weight='weight') #run my dijkstra my_solution = Dijkstra(my_graph) dist, path = my_solution.solver(source) #getting rid of all the node that cannot be reached by the source for k, v in dist.items(): if v == float("inf"): del dist[k] #testing for correctness boolean = boolean and dist == length if boolean: print("Dijkstra test passed") else: print("No") #initialize the boolean value for testing BF's correctness boolean = True print("testing for correctness of BF algorithm ...") #looping through graphs from my graphs and graphs by networkx for answer, my_graph in zip(self.test_list, self.compare_list): # if the graph has no nodes, break, automatically true if len(answer.nodes) > 0: #pick the smallest id to be source source = min(answer.nodes()) #run networkx's Bellman_ford length = nx.single_source_bellman_ford_path_length( answer, source, weight='weight') #run my Bellman_ford my_solution = Bellman_Ford(my_graph) dist, path = my_solution.solver(source) #getting rid of all the node that cannot be reached by the source for k, v in dist.items(): if v == float("inf"): del dist[k] #correctness boolean = boolean and dist == length if boolean: print("Bellman_Ford test passed") else: print("No")
def run(file_path: str, subwayStationNum: int, subwayIndex: int, subwayDict: dict, reverseSubwayDict: dict, D: list, orientation: str = "", destination: str = ""): res_tb = PrettyTable() res_route = "" with open(file_path, encoding='utf-8') as file_object: subwayLinesNum = int(file_object.readline()) for i in range(subwayLinesNum): subwayLineInfo = file_object.readline().rstrip().split(',') subwayLineNo = subwayLineInfo[1] for j in range(3, len(subwayLineInfo), 2): if not subwayLineInfo[j] in subwayDict: subwayDict[subwayLineInfo[j]] = subwayStationNum reverseSubwayDict[subwayStationNum] = subwayLineInfo[j] D.append(Dist(subwayStationNum, float("inf"), False, subwayLineNo, 0)) subwayStationNum += 1 else: continue subwayList = [[] for _ in range(max(subwayDict.values()) + 1)] with open(file_path, encoding='utf-8') as file_object: next(file_object) for i in range(subwayLinesNum): subwayLineInfo = file_object.readline().rstrip().split(',') for j in range(3, len(subwayLineInfo) - 2, 2): subwayList[subwayDict[subwayLineInfo[j]]].append( Station(subwayDict[subwayLineInfo[j + 2]], subwayLineInfo[j + 2], float(subwayLineInfo[j + 1]))) subwayList[subwayDict[subwayLineInfo[j + 2]]].append( Station(subwayDict[subwayLineInfo[j]], subwayLineInfo[j], float(subwayLineInfo[j + 1]))) num_orientation = subwayDict[orientation] route = [destination] if destination != "": num_destination = subwayDict[destination] Dijkstra(subwayList, D, num_orientation) i = num_destination while D[i].previousStationIndex != num_orientation: route.append(reverseSubwayDict[D[i].previousStationIndex]) i = D[i].previousStationIndex route.append(orientation) route.reverse() else: Dijkstra(subwayList, D, num_orientation) res_tb.field_names = ["SubwayLine", "SubwayStation", "Price", "Distance"] for i in range(len(D)): res_tb.add_row([D[i].subwayLineNo, reverseSubwayDict[D[i].index], str(convert(D[i].length)), str(Decimal(D[i].length).quantize((Decimal('0.000'))))]) for i in range(len(route) - 1): res_route = res_route + route[i] + "->" res_route = res_route + route[len(route) - 1] if destination == "": return res_tb else: return res_route
def main(): print("hello world!") g = import_distances() d = Dijkstra(g, 0) t = 4 if d.ispath(t): print(d.dist(t)) print(d.path(t))
def init(graph): MIN_COST_TABLE = dict() try: with open(MAP_FILE_NAME + '.mct', 'r') as f: data = f.read() if data != '': MIN_COST_TABLE = ast.literal_eval(data) except FileNotFoundError: dj = Dijkstra(graph) dj.traverse() MIN_COST_TABLE = dj.paths with open(MAP_FILE_NAME + '.mct', 'w') as f: f.write(str(MIN_COST_TABLE)) return MIN_COST_TABLE
def testShortestPathDijkstra(self): dijkstra = Dijkstra() S1 = 'v1' end = 'v4' D, R1 = dijkstra.dijkstra(self.graph, S1, end) print(D, R1) Path = [] while True: Path.append(end) if end == S1: break end = R1[end] Path.reverse() print(Path)
def find_dists(self, i_val): if i_val == self.k: delta = {} for v in self.v: delta[v] = np.inf return delta # Add source vertex self.g.add_vertex('s') for w in self.A[i_val]: self.g.add_edge('s', w, 0) # Elements not in A[i] subset = self.complement_lists(self.A[0], self.A[i_val]) # Find witnesses delta, path = Dijkstra(self.g.get_graph(), 's') # witnesses = self.find_witnesses(i, subset, path) # Cleanup the graph self.g.remove_vertex('s') return delta
def negative(self): print("test for negative cycle") '''test for correctness''' self.count = 0 for answer, my_graph in zip(self.test_list, self.compare_list): # if the graph has no nodes, break, automatically the same result if len(answer.nodes) > 0: #run my Dijkstra source = min(answer.nodes()) d_solution = Dijkstra(my_graph) d_dist, path = d_solution.solver(source) #run my Bellman_Ford b_solution = Bellman_Ford(my_graph) b_dist, path = b_solution.solver(source) # if the results are different, increment count if d_dist != b_dist: self.count += 1
def find_stretch(self): already_iterated = set() stretch = 0.0 for source in self.org_graph.get_graph().iterkeys(): for target in already_iterated: if target != source: graph_dijk_distance, graph_dijk_preds = Dijkstra( self.org_graph, source) spanner_dijk_distance, spanner_dijk_preds = Dijkstra( self.spanner, source) found_stretch = spanner_dijk_distance[ target] / graph_dijk_distance[target] if found_stretch > stretch: stretch = found_stretch already_iterated.add(source) return stretch
def useDijkstra(inputFile, startingVertex, goalVertex): # Create a bridges object # Modify id and the account information bridges = Bridges(5, "kylebeard", "834033543846") obj = Dijkstra(inputFile, startingVertex, goalVertex) obj.solve() obj.find_path() obj.draw_path() g = obj.get_graph() # Pass the graph object to BRIDGES bridges.set_data_structure(g) # visualize the graph bridges.visualize()
def make_spanner(self): for edge, weight in self.sorted_edges: v, u = edge if not self.spanner.has_vertex(v): self.spanner.add_vertex(v) if not self.spanner.has_vertex(u): self.spanner.add_vertex(u) dijk = Dijkstra(self.spanner, v) if not u in dijk[0] or (self.r_factor * weight) < dijk[0][u]: self.spanner.add_edge(v, u, weight)
def grow_shortest_tree(self, ai, delta): subset = self.complement_lists(self.A[ai], self.A[ai + 1]) for w in subset: new_delta, path = Dijkstra(self.g.get_graph(), w, limit=delta[ai + 1]) for p in path: source = p target = path[p] weight = self.g.get_edge_weight(source, target) self.spanner.add_edge(source, target, weight)
def run(self): self.listenConfiguration() algorithm = self.algorithmType.get() if (algorithm == "A*"): AStarAlgorithm = AStar(self.map,self.startGrid,self.targetGrid,self.isPathVisible,self.screen) return AStarAlgorithm.run() elif (algorithm == "BFS"): BFSAlgorithm = BFS(self.map,self.startGrid,self.targetGrid,self.isPathVisible,self.screen) return BFSAlgorithm.run() elif (algorithm == "DFS"): DFSAlgorithm = DFS(self.map, self.startGrid, self.targetGrid, self.isPathVisible,self.screen) return DFSAlgorithm.run() elif (algorithm == "Dijkstra"): DijkstraAlgorithm = Dijkstra(self.map, self.startGrid, self.targetGrid, self.isPathVisible,self.screen) return DijkstraAlgorithm.run() else: return
def executeAlgorithm(self): if (self.algorithm_type == AlgorithmTypeEnum.DIJKSTRA): # in the case for dijkstra we have to run the procedure twice for index in range(len(self.localizations)): d = Dijkstra() # Execute dijkstra with builin heap sort d.dijkstraWithBuiltinHeap(self.graph, self.localizations[index], self.emergency) D, P = d.dijkstra(self.graph, self.localizations[index], self.emergency) self.distances[self.localizations[index]] = D self.routes[self.localizations[index]] = P elif (self.algorithm_type == AlgorithmTypeEnum.FLOYD): floyd_warshall = FloydWarshall() self.distances, self.routes = floyd_warshall.pathReconstruction(self.graph)
def gen_graph(self): rand = Random() margin = self.density * sys.maxint coherent = False while not coherent: self.graph = Graph() for v in xrange(0, self.vertices): v = "v" + v.__str__() self.graph.add_vertex(v) for u in self.graph.get_vertices(): if margin >= rand.randint(0, sys.maxint) and v != u: self.graph.add_edge(v, u, rand.randint(1, 999)) if len(Dijkstra(self.graph, "v0")[0]) == self.vertices: coherent = True
def identify_pathfinder(name): if name == "Depth-First Search": solver = DFS(grid, int(start_x), int(start_y), int(end_x), int(end_y), screen) solver.agenda.append(grid[int(start_x)][int(start_y)]) elif name == "Breadth-First Search": solver = BFS(grid, int(start_x), int(start_y), int(end_x), int(end_y), screen) solver.agenda.append(grid[int(start_x)][int(start_y)]) elif name == "Dijkstra's Algorithm": solver = Dijkstra(grid, int(start_x), int(start_y), int(end_x), int(end_y), screen) elif name == "A* Pathfinder": solver = AStarPathfinder(grid, int(start_x), int(start_y), int(end_x), int(end_y), screen) return solver
def main(): vertexes, edges, interval = ReadInput("input") g = Graph() g.addVertexes(*vertexes) g.addEdges(*edges) short_path, walk_cost = Dijkstra(g,interval[0],interval[1]) rt = "\n Path: " for i in range(len(short_path)-1): rt += "{} ~ ".format(short_path[i]) rt+= "{}\n Cost: {}\n".format(short_path[i+1],walk_cost) print(rt)
def KesimoMinimo(w, k): n = len(w)-1 #determinar o caminho mínimo C_1(j), o numero de arestas |C_1(j)| e o comprimento c_1(j) de v_1 para cada v_j c = [None]*(k+1) for i in range(1,k+1): c[i] = [0]*(n+1) (c[1],T) = Dijkstra(w) #determinar a ordenação ORD_1 dos vértices v_j, segundo valores não decrescentes dos números de arestas |C_1(j)| ORD_1 = [] for i in range(1,n+1): TamC1 = 1; t = T[i] while t != None: TamC1 += 1; t = T[t] ORD_1.append((TamC1, i)) for j in range(len(ORD_1)-1, 0, -1): if ORD_1[j][0] < ORD_1[j-1][0]: ORD_1[j],ORD_1[j-1] = ORD_1[j-1],ORD_1[j] ORD_1 = [ORD_1[i][1] for i in range(len(ORD_1))] Hashtag = [None]*(n+1) for i in range(1,n+1): Hashtag[i] = [0]*(n+1) Hashtag[1][1] = 1 for j in range(2, n+1): Hashtag[T[j]][j] = 1 for klin in range(2,k+1): for j in ORD_1: minV = float("inf") for i in range(1,n+1): if i != j: kest = Hashtag[i][j] if c[kest+1][i] + w[i][j] < minV: minV = c[kest+1][i] + w[i][j] ultima = (i,j) c[klin][j] = minV Hashtag[ultima[0]][ultima[1]] = Hashtag[ultima[0]][ultima[1]] + 1 return c[k]
def rutas_seguras(lista_aristas): G=Grafo() G.agregar_lista_aristas(lista_aristas) G_aux=Grafo() # G_aux es el grafo que se obtiene del grafo G de entrada cambiando el peso w de cada arista por -log(w) for vertice in G.vertices: G_aux.vertices.add(vertice) for vertice in G.lista_adyacencia: vecinos_aux=set() for arista in G.lista_adyacencia[vertice]: nueva_arista=(arista[0], -math.log(arista[1])) vecinos_aux.add(nueva_arista) G_aux.lista_adyacencia[vertice]=vecinos_aux D = Dijkstra(0, G_aux) # D es el diccionario obtenido con el algoritmo de Dijkstra, #cuyos elementos son de la forma (vertice, predecesor, distancia a 0) aplicado a G_aux Caminos=dict() for vertice in D: Caminos[vertice]=camino_minimo(0, vertice, D) for vertice in D: print (vertice, Caminos[vertice], math.exp(-D[vertice][1]))
def test(self): djk = Dijkstra(10) # test data source = 1 destination = 5 djk.adjacency_matrix[1][2] = djk.adjacency_matrix[2][1] = 2 djk.adjacency_matrix[1][4] = djk.adjacency_matrix[4][1] = 1 djk.adjacency_matrix[2][3] = djk.adjacency_matrix[3][2] = 4 djk.adjacency_matrix[2][5] = djk.adjacency_matrix[5][2] = 5 djk.adjacency_matrix[3][5] = djk.adjacency_matrix[5][3] = 1 djk.adjacency_matrix[3][4] = djk.adjacency_matrix[4][3] = 3 djk.dijkstra(source) djk.pathPrint(destination) self.assertEqual(djk.sortestPath, [1, 4, 3, 5], msg="Path Should be [1,4,3,5]")
def update_routing_table(self): routingTable_update = Dijkstra(source=self.id, graph=self.LSDB) remove_keys = [] for i in self.routingTable.keys(): if i not in routingTable_update.keys(): remove_keys.append(i) for key in remove_keys: self.routingTable.pop(key) while True: for id in routingTable_update.keys(): if routingTable_update[id][ 1] not in self.neighbor_routers_id and routingTable_update[ id][1] != self.id: routingTable_update[id][1] = routingTable_update[ routingTable_update[id][1]][1] flag_break = True for id in routingTable_update.keys(): if routingTable_update[id][ 1] not in self.neighbor_routers_id and routingTable_update[ id][1] != self.id: flag_break = False if flag_break: break for id in routingTable_update.keys(): if routingTable_update[id][1] == self.id: link = self.Links[id] self.routingTable[id] = self.link_to_interface[link] continue if id not in self.routingTable.keys(): self.routingTable[id] = self.routingTable[ routingTable_update[id][1]] elif self.routingTable[id] != self.routingTable[ routingTable_update[id][1]]: self.routingTable[id] = self.routingTable[ routingTable_update[id][1]]
# ダイクストラでstartから各町についての最短時間、各町からstartまでの最短時間を求め、 # 残り時間で稼げる金額の最大値を求めれば良い ''' 2 2 5 1 3 1 2 2 2 1 1 ''' from Dijkstra import Dijkstra import numpy as np N, M, T = map(int, input().split()) A = list(map(int, input().split())) g1 = Dijkstra(n=N) g2 = Dijkstra(n=N) for i in range(M): a, b, c = map(int, input().split()) a, b = a - 1, b - 1 g1.add_edge(a, b, c, undirected=False) g2.add_edge(b, a, c, undirected=False) dist1, prev1 = g1.run(0) dist2, prev2 = g2.run(0) dist = np.array(dist1) + np.array(dist2) remain = np.ones(N) * T - dist res = (remain * np.array(A))[1:].max()
from Dijkstra import Dijkstra,DirectedGraph E = [[(96, 65)], [(64, 99), (82, 120), (3, 100), (19, 87), (51, 85), (96, 112), (85, 108), (87, 98), (16, 57), (80, 98), (55, 115), (9, 68), (46, 87), (90, 57), (56, 57), (0, 118), (57, 66), (7, 70), (27, 120), (18, 110), (75, 110), (20, 114), (72, 104), (30, 109), (58, 111), (4, 65), (37, 79), (45, 112)], [(24, 88), (91, 67), (58, 112), (13, 52), (72, 70), (15, 97), (36, 75), (52, 71), (31, 78), (76, 109), (26, 78), (29, 101), (32, 109), (65, 117), (22, 53), (96, 119), (30, 77), (2, 77), (6, 115), (71, 122)], [(75, 48), (21, 80), (32, 119), (61, 48), (13, 57), (82, 97), (55, 88), (50, 121), (77, 83), (70, 114), (96, 83), (38, 72), (74, 51), (34, 80), (28, 102), (78, 116), (66, 53), (89, 107), (11, 54), (54, 100), (48, 72), (64, 112), (76, 104)], [(63, 66), (49, 55), (80, 79), (31, 122), (1, 67), (6, 89), (86, 100), (57, 49), (29, 67), (20, 81), (97, 48), (44, 70), (8, 73), (85, 100)], [(38, 55), (5, 119), (97, 68), (10, 72), (11, 106), (35, 106), (73, 83), (17, 115), (7, 106), (60, 52)], [(98, 113), (82, 52), (38, 118), (15, 48), (63, 97), (47, 120), (73, 89), (58, 67), (67, 78), (9, 75), (70, 78), (7, 83)], [(99, 104), (22, 77), (79, 51)], [(46, 72), (42, 79), (57, 51), (59, 89), (41, 90), (19, 75), (14, 88), (33, 86), (13, 107), (20, 121), (48, 115), (45, 99), (25, 54)], [(22, 108), (58, 83), (67, 50), (17, 105), (5, 112), (84, 88), (1, 120), (20, 119), (50, 106), (87, 51), (25, 118), (40, 54), (16, 120), (75, 122)], [(28, 65), (83, 119), (84, 48), (6, 84), (68, 87), (87, 72), (12, 88), (30, 72), (34, 68), (16, 103), (5, 68), (89, 116), (95, 82), (44, 88), (77, 114), (41, 49), (55, 79), (14, 87), (23, 90), (81, 76), (27, 106), (60, 76)], [(36, 74), (15, 69), (16, 49), (85, 83), (53, 118), (91, 52), (31, 76), (28, 82), (3, 55), (89, 86), (47, 68)], [(87, 110), (62, 89), (27, 114), (5, 51), (37, 120), (91, 65), (74, 72), (42, 75), (29, 112), (52, 69)], [(64, 72), (58, 73), (37, 116), (2, 66), (30, 48), (17, 69), (73, 67), (97, 82), (93, 48), (24, 71), (26, 51)], [(98, 52), (43, 100), (71, 98), (51, 56), (66, 95), (52, 75), (29, 65)], [(29, 100), (60, 71), (12, 115), (86, 66), (43, 73), (22, 84), (55, 50), (70, 109), (8, 101), (49, 89), (54, 108), (17, 100), (96, 52), (88, 66), (87, 111), (14, 95), (72, 68), (36, 66), (65, 107), (23, 55), (79, 106), (62, 68), (25, 100), (10, 122), (33, 56), (97, 82), (51, 67), (68, 68)], [(17, 66), (56, 51), (76, 73), (18, 100), (26, 65), (9, 95), (77, 76), (5, 118), (72, 102), (53, 105), (44, 105), (38, 108), (80, 101), (83, 115), (59, 80), (58, 107), (27, 103)], [(89, 85), (81, 49), (41, 85), (52, 121), (59, 87), (96, 117), (10, 70), (2, 101), (68, 99)], [(46, 48), (18, 110), (72, 79)], [(85, 98), (84, 65), (27, 56), (82, 54), (90, 112), (91, 85), (46, 65), (44, 87), (32, 82), (50, 115)], [(29, 102), (72, 97), (82, 80), (4, 83), (41, 68), (5, 73), (71, 104), (2, 78), (70, 68), (88, 121), (26, 56), (56, 117), (25, 82), (15, 85), (67, 106), (8, 108), (38, 80), (10, 73), (77, 111), (28, 72), (66, 71), (24, 73), (30, 85), (42, 57), (61, 102), (60, 110), (31, 51), (96, 82)], [(44, 66), (56, 75), (9, 89), (30, 69), (35, 78), (10, 65), (28, 79), (68, 51), (37, 111), (72, 88), (81, 102), (11, 111)], [(22, 105), (89, 105), (96, 104), (92, 103)], [(83, 97), (16, 86), (37, 67), (70, 117), (56, 83), (2, 65), (68, 85), (88, 70), (50, 54), (31, 68), (18, 115), (42, 79), (90, 48), (92, 88), (86, 86), (6, 68), (55, 119), (3, 111), (64, 56), (72, 101), (24, 52), (22, 72), (0, 106), (53, 50), (34, 106)], [(19, 108), (9, 87), (25, 112), (37, 48), (54, 82), (87, 118), (15, 101), (56, 75), (46, 102), (61, 54), (92, 115), (78, 97), (85, 106), (65, 49), (30, 68), (96, 65), (58, 65), (47, 117), (88, 74), (1, 73), (64, 86), (74, 115), (81, 79), (83, 103), (89, 113), (82, 66), (21, 104), (24, 55)], [(40, 80), (85, 55), (97, 77), (30, 89), (72, 71), (58, 68), (22, 56)], [(48, 74), (77, 49), (18, 119), (41, 78), (90, 112)], [(53, 107), (58, 82), (83, 71), (4, 82), (3, 115), (56, 122), (40, 68), (54, 108), (78, 81), (24, 53), (0, 72), (82, 118), (59, 54), (62, 89), (48, 79), (73, 120), (92, 110), (36, 55), (44, 81), (45, 98), (30, 51), (10, 50)], [(9, 120), (92, 49), (82, 68), (76, 86), (11, 80), (60, 78), (29, 120), (0, 102)], [(59, 67), (80, 113), (52, 110), (68, 75), (32, 106), (86, 98), (39, 55), (89, 103), (29, 111), (50, 68), (76, 102), (63, 80), (43, 90), (37, 83), (5, 48), (51, 79), (7, 118), (46, 49), (73, 67), (78, 89), (49, 67), (90, 51)], [(79, 95), (58, 115), (30, 115), (87, 55)], [(91, 122), (18, 113), (2, 105), (89, 110), (10, 111), (15, 117), (24, 119), (53, 114), (59, 87), (51, 115), (78, 70), (46, 70), (82, 95), (1, 102), (31, 87), (81, 57), (61, 75), (66, 77), (52, 121), (95, 79), (22, 100), (42, 83), (25, 52), (16, 67)], [(73, 107)], [(75, 84), (71, 78), (15, 99), (33, 99), (45, 113), (89, 65), (53, 101), (70, 85), (64, 100), (81, 73), (62, 72), (12, 101)], [(3, 119), (43, 86), (41, 90), (30, 76), (24, 67), (9, 80), (68, 111), (10, 121), (79, 117), (83, 108), (45, 83), (94, 67), (26, 102), (62, 79)], [(94, 51), (85, 69), (96, 74)], [(19, 97), (60, 48), (6, 100)], [(77, 117), (66, 119), (91, 112), (93, 72), (98, 89), (33, 69), (86, 110), (40, 54), (54, 100), (10, 77), (48, 99), (16, 109), (76, 72), (65, 74), (41, 90), (90, 82), (18, 69), (61, 114), (59, 56), (85, 101), (46, 81), (83, 69), (53, 50), (56, 101), (49, 79), (2, 54)], [(85, 52), (48, 95), (55, 118)], [(24, 72), (6, 72), (77, 97), (36, 82), (26, 65), (37, 90), (54, 118), (41, 51), (8, 121), (85, 105), (38, 72), (46, 80), (15, 105), (80, 111), (65, 122), (86, 73), (1, 75), (97, 89), (53, 82), (64, 53), (35, 95), (30, 104)], [(30, 121), (92, 73), (22, 69), (18, 69), (41, 97)], [(35, 67), (70, 86), (97, 69), (7, 84)], [(21, 110), (26, 107), (73, 115), (93, 71), (67, 104), (80, 110), (35, 68), (41, 87), (7, 108), (90, 53), (76, 114), (69, 65), (86, 101), (70, 87), (94, 53), (42, 70)], [(29, 75), (55, 102), (2, 82), (82, 105), (92, 56), (26, 122), (27, 105), (7, 66), (58, 108)], [(35, 53), (28, 69), (91, 102), (21, 83), (89, 71), (41, 108), (69, 100), (94, 77), (25, 70), (93, 53), (50, 85), (6, 87), (34, 86), (85, 84), (38, 79), (12, 82), (57, 53), (72, 66), (11, 115), (79, 112), (83, 108)], [(1, 57), (7, 87), (49, 67), (77, 104), (73, 87), (14, 99), (41, 79), (63, 109), (64, 55)], [(72, 101), (18, 109), (22, 95)], [(44, 68), (26, 98), (71, 100), (10, 84), (2, 75), (39, 107), (76, 103), (77, 65), (14, 101), (19, 69), (62, 120), (86, 101), (34, 57), (18, 74), (90, 121), (7, 56), (83, 105), (56, 109), (69, 51), (60, 104), (96, 100)], [(44, 72), (37, 89), (95, 77), (66, 72), (52, 65), (27, 118), (14, 120), (82, 57), (67, 118), (55, 88), (49, 82), (48, 65), (59, 117), (30, 84), (7, 104), (92, 102), (26, 115), (16, 121), (3, 87), (34, 81), (77, 53)], [(80, 86), (77, 75), (28, 122), (0, 121)], [(28, 84), (44, 74), (86, 108), (54, 97), (7, 51), (52, 98), (79, 49), (55, 109), (98, 72), (32, 52), (12, 115), (23, 112), (29, 106), (42, 86), (92, 112), (84, 90), (78, 120), (0, 110), (59, 118), (90, 83), (34, 78)], [(96, 55), (6, 86), (1, 99), (60, 82), (90, 69), (24, 51), (27, 48), (17, 102), (15, 75), (71, 114), (0, 74)], [(65, 89), (74, 102)], [(90, 49), (89, 100), (86, 88), (79, 50), (0, 90), (71, 82), (75, 69), (85, 101), (88, 88), (53, 108), (81, 70), (67, 111), (56, 109), (40, 55), (55, 56), (14, 68), (2, 97), (35, 54), (48, 105), (11, 122), (43, 103), (23, 57), (61, 49), (95, 53), (68, 52), (7, 111), (62, 116), (59, 52), (46, 52)], [(47, 84)], [(31, 119), (80, 53), (13, 57), (33, 83), (63, 68), (85, 116), (35, 103), (87, 82), (32, 54), (92, 89), (56, 115)], [(88, 66), (79, 100), (25, 69)], [(61, 110), (73, 103), (17, 77), (14, 66), (88, 103), (45, 82), (32, 56), (79, 50), (92, 106), (60, 87), (3, 73), (87, 81), (44, 79)], [(82, 114)], [(74, 53)], [(34, 89), (64, 114), (80, 71), (83, 53), (68, 98), (60, 115), (82, 70), (88, 119), (28, 52), (62, 74), (11, 100), (25, 87), (59, 52), (95, 79)], [(6, 80)], [(0, 122), (95, 51), (48, 53), (59, 108)], [(41, 77), (58, 55), (57, 50), (59, 121), (68, 77), (93, 48), (80, 113), (9, 76), (21, 66), (96, 66), (79, 89), (32, 86), (55, 78), (31, 116), (47, 97), (15, 90), (82, 80)], [(55, 76), (95, 75), (15, 86), (17, 83), (53, 55), (2, 81)], [(55, 118), (71, 87), (20, 79), (69, 99), (97, 56), (12, 79), (56, 87)], [(18, 89), (86, 117), (66, 77), (4, 85), (7, 66), (47, 114), (88, 71), (16, 86), (77, 75), (95, 112), (19, 104), (48, 65), (96, 78), (51, 54), (81, 81), (41, 66), (11, 116), (33, 115), (13, 54), (87, 57), (10, 89), (68, 104), (53, 78), (12, 51), (8, 115), (59, 56), (5, 113), (57, 108), (14, 107), (82, 70)], [(63, 67), (59, 81), (58, 85)], [(66, 110), (25, 85), (85, 69), (40, 80), (94, 90), (10, 113), (68, 70), (47, 53), (87, 68), (52, 78), (80, 107), (55, 70), (30, 108), (58, 73)], [(96, 116), (89, 95)], [(69, 70)], [(57, 107), (58, 82), (77, 86), (36, 107), (11, 111), (84, 108), (29, 75), (5, 100), (43, 119), (13, 104), (69, 121), (25, 85), (68, 51), (93, 89), (76, 98), (49, 69), (23, 90), (90, 99), (78, 79), (3, 87), (87, 122), (15, 121), (18, 71)], [(70, 84)], [(58, 48), (36, 83), (0, 97), (65, 74), (90, 111)], [(69, 112), (79, 108), (97, 104)], [(12, 102), (88, 102), (62, 49), (5, 105), (36, 67), (38, 72), (44, 115), (47, 79), (86, 69), (30, 88), (20, 83), (89, 95), (25, 119), (65, 55), (75, 110), (93, 72), (21, 98), (54, 80), (90, 52), (69, 72), (15, 70), (40, 71), (32, 86), (14, 113), (71, 117)], [(17, 73), (31, 104)], [(51, 117), (5, 52), (11, 100), (16, 117), (80, 70), (85, 67)], [(94, 95), (14, 55), (59, 76)], [(70, 107), (79, 48), (59, 95)], [(50, 76), (72, 50), (64, 72), (7, 85), (77, 112), (3, 106), (91, 115), (55, 55), (57, 55), (49, 54)], [(76, 82), (83, 107), (4, 122), (79, 68), (59, 81), (34, 73), (14, 69), (30, 81), (10, 103), (67, 54), (50, 52), (54, 122), (7, 90), (97, 110), (2, 67)], [(58, 77), (94, 55), (35, 55)], [(23, 65), (41, 52), (48, 76), (83, 99), (26, 116), (16, 76), (57, 121), (2, 100), (18, 53), (87, 53), (21, 66), (66, 108), (72, 88), (91, 103), (63, 105), (9, 89), (11, 102), (67, 72), (96, 101), (1, 55), (39, 108), (28, 108), (12, 72), (54, 55), (89, 105)], [(85, 108), (88, 54), (22, 68), (59, 49)], [(30, 53), (35, 99), (79, 107), (46, 109)], [(61, 121), (22, 121), (91, 119), (2, 77), (71, 78), (66, 48), (14, 116), (79, 82)], [(69, 103), (87, 113), (82, 105), (25, 95), (18, 116), (70, 118)], [(79, 86), (32, 115), (51, 66), (96, 112), (52, 114)], [(72, 122), (18, 71), (96, 106)], [(46, 79), (76, 82), (61, 57), (69, 107), (18, 110), (96, 114), (82, 110)], [(66, 105), (41, 114), (62, 77), (59, 68), (50, 81), (92, 77), (19, 106), (43, 97), (20, 67), (40, 56), (55, 102), (76, 103), (47, 74), (37, 100), (88, 65), (39, 71), (16, 83), (35, 110), (14, 115), (94, 80), (22, 49), (81, 103), (0, 83), (65, 73), (70, 112), (17, 116), (77, 57), (7, 67)], [(79, 111)], [(75, 70), (33, 120), (24, 87), (93, 54), (83, 106), (1, 68), (49, 100), (30, 51), (90, 55), (12, 50), (29, 118), (80, 121), (21, 86), (66, 115), (45, 85), (56, 83), (91, 65), (67, 105), (78, 105), (88, 122), (87, 99), (0, 108), (94, 95), (79, 67), (76, 69), (46, 82), (84, 97), (3, 79), (5, 108)], [(72, 67)], [(41, 65), (42, 98), (36, 108), (82, 113), (37, 101), (18, 115), (9, 105), (77, 102), (34, 111), (83, 86), (70, 73)], [(94, 68)], [(58, 79), (79, 57)], [(67, 50), (19, 107), (93, 51), (69, 74), (60, 118), (46, 77), (2, 90), (86, 66), (84, 51), (30, 118), (32, 56), (63, 86), (51, 97), (98, 103)], []] graph = [] for i in range(len(E)): for e in E[i]: graph += [(str(i),str(e[0]),e[1])] graph = DirectedGraph.build(graph) Dijkstra.process(graph, '0') c = 0 flag='' for node in graph.shortest_path('99'): flag+=chr(node.cost-c) c = node.cost print flag raw_input('Press any key to exit...')
json_dict = json.loads(data1) name = json_dict['id'] x = json_dict['x'] y = json_dict['y'] dist = math.sqrt((x * x) + (y * y)) if dist > 50: dist = -1 x2 = 20 y2 = 10 dist2 = math.sqrt((x2 * x2) + (y2 * y2)) dist3 = math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y)) name2 = 'car2' graph = { 'base': { name: dist, name2: dist2 }, name: { 'base': dist, name2: dist3 }, name2: { 'base': dist2, name: dist3 } } Dijkstra(graph, name, 'base') print("Data processed...") # Sending reply # conn.send(reply.encode()) conn.close() # Close connections
from Dijkstra import Dijkstra dijkstra = Dijkstra("nodes.csv", 1) dijkstra.solve() print(dijkstra.getOptimalPath(14)) print(dijkstra.getOptimalDistance(14))
import networkx as nx from DataHelper import DataHelper from Dijkstra import Dijkstra data = DataHelper.read_data("data//graph.txt") graph = nx.DiGraph() graph.add_weighted_edges_from(data) dijkstra = Dijkstra(graph) print(dijkstra.dijkstra_shortest_path(1, 20))
animate(solution[2]) print("Unreachable goal.") else: path, search = solution[0], solution[1] end = time() print("It took {} seconds to solve.".format(end - start)) animate(search) animatePath(path) pygame.time.wait(3000) # Use Dijkstra to solve for path else: start = time() dijkstra = Dijkstra([int(coordinates[0][0] / multiplier), int(200 - coordinates[0][1] / multiplier)], [int(coordinates[1][0] / multiplier), int(200 - coordinates[1][1] / multiplier)], clearance) solution = dijkstra.solve() pygame.init() display = pygame.display.set_mode((width, height)) pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 10 * multiplier) ticks = 400 clock = pygame.time.Clock() if len(solution) == 3: animate(solution[2]) print("Unreachable goal.") else: path, search = solution[0], solution[1] end = time() print("It took {} seconds to solve.".format(end - start))
from DenseGraph import DenseGraph from ReadGraph import read_graph from SparseGraph import SparseGraph from LazyPrimMST import LazyPrimMST from PrimMST import PrimMST from KruskalMST import KruskalMST from Dijkstra import Dijkstra if __name__ == '__main__': graph = SparseGraph(5, True) read_graph(graph, 'testG1.txt') tmp = Dijkstra(graph, 0) for i in range(5): tmp.show_path(i)
from Graph import Graph from Dijkstra import Dijkstra from Floyd import Floyd from Prima import Prima from Kruskal import Kruskal if __name__ == "__main__": g = Graph("in.txt", False) d = Dijkstra(g) f = Floyd(g) p = Prima(g) k = Kruskal(g) d.run(0) f.run() p.run() k.run()
def main(): # assumes degree input in increments of 5 # x,y,V,A,B,rV,D,dw ''' velocities = [2] rotationalVelocities = [15,30,45,90,180] dynamicWindows = [0.5,1,1.5,2] for velocity in velocities: for rotational in rotationalVelocities: for dynamic in dynamicWindows: print" v: %s, r: %s, dw: %s" % (velocity, rotational, dynamic) startTime = time.time() robot = PointRobot(0,0,velocity,1,1,rotational,90,dynamic) #print robot.toString() obstacleList = initializeObstacles() #print "calculating coordinates" coordinatesTuple = robot.calcCoordinatesReachable(obstacleList) tupleList = coordinatesTuple[0] # list of reachable tuples behindObstacleList = coordinatesTuple[1] # list of tuples behind obstales #print "tuple list: %s" %tupleList xList = [] yList = [] for t in tupleList: #print "x: %f, y: %f" % (t[0], t[1]) xList.append(t[0]) yList.append(t[1]) #print "xList : %s" % xList #print "yList: %s" % yList oxList = [] oyList = [] for t in behindObstacleList: oxList.append(t[0]) oyList.append(t[1]) # find unreachable points via dijskstra's algorithm unreachableCoordinates = [] d = Dijkstra(unreachableCoordinates) vertexList = d.genVertices(tupleList) #print "initializing vertices behind obstacles" verticesBehindObstacles = [] for v in vertexList: for t in behindObstacleList: if ((v.x == t[0]) and (v.y == t[1])): verticesBehindObstacles.append(v) #print "vertices behind obstacles initialized" #print "calculating edges" pathList = d.genPaths(vertexList,obstacleList) #print "edges calculated" # select m nearest neighbors for each vertex #print "generating nearest neighbors" startVertex = Vertex(0,0) vertexList.append(startVertex) for v in vertexList: v.genNearestNeighbors(pathList,3) for v in verticesBehindObstacles: v.genNearestNeighbors(pathList,3) #for n in v.nNL: # print "nearest neighbor list: %s" % n.toString() #startVertex.genNearestNeighbors(pathList, 3) #print "nearest neighbors generated" vi = robot.tV # initial velocity a = robot.tA t = robot.dw # length of time is just length of dynamic window vf = vi + a * t # final velocity # max distance that can be traveled maxDistance = ((vi + vf)/2)*t #print "running dijkstras on vertices behind obstacles" for v in verticesBehindObstacles: #print "v: %s" % v.toString() #for n in v.nNL: # print "nearest neighbor list: %s" % n.toString() d.algorithm(pathList,startVertex,v) if (v.distance > maxDistance): #print "v: %s" % v.toString() d.unreachableCoordinates.append(v) #print "unreachable: %s " % v.toString() #for n in v.nNL: # print "unreachable's nearest neighbor list: %s" % n.toString() #print "dijkstras complete" # unreachable vertices uxList = [] uyList = [] for v in unreachableCoordinates: uxList.append(v.x) uyList.append(v.y) # plots edges (takes a while) #for e in pathList: #print "v0x (%s), v0y (%s), v1x (%s), v1y (%s)" % (e.vertex0.x, e.vertex0.y, e.vertex1.x, e.vertex1.y) #x0 = e.vertex0.x #y0 = e.vertex0.y #x1 = e.vertex1.x #y1 = e.vertex1.y #plt.plot([x0,x1],[y0,y1],color = 'k') ''' ''' print "plotting coordinates" direct = plt.plot(xList,yList,'go') around = plt.plot(oxList,oyList,'yo') unreachable = plt.plot(uxList,uyList,'ro') plt.ylabel('y') plt.xlabel('x') plt.title("reachable coordinates") plt.axis([min(xList),max(xList) , min(yList), max(yList)]) #plt.legend([direct,around,unreachable], ["straight path", "around obstacle", "unreachable"]) #plt.axis([0,2 , 0, 2]) plt.show() print "plotting complete" ''' ''' totalTime = time.time() - startTime print "total time: %f" % totalTime ''' robot = PointRobot(0,0,1,1,1,45,90,1) #print robot.toString() obstacleList = initializeObstacles() print "calculating coordinates" coordinatesTuple = robot.calcCoordinatesReachable(obstacleList) tupleList = coordinatesTuple[0] # list of reachable tuples behindObstacleList = coordinatesTuple[1] # list of tuples behind obstales print "tuple list: %s" %tupleList xList = [] yList = [] for t in tupleList: #print "x: %f, y: %f" % (t[0], t[1]) xList.append(t[0]) yList.append(t[1]) #print "xList : %s" % xList #print "yList: %s" % yList oxList = [] oyList = [] for t in behindObstacleList: oxList.append(t[0]) oyList.append(t[1]) # find unreachable points via dijskstra's algorithm unreachableCoordinates = [] d = Dijkstra(unreachableCoordinates) vertexList = d.genVertices(tupleList) ''' print "initializing vertices behind obstacles" verticesBehindObstacles = [] for v in vertexList: for t in behindObstacleList: if ((v.x == t[0]) and (v.y == t[1])): verticesBehindObstacles.append(v) print "vertices behind obstacles initialized" ''' print "calculating edges" pathList = d.genPaths(vertexList,obstacleList) print "edges calculated" ''' # select m nearest neighbors for each vertex print "generating nearest neighbors" startVertex = Vertex(0,0) vertexList.append(startVertex) for v in vertexList: v.genNearestNeighbors(pathList,3) for v in verticesBehindObstacles: v.genNearestNeighbors(pathList,3) #for n in v.nNL: # print "nearest neighbor list: %s" % n.toString() #startVertex.genNearestNeighbors(pathList, 3) print "nearest neighbors generated" vi = robot.tV # initial velocity a = robot.tA t = robot.dw # length of time is just length of dynamic window vf = vi + a * t # final velocity # max distance that can be traveled maxDistance = ((vi + vf)/2)*t print "running dijkstras on vertices behind obstacles" for v in verticesBehindObstacles: #print "v: %s" % v.toString() #for n in v.nNL: # print "nearest neighbor list: %s" % n.toString() d.algorithm(pathList,startVertex,v) if (v.distance > maxDistance): print "v: %s" % v.toString() d.unreachableCoordinates.append(v) #print "unreachable: %s " % v.toString() #for n in v.nNL: # print "unreachable's nearest neighbor list: %s" % n.toString() print "dijkstras complete" ''' ''' # unreachable vertices uxList = [] uyList = [] for v in unreachableCoordinates: uxList.append(v.x) uyList.append(v.y) ''' # plots edges (takes a while) for e in pathList: #print "v0x (%s), v0y (%s), v1x (%s), v1y (%s)" % (e.vertex0.x, e.vertex0.y, e.vertex1.x, e.vertex1.y) x0 = e.vertex0.x y0 = e.vertex0.y x1 = e.vertex1.x y1 = e.vertex1.y plt.plot([x0,x1],[y0,y1],color = 'k') print "plotting coordinates" direct = plt.plot(xList,yList,'go') #around = plt.plot(oxList,oyList,'yo') #unreachable = plt.plot(uxList,uyList,'ro') plt.ylabel('y') plt.xlabel('x') plt.title("reachable coordinates") plt.axis([min(xList),max(xList) , min(yList), max(yList)]) #plt.legend([direct,around,unreachable], ["straight path", "around obstacle", "unreachable"]) #plt.axis([0,2 , 0, 2]) plt.show() print "plotting complete"