def draw_way(screen, graph, points, color_way): way_to_cent, l1 = dijkstra(graph, 0, 1) print('Way from point A to center {}'.format(way_to_cent)) way_to_end, l2 = dijkstra(graph, 1, 2) print('Way from point center to B {}'.format(way_to_end)) way = [] spline_points = [] way.extend(way_to_cent) way.extend(way_to_end[1:]) for i in range(len(way)): spline_points.append(points[way[i]]) spline_points = catmullrom_splines(spline_points) print('Total length with center point: {}'.format(l1 + l2)) for i in range(1, len(way)): draw.line(screen.get_surface(), color_way, points[way[i]], points[way[i - 1]], 2) screen.update() time.sleep(0.1) for i in range(1, len(spline_points)): draw.line(screen.get_surface(), 0x00FF00, spline_points[i - 1], spline_points[i], 4) screen.update() time.sleep(0.005)
def main(): #Sample graph files fileNames = ["graph1.txt", "graph2.txt", "graph3.txt"] file = open(fileNames[2], "r") #---Format of files--- #First row in file contains number of nodes in graph #Rows after first row contain edge info. #Format: start node, end node, distance #Example: 0 3 5 = Edge that goes from vertex 0 to 3 with distance 5 #Populate an adjacency matrix from file am = adjacencyMatrix() i = 0 for line in file: if i == 0: numVertices = int(line) am.create(numVertices) else: dest, source, dist = line.split() dest, source, dist = int(dest), int(source), int(dist) am.addEdge(dest, source, dist) i += 1 #Run Dijkstra's shortest path algorithm on graph d = dijkstra(am, numVertices) d.run(0) d.displaySolution()
def test_simple(self): G = loadGraphFromFile('simple_graph.txt') A = dijkstra(G, 1) self.assertEqual(A[1], 0) self.assertEqual(A[2], 3) self.assertEqual(A[3], 3) self.assertEqual(A[4], 5)
def test_grafo_com_tres_nos_indo_pra_C_por_B(self): grafo = { 'A': ((42, 'B'), (100, 'C')), 'B': ((10, 'C'),), 'C': (), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 52} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def test_grafo_com_tres_nos_indo_pra_C_por_B(self): grafo = { 'A': ((42, 'B'), (100, 'C')), 'B': ((10, 'C'), ), 'C': (), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 52} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def createDurationTrip(): global SDep, SArr, path, costOpti s.build_Vertices( "time") # Construction d'un graphe de parcours avec des poids de duree source = s.g.get_Vertex(SDep) #Exemple a changer getClic1 destination = s.g.get_Vertex(SArr) #Exemple a changer getClic2 dijkstra(s.g, source, destination) costOpti = math.floor(destination.get_Distance() / 60) path = [destination.get_Id()] cheminLePlusCourt(destination, path) for i in path: print(i.name)
def draw_way(screen, graph, points, color_way): way_to_cent, l1 = dijkstra(graph, 0, 1) print('Way from point A to center {}'.format(way_to_cent)) way_to_end, l2 = dijkstra(graph, 1, 2) print('Way from point center to B {}'.format(way_to_end)) way_max, l3 = dijkstra(graph, 0, 2) print('Way from point A to B {}'.format(way_max)) print('Total length with center point: {}'.format(l1 + l2)) print('Total length without center point: {}'.format(l3)) for i in range(1, len(way_to_cent)): draw.line(screen.get_surface(), color_way, points[way_to_cent[i]], points[way_to_cent[i - 1]], 6) for i in range(1, len(way_to_end)): draw.line(screen.get_surface(), color_way, points[way_to_end[i]], points[way_to_end[i - 1]], 6) for i in range(1, len(way_max)): draw.line(screen.get_surface(), 0x00FF00, points[way_max[i]], points[way_max[i - 1]], 3)
def test_grafo_com_quatro_nos_sequenciais(self): grafo = { 'A': ((42,'B'),), 'B': ((10,'C'),), 'C': ((120,'D'),), 'D': (), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 52, 'D': 172} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def test_grafo_com_quatro_nos_sequenciais(self): grafo = { 'A': ((42, 'B'), ), 'B': ((10, 'C'), ), 'C': ((120, 'D'), ), 'D': (), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 52, 'D': 172} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def test_grafo_com_quatro_nos(self): grafo = { 'A': ((42,'B'),(20,'C'),), 'B': ((10,'C'),), 'C': ((120,'D'),), 'D': ((24,'C'),), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 20, 'D': 140} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def get_closest_painting(d_map, location, pictures_lists): shortest_distance = sys.maxsize short_path = None closed_painting = None for painting in pictures_lists: (path, distance) = dijkstra(d_map, location, painting, [], {}, {}) if shortest_distance > distance: shortest_distance = distance short_path = path closed_painting = path[-1] return closed_painting, short_path
def test_larger(self): G = loadGraphFromFile('larger_graph.txt') A = dijkstra(G, 1) self.assertEqual(A[1], 0) self.assertEqual(A[2], 2) self.assertEqual(A[4], 1) self.assertEqual(A[3], 3) self.assertEqual(A[5], 3) self.assertEqual(A[6], 6) self.assertEqual(A[7], 5)
def test_simple_path(self): root = Node(1) n2, n5 = Node(2), Node(5) target = Node(7) n2.add_neighbor(target) n5.add_neighbor(target) root.add_neighbor(n2) root.add_neighbor(n5) path = dijkstra([root, n2, n5, target], root, target) self.assertEqual(value_sum(path), 10)
def subGraphMatrix(fullMatrix, nodesInput): n = len(nodesInput) matrix = [[-1 for j in range(n)] for i in range(n)] for i in range (n): dist = dijkstra(fullMatrix, nodesInput[i], nodesInput) for j in range (len(dist)): for k in range (len(nodesInput)): if(j == nodesInput[k]): matrix[i][k] = dist[j] return matrix
def test_grafo_com_quatro_nos(self): grafo = { 'A': ( (42, 'B'), (20, 'C'), ), 'B': ((10, 'C'), ), 'C': ((120, 'D'), ), 'D': ((24, 'C'), ), } no = 'A' menores_distancias = {'A': 0, 'B': 42, 'C': 20, 'D': 140} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def testDijkstra(self): state_str = '#-\n-b' base, harvester, food, obstacle, defender, enemy, has_food = problem.parse( state_str) state = problem.to_state(base, harvester, food, obstacle, defender, enemy, has_food) world = problem.to_problem(x=2, y=2) policy = dijkstra((1, 1), state, world) self.assertEquals(policy, { (0, 1): ((1, 1), 1), (1, 0): ((1, 1), 1), (1, 1): ('*', 0) }, policy)
def get_shortest_paths_for_all_nodes(g,cur_id,distance_dict,edge_dict): edge_dict[cur_id]=[] distance_dict[cur_id]=dict() #get shortest path from each node to all other nodes; for i in list(g.nodes.keys()): connections_i=g.edges[i] for c in connections_i: edge_dict[cur_id].append((i,c)) for j in list(g.nodes.keys()): if i==j: continue shortest_path_i_j,length_shortest_path_i_j=dijkstra(g,i,j) distance_dict[cur_id][(i,j)]=length_shortest_path_i_j return distance_dict,edge_dict
def lsdb_to_graph(): # ("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), # ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), # ("e", "f", 9)]) data = request.get_json() if data: start = data[0] dest = data[1] if data: shortest_path = dijkstra(start, dest) return jsonify(shortest_path) else: return ""
def test_bidirectional_links(self): root = Node(1) n2, n5 = Node(2), Node(5) target = Node(7) root.add_neighbor(n2) n2.add_neighbor(root) root.add_neighbor(n5) n5.add_neighbor(root) n2.add_neighbor(target) target.add_neighbor(n2) n5.add_neighbor(target) target.add_neighbor(n5) path = dijkstra([root, n2, n5, target], root, target) self.assertEqual(value_sum(path), 10)
def invalidinput_test(): with pytest.raises(InvalidInputException): g = None src = GraphVertex("src") dijkstra(g,src) with pytest.raises(InvalidInputException): g = MyGraph() src = None dijkstra(g,src) with pytest.raises(InvalidInputException): g = MyGraph() src = GraphVertex("src") dijkstra(g,src)
def shortpath_test(): g = MyGraph() v0 = GraphVertex("v0") v1 = GraphVertex("v1") v2 = GraphVertex("v2") g.insertVertex(v0) g.insertVertex(v1) g.insertVertex(v2) e0 = GraphEdge("e0", 8) e1 = GraphEdge("e1", 3) e2 = GraphEdge("e2", 4) g.insertEdge(v0, v2, e0) g.insertEdge(v0, v1, e1) g.insertEdge(v1, v2, e2) ret = dijkstra(g, v0) assert e1 in ret.edges() assert e2 in ret.edges() assert e0 not in ret.edges()
def lcp_print(): start_lcp = time.time() global net_graph #print ('all_nodes : {}'.format(all_nodes)) while True: if time.time() - start_lcp >= 30: paths = dijkstra(node_ID, net_graph) all_nodes = net_graph.getNodes() for n in net_graph.getNodes(): #print ('claculating shortest path for {}'.format(n)) if n != node_ID: short_path_list = shortest_path(node_ID, n, paths) + [ n, ] short_path = ''.join(short_path_list) cost = cost_path(short_path_list, net_graph) #print (node_ID) print('least-cost path to node {}: {} and the cost is {}'. format(n, short_path, cost)) start_lcp = time.time()
def split_odd_graph(graph, odd_vert): path_list = [] edge_list = [] odd_G = [] # search in every pair of odd vertexes: distances from source to sink and path between them for vert in odd_vert: # odd_graph_dist, path = dijkstra(odd_graph_list, vert) odd_graph_dist, path = dijkstra(graph, vert) path_list.append(path) edge = [(path[i][0], path[i][-1]) for i in range(len(path))] edge_list.append(edge) odd_G.append(odd_graph_dist) edge_odd_list = [ val for sublist in edge_list for val in sublist] weight_odd_list = [ val for sublist in odd_G for val in sublist] path_odd_list = [ val for sublist in path_list for val in sublist] return edge_odd_list, weight_odd_list, path_odd_list
def run_algorithm(self, algo): """ Main algorithm function. :param algo: String, choosen algorithm :return: None """ #Breadth-first search algorithm if algo == 'bfs': cf, hbxt = bfs(self.start_tile, self.end_tile) #Dijkstra's algorithm elif algo == 'dijkstra': cf, csf, hbxt = dijkstra(self.start_tile, self.end_tile) self.cost = csf[self.end_tile] #A* algorithm elif algo == 'a_star': cf, csf, hbxt = a_star(self.start_tile, self.end_tile) self.cost = csf[self.end_tile] self.draw_paths(cf, hbxt, algo)
def simple_test(): # Setup simple graph g = MyGraph() v0 = GraphVertex("v0") v1 = GraphVertex("v1") v2 = GraphVertex("v2") g.insertVertex(v0) g.insertVertex(v1) g.insertVertex(v2) e0 = GraphEdge("e0", 8) e1 = GraphEdge("e1", 3) e2 = GraphEdge("e2", 4) g.insertEdge(v0, v2, e0) g.insertEdge(v0, v1, e1) g.insertEdge(v1, v2, e2) # Run the algorithm ret = dijkstra(g, v0) # Make sure it matches our expectations assert e1 in ret.edges() assert e2 in ret.edges() assert e0 not in ret.edges()
def drawer(self, canvas): ''' gets data for drawing and renders it to the screen ''' graph, world, obstacles, grownObstacles, start_goal = createGraph() # render world scale = lambda p: [scale_x*(tr_x - p.x), scale_y*(tr_y - p.y)] toCanvasPoly = lambda os: list(it.chain(*map(scale, os))) canvas.create_polygon(toCanvasPoly(world), outline='blue', fill='white', width=3.0) # render grown obstacles for grownObstacle in grownObstacles: canvas.create_polygon(toCanvasPoly(grownObstacle), outline='green', fill='white', width=3.0) # render original obstacles for obstacle in obstacles: canvas.create_polygon(toCanvasPoly(obstacle), outline='black', fill='white', width=3.0) # render visibility graph for v1 in graph.vertices: for v2 in v1.adjacent: canvas.create_polygon(toCanvasPoly([v1.p, v2.p]), outline='red', fill='white', width=1.0) # render shortest path path = dijkstra(graph.vertices, start_goal[0], start_goal[1]) for i in range(len(path) - 1): canvas.create_polygon(toCanvasPoly([path[i].p, path[i+1].p]), outline='grey', fill='white', width=5.0) # write shortest path to file pathFile = open('path.txt', 'w') pathFile.write(''.join(map(lambda v: str(v.p.x) + ' ' + str(v.p.y) + '\n', path))) canvas.pack(fill=BOTH, expand=1)
def test_grafo_unitario_de_no_com_nome_B(self): grafo = { 'B': ()} no = 'B' menores_distancias = {'B': 0} self.assertEqual(dijkstra(grafo, no), menores_distancias)
# A is single source shortest path from source 0 noNC, A = bellmenford(0, vn + 1, E) if noNC: # c'[u][v] = c[u][v] + A[u] - A[v] for u in E2: for e in E2[u]: e[1] += A[u] - A[e[0]] # all pair shortest distance D = [[0] * (vn + 1) for i in range(vn + 1)] # n dijkstra for n in range(1, vn + 1): D[n] = dijkstra(n, vn, E2) # D[u][v] = D[u][v] - A[u] + A[v] ret, x, y = float('inf'), -1, -1 for u in range(1, vn + 1): for v in range(1, vn + 1): D[u][v] += - A[u] + A[v] if ret > D[u][v]: ret, x, y = D[u][v], u, v # shortest path in all pairs print ret, 'from', x, 'to', y end = time() print 'Time: ', end - start
def test_grafo_dois_nos_de_B_para_A(self): grafo = { 'A': (), 'B': ((42, 'A'),) } no = 'B' menores_distancias = {'A': 42, 'B': 0} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def test_grafo_com_dois_nos(self): grafo = { 'A': ((42, 'B'),), 'B': () } no = 'A' menores_distancias = {'A': 0, 'B': 42} self.assertEqual(dijkstra(grafo, no), menores_distancias)
def test_grafo_unitario(self): grafo = { 'A': ()} no = 'A' menores_distancias = {'A': 0 } self.assertEqual(dijkstra(grafo, no), menores_distancias)
def search(): _translate = QtCore.QCoreApplication.translate numbers = [] graph = {} predecessor_isdigit = False count = -1 data = open("data/db_amostra.txt", "r") in_search = main.ld_search.text() for line in data: graph.setdefault(int(line.split()[0]), {}).update({ int(line.split()[1]): abs(int(line.split()[1]) - int(line.split()[0])) }) data.close() if in_search != "": for ch in in_search: if ch.isdigit() and predecessor_isdigit == False: numbers.append(ch) predecessor_isdigit = True count += 1 elif ch.isdigit() and predecessor_isdigit == True: numbers[count] = numbers[count] + ch else: predecessor_isdigit = False for i in range(len(numbers)): numbers[i] = int(numbers[i]) if len(numbers) == 2: distance, path = dijkstra(graph, numbers[0], numbers[1]) if distance != -1 and path != -1: main.lb_result.setText( _translate( "MainWindow", f"<html><head/><body><p><span style=\" font-size:14pt; font-weight:600;\">Search result</span></p><p align=\"center\">The <span style=\" font-weight:600;\">shortest distance</span> between <span style=\" font-weight:600;\">{numbers[0]}</span> and <span style=\" font-weight:600;\">{numbers[1]} intersection</span> is: <span style=\" font-weight:600;\">{distance} meters</span>.</p><p align=\"center\">The <span style=\" font-weight:600;\">shortest path</span> between <span style=\" font-weight:600;\">{numbers[0]}</span> and <span style=\" font-weight:600;\">{numbers[1]} intersection</span> is:</p><p align=\"center\"><span style=\" font-weight:600;\">{path}</span></p></body></html>" )) main.fr_result.show() else: main.lb_result.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600;\">Search result</span></p><p align=\"center\">Sorry, path <span style=\" font-weight:600;\">not reachable</span>. :'(</p><p align=\"center\"><br/></p><p align=\"center\"><br/></p></body></html>" )) main.fr_result.show() else: main.lb_result.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600;\">Search result</span></p><p align=\"center\">Please, <span style=\" font-weight:600;\">enter</span> the <span style=\" font-weight:600;\">numbers of the crossroads</span> you want to search for!</p><p align=\"center\"><br/></p><p align=\"center\"><br/></p></body></html>" )) main.fr_result.show() else: main.lb_result.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600;\">Search result</span></p><p align=\"center\">Please, <span style=\" font-weight:600;\">enter</span> your search!</p><p align=\"center\"><br/></p><p align=\"center\"><br/></p></body></html>" )) main.fr_result.show() main.btn_close.clicked.connect(lambda: main.fr_result.hide())
array = [] newArray = [] with open('assignment3.txt') as i: for line in i: cs = "[']\r\n," for char in cs: line = line.replace(char, "") array.append(line) m = 0 for i in array: m = m + 1 if i is '': newArray.append(array[m:len(array) - 1]) dx = dijkstra(g, g.getVertex('S'), g.getVertex('F')) print("Solved nodes for Dijkstra: ") for i in dx: print(i, end='') print("\n") print("Number of nodes solved: %i" % len(dx)) print("\n") ax = a_Star(a, a.getVertex('S'), a.getVertex('F'), newArray) print("Solved nodes for A*: ") for i in ax: print(i, end='') print("\n") print("Number of nodes solved: %i" % len(ax)) print("\n")
data['uk12']['lbl'].append(i[1]['name']) # Usaremos a periferia para obter duas sementes espalhadas data['uk12']['a']['seeds'] = nx.periphery(data['uk12']['grafo']) # Usaremos um vertice aleatorio e um de seus vizinhos como sementes proximas uma da outra random_v = np.random.randint(0, len(data['uk12']['grafo'].nodes())) data['uk12']['b']['seeds'] = ([random_v, data['uk12']['grafo'].neighbors(random_v) [np.random.randint(0, len(data['uk12']['grafo'].neighbors(random_v)))]]) # Executando o Dijkstra nas sementes data['uk12']['a']['lambda'], \ data['uk12']['a']['pi'],\ data['uk12']['a']['h'] = dijkstra(data['uk12']['grafo'], data['uk12']['a']['seeds']) data['uk12']['b']['lambda'], \ data['uk12']['b']['pi'], \ data['uk12']['b']['h'] = dijkstra(data['uk12']['grafo'], data['uk12']['b']['seeds']) if wg59 is True: # Simulacao do grafo WG59, com k = 3 data['wg59']['a'] = {} data['wg59']['b'] = {} data['wg59']['lbl'] = [] data['wg59']['grafo'] = load_graph(data['wg59']['dist'],data['wg59']['name']) for i in data['wg59']['grafo'].nodes(data=True): data['wg59']['lbl'].append(i[1]['name'])
# get weight of the edges weights = {(u, v): data['weight'] for u, v, data in G.edges(data=True)} # plot weights of the edges nx.draw_networkx_edge_labels( G, pos, edge_labels=weights, font_size=12, font_family='sans-serif') #save G on img folder plt.savefig("img/" + fig_title + ".png") # plot G plt.show() # close window plt.close() #init random number generator random.seed() #reads graph G = nx.read_edgelist('data/southern_women_club.txt', nodetype=int, data=(('weight',float),)); plot_weighted_graph(G, 1, 'complete_graph') #choose two distant source nodes. We are going to take nodes from the graph periphery periphery = nx.periphery(G) sources = random.sample(range(1, len(periphery)), 2) H, predecessors = dijkstra(G, sources) plot_weighted_graph(H, 2, 'two_sources', sources, predecessors) #choose 3 random source nodes sources = random.sample(range(1, len(G)), 3) I, predecessors = dijkstra(G, sources) plot_weighted_graph(I, 3, 'three_sources', sources, predecessors) #choose another 3 raomdon source nodes sources = random.sample(range(1, len(G)), 3) I, predecessors = dijkstra(G, sources) plot_weighted_graph(I, 4, 'another_three_sources', sources, predecessors)
def find(): # this should find the next node to send, if we are at a end node, use dijkstra, pass it go next node print("Received routing request") data = request.get_json() if 'type' in data: if data['type'] == 'EOT': if 'dest' in data: destination = data['dest'] if 'origin' in data: origin = data['origin'] if destination == node.node_name: print( '...Received negotiation packet...from origin: {}'.format( origin)) if origin in node.threshold: node.threshold[origin] += 1 else: node.threshold[origin] = 1 return "Received full package!" return jsonify({'status': 'success'}) if 'dest' in data: destination = node.dhtEngine.get_key_from_node_id(data['dest']) if 'origin' in data: origin = data['origin'] if check_threshold(origin): return jsonify({'error': '100 - threshold reached'}) if node.type == 'end': print('Starting routing request from {} to {}'.format( node.node_name, data['dest'])) # Pass it to associated bnode # Since we can have more than 1 abnode, we choose first one in list bnode = node.associated_bnodes[0] origin_key = get_key_from_node_ids(bnode) payload = {'origin': origin_key, 'dest': data['dest']} ip = get_routing_ip(bnode) print("Routing to {} with ip {} with payload: {}".format( bnode, ip, payload)) send(payload, ip) return jsonify({'status': 'success'}) payload = {'origin': data['origin'], 'dest': data['dest']} # first check if end node is connected to this # if destination in node.end_nodes: if existing_key_in_end_nodes_router(data['dest']): print('Destination is a connected end node') enode_key = get_enode_name_from_existing_key_in_end_nodes_router( data['dest']) ip = get_routing_ip(enode_key) enode_payload = {'origin': origin, 'dest': enode_key, 'type': 'EOT'} print("Routing to {} with ip {} with payload: {}".format( enode_key, ip, payload)) send(enode_payload, ip) return "Dijkstra routing complete!" if node.type != 'end': shortest_path = dijkstra(node.node_name, destination) else: shortest_path = dijkstra(node.neighbours[0], destination) print("Calculated shortest path {}".format(shortest_path)) shortest_path = shortest_path.split(',') next_node = shortest_path[0] # we have reached a path of two nodes if next_node == node.node_name: next_node = shortest_path[1] ip = get_routing_ip(next_node) print("Routing to {} with ip {} with payload: {}".format( next_node, ip, payload)) send(payload, ip) return jsonify(next_node)
if not listaDeAdjacencia.get(aeroporto): listaDeAdjacencia[aeroporto] = {} cordOrigem = {'latitude': data['LatOrig'][key], 'longitude': data['LongOrig'][key]} cordDestino = {'latitude': data['LatDest'][key], 'longitude': data['LongDest'][key]} listaDeAdjacencia[aeroporto][data['Aeroporto.Destino'][key]] = haversine(cordOrigem, cordDestino) # Salvando lista de adjacência with open('listaAdjacência.json', 'w') as json_file: json.dump(listaDeAdjacencia, json_file) graph = { 'a': {'b': 4, 'c': 4}, 'b': {'a': 4, 'c': 2}, 'c': {'a': 4, 'd': 3, 'e': 4, 'f': 2}, 'd': {'c': 3, 'e': 3}, 'e': {'c': 4, 'd': 3, 'f': 3}, 'f': {'c': 2, 'e': 3} } # print(listaDeAdjacencia) main() qtd_nos = len(listaDeAdjacencia) print("\n\n==========================\nNúmero de aeroportos: ", qtd_nos, "\n==========================\n") prim_algoritmo(listaDeAdjacencia) kruskal_algoritmo(listaDeAdjacencia) dijkstra(listaDeAdjacencia, "Hercilio Luz", "Carajas")
distGraph.vertices[VertIndex.index(row[1])], row[3]) astarGraph.addDiEdge(astarGraph.vertices[VertIndex.index(row[0])], astarGraph.vertices[VertIndex.index(row[1])], row[3]) costOrg = costGraph.vertices[VertIndex.index('SFB')] distOrg = distGraph.vertices[VertIndex.index('SFB')] costDest = costGraph.vertices[VertIndex.index('YNG')] distDest = distGraph.vertices[VertIndex.index('YNG')] aStarOrg = astarGraph.vertices[VertIndex.index('ABE')] aStarDest = astarGraph.vertices[VertIndex.index('YNG')] # first run of dijkstra d1_start = time.time() dijkstra(costOrg, costGraph) d1_end = time.time() print("Running Dijkstra's On Cost ", (d1_end - d1_start) * 1000, "ms") print("Dijkstra on cost n vertices:", len(costGraph.vertices)) # second run of dijkstra d2_start = time.time() dijkstra(distOrg, distGraph) d2_end = time.time() print("Running Dijkstra's On Distance ", (d2_end - d2_start) * 1000, "ms") print("Dijkstra on cost n vertices:", len(distGraph.vertices)) # astar run astar_start = time.time() aStarPath = a_star(aStarOrg, aStarDest, astarGraph) astar_end = time.time()
def SuccessiveShortestPath(G, G_Cost, DEM, nodesNumber): x = G.dot(0) pi = [0 for i in range(nodesNumber)] e = (DEM.transpose() - DEM).sum(0) E = np.where(e > 0)[0] D = np.where(e < 0)[0] RG_ReduceCost = G_Cost RG_Capacity = G.copy() originalReverseCapacity = G.dot(0) originalReverseCost = G.dot(0) cycleNo = 0 flow = x while E.size != 0: i = 0 dist, paths = dijkstra(RG_Capacity, RG_ReduceCost, E[0]) p = paths[D[i]] if (not p): print("\n p is null! \n") break pi = pi - dist rij = np.zeros((1, np.size(p) - 1), dtype=int)[0] for j in range(0, np.size(p) - 1): rij[j] = RG_Capacity[p[j]][p[j + 1]] delta = np.min([e[E[i]], -e[D[i]], min(rij)]) x = x.dot(0) for j in range(0, np.size(p) - 1): x[p[j]][p[j + 1]] = delta flow += x e = e + x.sum(0) - x.sum(1).transpose() E = np.where(e > 0)[0] D = np.where(e < 0)[0] ones1 = np.ones((1, nodesNumber), dtype=int)[0] ones2 = np.ones((nodesNumber, 1), dtype=int) ones1.shape = (1, nodesNumber) ones2.shape = (nodesNumber, 1) dist.shape = (1, nodesNumber) RG_ReduceCost = RG_ReduceCost + ((dist.transpose().dot(ones1) - (ones2.dot(dist)))) # Set minus numbers to zero, to be improved #RG_ReduceCost = RG_ReduceCost * np.where(RG_ReduceCost > 0, 1, 0) RG_ReduceCost = RG_ReduceCost * np.where(RG_Capacity > 0, 1, 0) originalReverseCost = originalReverseCost - dist.transpose().dot( ones1) + ones2.dot(dist) originalReverseCost = originalReverseCost * np.where( originalReverseCapacity > 0, 1, 0) for j in range(0, np.size(p) - 1): pj = p[j] pj1 = p[j + 1] RG_Capacity[pj][pj1] = RG_Capacity[pj][pj1] - delta if RG_ReduceCost[pj1][pj] > 0: originalReverseCapacity[pj1][pj] = RG_Capacity[pj1][pj] originalReverseCost[pj1][pj] = RG_ReduceCost[pj1][pj] RG_Capacity[pj1][pj] = 0 RG_Capacity[pj1][pj] = RG_Capacity[pj1][pj] + delta RG_ReduceCost[pj1][pj] = 0 ''' if RG_Capacity[pj][pj1] == 0: if originalReverseCapacity[pj1][pj] > 0: RG_Capacity[pj1][pj] = originalReverseCapacity[pj1][pj] originalReverseCapacity[pj1][pj] = 0 RG_ReduceCost[pj1][pj] = originalReverseCost[pj1][pj] originalReverseCost[pj1][pj] = 0 ''' if RG_Capacity[pj][pj1] == 0: if originalReverseCapacity[pj][pj1] > 0: RG_Capacity[pj][pj1] = originalReverseCapacity[pj][pj1] originalReverseCapacity[pj][pj1] = 0 RG_ReduceCost[pj][pj1] = originalReverseCost[pj][pj1] originalReverseCost[pj][pj1] = 0 if RG_ReduceCost[pj1][pj] < 0: print("\nError, RG_ReduceCost < 0\n") cycleNo = cycleNo + 1 if cycleNo > 10000: print("\nIterations more than 10000!\n") break flow = flow - flow.transpose() flow = flow * np.where(flow < 0, 0, 1) MiniCost = sum(sum(np.nan_to_num(G_Cost) * flow)) return MiniCost, flow
font_size=12, font_family='sans-serif') #save G on img folder plt.savefig("img/" + fig_title + ".png") # plot G plt.show() # close window plt.close() #init random number generator random.seed() #reads graph G = nx.read_edgelist('data/southern_women_club.txt', nodetype=int, data=(('weight', float), )) plot_weighted_graph(G, 1, 'complete_graph') #choose two distant source nodes. We are going to take nodes from the graph periphery periphery = nx.periphery(G) sources = random.sample(range(1, len(periphery)), 2) H, predecessors = dijkstra(G, sources) plot_weighted_graph(H, 2, 'two_sources', sources, predecessors) #choose 3 random source nodes sources = random.sample(range(1, len(G)), 3) I, predecessors = dijkstra(G, sources) plot_weighted_graph(I, 3, 'three_sources', sources, predecessors) #choose another 3 raomdon source nodes sources = random.sample(range(1, len(G)), 3) I, predecessors = dijkstra(G, sources) plot_weighted_graph(I, 4, 'another_three_sources', sources, predecessors)
from functions import * from dijkstra import * G = [[0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0]] print("Largeur") parcoursEnLargeur(G, 0) print("\nProfondeur") parcoursEnProfondeur(G, 0) G = [[0, 10, 5, inf, inf], [10, 0, 4, 3, inf], [5, 4, 0, 1, inf], [inf, 3, 1, 0, 6], [inf, inf, inf, 6, 0]] print("\n Dijkstra :") dist, pere = dijkstra(G, 0) i = 0 for item, item1 in zip(dist, pere): print("Sommet S(", i, ") : dist ", item, ' pere ', item1) i += 1