def self_similarity(G, distances, size=1000, weight=None): pwl = [] if weight == None: for node in tqdm(np.random.choice(G.nodes(), size=size)): for d in distances: pwl += [ (d, len( nx.single_source_dijkstra_path_length(G, node, cutoff=d, weight=None))) ] else: for node in tqdm(np.random.choice(G.nodes(), size=size)): for d in distances: pwl += [ (d, len( nx.single_source_dijkstra_path_length(G, node, cutoff=d, weight=weight))) ] pwl = np.asarray(pwl) return pwl
def test_dijkstra(self): (D, P) = nx.single_source_dijkstra(self.XG, 's') assert_equal(P['v'], ['s', 'x', 'u', 'v']) assert_equal(D['v'], 9) assert_equal( nx.single_source_dijkstra_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal( nx.single_source_dijkstra_path_length(self.XG, 's')['v'], 9) assert_equal( nx.single_source_dijkstra(self.XG, 's')[1]['v'], ['s', 'x', 'u', 'v']) assert_equal( nx.single_source_dijkstra_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal( nx.single_source_dijkstra_path( self.XG, 's', weight_fnc=lambda u, v, ed: ed['weight'] * 2)['v'], ['s', 'x', 'u', 'v']) assert_equal( nx.single_source_dijkstra_path_length( self.XG, 's', weight_fnc=lambda u, v, ed: ed['weight'] * 2)['v'], 18) GG = self.XG.to_undirected() (D, P) = nx.single_source_dijkstra(GG, 's') assert_equal(P['v'], ['s', 'x', 'u', 'v']) assert_equal(D['v'], 8) # uses lower weight of 2 on u<->x edge assert_equal(nx.dijkstra_path(GG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8) assert_equal(nx.dijkstra_path(self.XG2, 1, 3), [1, 4, 5, 6, 3]) assert_equal(nx.dijkstra_path(self.XG3, 0, 3), [0, 1, 2, 3]) assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15) assert_equal(nx.dijkstra_path(self.XG4, 0, 2), [0, 1, 2]) assert_equal(nx.dijkstra_path_length(self.XG4, 0, 2), 4) assert_equal(nx.dijkstra_path(self.MXG4, 0, 2), [0, 1, 2]) assert_equal( nx.single_source_dijkstra(self.G, 's', 'v')[1]['v'], ['s', 'u', 'v']) assert_equal( nx.single_source_dijkstra(self.G, 's')[1]['v'], ['s', 'u', 'v']) assert_equal(nx.dijkstra_path(self.G, 's', 'v'), ['s', 'u', 'v']) assert_equal(nx.dijkstra_path_length(self.G, 's', 'v'), 2) # NetworkXError: node s not reachable from moon assert_raises(nx.NetworkXError, nx.dijkstra_path, self.G, 's', 'moon') assert_raises(nx.NetworkXError, nx.dijkstra_path_length, self.G, 's', 'moon') assert_equal(nx.dijkstra_path(self.cycle, 0, 3), [0, 1, 2, 3]) assert_equal(nx.dijkstra_path(self.cycle, 0, 4), [0, 6, 5, 4])
def fastmap_L2(G, K, epsilon): NG = G.copy() embedding = {} # initial the embedding as a dict for node in list(NG.nodes()): embedding[node] = [] for r in range(K): node_a = choice(list(NG.nodes())) node_b = node_a # Find the farthest nodes a, b for t in range(C): raw_length = nx.single_source_dijkstra_path_length(NG, node_a) length = adjust_length(raw_length, embedding, node_a, r) node_c = max(length.items(), key=operator.itemgetter(1))[0] if node_c == node_b: break else: node_b = node_a node_a = node_c raw_length_a = nx.single_source_dijkstra_path_length(NG, node_a) length_a = adjust_length(raw_length_a, embedding, node_a, r) raw_length_b = nx.single_source_dijkstra_path_length(NG, node_b) length_b = adjust_length(raw_length_b, embedding, node_b, r) dis_ab = length_a[node_b] print("Iteration {}, largest distance: {}".format(r + 1, dis_ab)) if dis_ab < epsilon: break # Calcute the embedding for node in list(NG.nodes()): p_ir = float(length_a[node] + dis_ab - length_b[node]) / (2 * math.sqrt(dis_ab)) embedding[node].append(p_ir) return embedding
def fastmap_L1(G, K, epsilon): NG = G.copy() embedding = {} # initial the embedding as a dict for node in list(NG.nodes()): embedding[node] = [] for r in range(K): node_a = choice(list(NG.nodes())) node_b = node_a # Find the farthest nodes a, b for t in range(C): length = nx.single_source_dijkstra_path_length(NG, node_a) node_c = max(length.items(), key=operator.itemgetter(1))[0] if node_c == node_b: break else: node_b = node_a node_a = node_c length_a = nx.single_source_dijkstra_path_length(NG, node_a) length_b = nx.single_source_dijkstra_path_length(NG, node_b) dis_ab = length_a[node_b] print("Iteration {}, largest distance: {}".format(r + 1, dis_ab)) if dis_ab < epsilon: break # Calcute the embedding for node in list(NG.nodes()): p_ir = float(length_a[node] + dis_ab - length_b[node]) / 2 embedding[node].append(p_ir) # Update the weight of the graph for i, j in NG.edges(): w = NG[i][j]['weight'] NG[i][j]['weight'] = w - abs(embedding[i][r] - embedding[j][r]) if abs(NG[i][j]['weight']) < 0.00001: NG[i][j]['weight'] = 0 return embedding
def discount_solution(path_to_graph: str, source: int, target: int, k: int) -> int: """ Finds the biggest discount that can be achieved :param path_to_graph: path to the road graph. tolls are edge-attributed under 'weight' label. :param source: the desired source :param target: the desired target :param k: your maximal money bound :return: value of the biggest discount. """ """ idea: we run dijkstra twice on the graph: one-source-multi-target, and multi-source-one-target. now, we iterate all the edges. for any edge we can find the lowest-cost path passing through it by using the values from dijkstra iterations above: shortest path from source to u + weight of edge (u, v) + shortest path from v to target. we start with 0 discount and whenever we find an edge with legal path passing through it and better discount, we update it. """ g = nx.read_gpickle(os.path.join(os.getcwd(), path_to_graph)) from_source = nx.single_source_dijkstra_path_length(g, source) reversed_graph = nx.DiGraph() reversed_graph.add_weighted_edges_from([(v, u, w) for (u, v), w in nx.get_edge_attributes(g, 'weight').items()]) to_target = nx.single_source_dijkstra_path_length(reversed_graph, target) tolls = nx.get_edge_attributes(g, 'weight') discount = 0 for u, v in list(g.edges): toll = tolls[(u, v)] if u in from_source.keys() and v in to_target.keys(): if from_source[u] + toll + to_target[v] <= k: discount = max(discount, toll) return discount
def test_single_source_shortest_path_length(self): ans = dict(nx.shortest_path_length(self.cycle, 0)) assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert ans == dict(nx.single_source_shortest_path_length( self.cycle, 0)) ans = dict(nx.shortest_path_length(self.grid, 1)) assert ans[16] == 6 # now with weights ans = dict(nx.shortest_path_length(self.cycle, 0, weight="weight")) assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert ans == dict(nx.single_source_dijkstra_path_length( self.cycle, 0)) ans = dict(nx.shortest_path_length(self.grid, 1, weight="weight")) assert ans[16] == 6 # weights and method specified ans = dict( nx.shortest_path_length(self.cycle, 0, weight="weight", method="dijkstra")) assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert ans == dict(nx.single_source_dijkstra_path_length( self.cycle, 0)) ans = dict( nx.shortest_path_length(self.cycle, 0, weight="weight", method="bellman-ford")) assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert ans == dict( nx.single_source_bellman_ford_path_length(self.cycle, 0))
def test_single_source_shortest_path_length(self): ans = dict(nx.shortest_path_length(self.cycle, 0)) assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.single_source_shortest_path_length(self.cycle, 0))) ans = dict(nx.shortest_path_length(self.grid, 1)) assert_equal(ans[16], 6) # now with weights ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight')) assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.single_source_dijkstra_path_length( self.cycle, 0))) ans = dict(nx.shortest_path_length(self.grid, 1, weight='weight')) assert_equal(ans[16], 6) # weights and method specified ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight', method='dijkstra')) assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.single_source_dijkstra_path_length( self.cycle, 0))) ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight', method='bellman-ford')) assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.single_source_bellman_ford_path_length( self.cycle, 0)))
def Part1_2(house_nd,object_nd, dist2objects=None, dist2houses=None): if (dist2objects is None or dist2houses is None): N = len(house_nd) M = len(object_nd) dist2objects = np.empty([N,M]) dist2houses = np.empty([M,N]) Grev = G.reverse() for j in range(M): length_house2object = nx.single_source_dijkstra_path_length(Grev, object_nd[j], cutoff=None, weight='length') length_object2house = nx.single_source_dijkstra_path_length(G, object_nd[j], cutoff=None, weight='length') for i in range(N): dist2objects[i,j] = length_house2object[house_nd[i]] dist2houses[j,i] = length_object2house[house_nd[i]] #------------ можно обойтись только тем, что ниже, если использовать инфу из первой функции #ThereAndBack = np.empty(N) # nearest objects to houses there-and-back #ThereAndBackDist = np.empty([N,M]) # distance to nearest objects to houses there-and-back ThereAndBackDist = dist2objects + dist2houses.transpose() A = np.argmin(np.max(dist2objects, axis=0)) # максимальное расстояние до объектов ??? B = np.argmin(np.max(dist2houses.transpose(), axis=0)) # максимальное расстояние до домов ??? C = np.argmin(np.max(ThereAndBackDist, axis=0)) # максимальное расстояние туда и обратно ??? a = np.argmax(dist2objects, axis=0)[A] b = np.argmax(dist2houses.transpose(), axis=0)[B] c = np.argmax(ThereAndBackDist, axis=0)[C] return A, B, C, a, b, c
def new_source(self): self.CFpath = nx.single_source_dijkstra_path(self.CF, self.origin) self.FFpath = nx.single_source_dijkstra_path(self.FF, self.origin) self.CFlength = nx.single_source_dijkstra_path_length( self.CF, self.origin) self.FFlength = nx.single_source_dijkstra_path_length( self.FF, self.origin) self.Ostring = str(self.origin)
def mesh_length(graph): first_node = next(iter(graph.nodes)) initial_dists = nx.single_source_dijkstra_path_length(graph, first_node) furthest_node = max(initial_dists.items(), key=operator.itemgetter(1))[0] lengths = nx.single_source_dijkstra_path_length(graph, furthest_node) other_end, length = max(lengths.items(), key=operator.itemgetter(1)) return length, (furthest_node, other_end)
def _get_k_hop_neighbors(G, node, k): if k == 0: return {node} else: return ( set(nx.single_source_dijkstra_path_length(G, node, k).keys()) - set( nx.single_source_dijkstra_path_length(G, node, k - 1).keys()))
def _k_hop_neibors(self, node, k): if k == 0: return {node} else: return set(nx.single_source_dijkstra_path_length( self._g, node, k).keys()) - set( nx.single_source_dijkstra_path_length( self._g, node, k - 1).keys())
def multiprocessing_single_source_shortest_paths(G, G_reverse, source_origin, source_destination, cutoff, weight, key, listOfReachableNodes): if key == 'origin': listOfReachableNodes['origin'] = nx.single_source_dijkstra_path_length( G=G, source=source_origin, cutoff=cutoff, weight=weight) else: listOfReachableNodes[ 'destination'] = nx.single_source_dijkstra_path_length( G=G_reverse, source=source_destination, cutoff=cutoff, weight=weight) return 'done'
def networkx_call(M, source, edgevals=False): print('Format conversion ... ') M = M.tocsr() if M is None: raise TypeError('Could not read the input graph') if M.shape[0] != M.shape[1]: raise TypeError('Shape is not square') # Directed NetworkX graph G = nx.Graph(M) Gnx = G.to_undirected() print('NX Solving... ') t1 = time.time() if edgevals is False: path = nx.single_source_shortest_path_length(Gnx, source) else: path = nx.single_source_dijkstra_path_length(Gnx, source) t2 = time.time() - t1 print('Time : ' + str(t2)) return path
def findDiameter(G): for index, graph in enumerate(G): diameter = set() for node in graph: lenght = nx.single_source_dijkstra_path_length(graph, node) diameter.add(lenght[max(lenght, key=lenght.get)]) print("Diameter: ", index, max(diameter))
def getFreePathToTarget(self, bot, current, target): ## tmp: get one of the current active paths if len(self.botWaypoints) == 0 or (len(self.botWaypoints) == 1 and bot in self.botWaypoints): return nx.shortest_path(self.graph, current, target, weight="weight") rndKey = random.choice([key for key in self.botWaypoints.keys() if key != bot]) otherPath = self.botWaypoints[rndKey][0] ## Create a dummy graph node and connect it to each nodes of the shortest path. u = "startNode" self.graph.add_node(u) for v in otherPath: self.graph.add_edge(u, v, weight=1) ## Now calculate the path lengths of all graph nodes to the shortest path nodes. distances = nx.single_source_dijkstra_path_length(self.graph, u, weight="weight") self.graph.remove_node(u) # we don't need the dummy graph node any more del distances[u] ## Create weight heuristics based on path lengths. for node_index, length in distances.iteritems(): self.graph.node[node_index]["weight"] = length for u, v in self.graph.edges(): w = (self.graph.node[u]["weight"] + self.graph.node[v]["weight"]) * 0.5 self.graph[u][v]["weight"] = 1 / w ** 2 ## And finally calculate the path to the flanking position. return nx.shortest_path(self.graph, current, target, weight="weight")
def initialize(self): layer = self.visualizer.anonymousLayer(True) self.visualizer.addLabel("Initializing...", "centered-info-box", Color(222, 222, 222, 255), None) self.visualizer.endLayer() self.bestBotShapeId = -1 self.selectedBot = None self.selectedBotShapeId = -1 self.lastClickTime = time.time() self.botWaypoints = {} self.graph = corridormap.build_graph(self.level.blockHeights, self.level.width, self.level.height) self.kdtree = scipy.spatial.cKDTree([self.graph.node[node]["position"] for node in self.graph.nodes()]) self.lookup = [[None for y in range(self.level.height)] for x in range(self.level.width)] node_count = len(self.graph.nodes()) for x, y in itertools.product(range(self.level.width), range(self.level.height)): closest = None for d, i in zip(*self.kdtree.query((x, y), 2, distance_upper_bound=8.0)): if i >= node_count: continue if closest is None or d < closest: self.lookup[x][y] = i closest = d for node in self.graph.nodes(): self.graph.node[node]["distances"] = nx.single_source_dijkstra_path_length(self.graph, node, weight="weight") self.graph.node[node]["explored"] = False self.initGraphVisualization() self.visualizer.hideLayer(layer)
def solve_fiber_path(row, owner, fiber_nodes_owner, G1): current_node = str(int(row['node_id'])) paths = nx.single_source_dijkstra_path(G1, current_node) lengths = nx.single_source_dijkstra_path_length(G1, current_node) all_paths_from_fiber = {node: paths[node] for node in fiber_nodes_owner} all_lengths_from_fiber = { node: lengths[node] for node in fiber_nodes_owner } if (len(all_paths_from_fiber) > 0): optimal_node = min(all_lengths_from_fiber, key=all_lengths_from_fiber.get) optimal_path = paths[optimal_node] optimal_path_length = lengths[optimal_node] else: optimal_path = [None] optimal_path_length = None output = pd.Series({ ('length_' + owner): optimal_path_length, ('path_' + owner): optimal_path, ('fiber_node_' + owner): optimal_path[-1] }) return output
def bounding_diameters(graph): w_set = dict(graph.degree()) n = len(w_set) e_lower = numpy.empty((n,)) e_upper = numpy.empty((n,)) e_lower[:] = -float("inf") e_upper[:] = float("inf") lower_bound = -float("inf") upper_bound = float("inf") while (lower_bound != upper_bound) and (len(w_set) != 0): v = max(w_set.iteritems(), key=operator.itemgetter(1))[0] path_lengths = nx.single_source_dijkstra_path_length(graph, v) ecc = max(path_lengths.iteritems(), key=operator.itemgetter(1))[1] # plucking highest value in dict lower_bound = max(lower_bound, ecc) upper_bound = min(upper_bound, 2 * ecc) temp = w_set.copy() for w in w_set: e_lower[w] = max(e_lower[w], max(ecc - path_lengths[w], path_lengths[w])) e_upper[w] = min(e_upper[w], ecc + path_lengths[w]) if (e_upper[w] <= lower_bound and e_lower[w] >= upper_bound / 2) or e_lower[w] == e_upper[w]: del temp[w] w_set = temp return lower_bound
def test_on_undirected_not_connected_graph(self): """ Test on an undirected and not connected graph. Not all nodes will be reachable from the source. """ # make the undirected not connected graph params_uncg = {'num_nodes': 200, 'num_edges': 400, 'seed': 0, 'directed': False} graph = make_graph(**params_uncg) assert(not nx.is_connected(graph)) # first run dijkstra_sssp dist, _ = dijkstra_sssp.solve(graph, source=0, weight='weight') # then run networkx's dijkstra nx_dist = nx.single_source_dijkstra_path_length(graph, source=0, weight='weight') # finally, compare results inf = float('inf') for node in graph.nodes_iter(): if dist[node] != inf: # node was reachable self.assertEqual(dist[node], nx_dist[node]) else: # node was unreachable self.assertTrue(node not in nx_dist) self.assertEqual(dist[node], inf)
def compute_distances(network_g, source, targets): distance_map = {} path_length_dict = nx.single_source_dijkstra_path_length(network_g, source) for t in targets: distance_map[t] = path_length_dict[t] # print distance_map return distance_map
def _straightness_centrality(G, weight, normalized=True): """ Calculates straightness centrality. """ straightness_centrality = {} for n in G.nodes(): straightness = 0 sp = nx.single_source_dijkstra_path_length(G, n, weight=weight) if len(sp) > 0 and len(G) > 1: for target in sp: if n != target: network_dist = sp[target] euclidean_dist = _euclidean(n, target) straightness = straightness + (euclidean_dist / network_dist) straightness_centrality[n] = straightness * (1.0 / (len(G) - 1.0)) # normalize to number of nodes-1 in connected part if normalized: if len(sp) > 1: s = (len(G) - 1.0) / (len(sp) - 1.0) straightness_centrality[n] *= s else: straightness_centrality[n] = 0 else: straightness_centrality[n] = 0.0 return straightness_centrality
def nrmsd(G, embedding, S, alg = 'L1'): if S<=1: print("S should bigger than 1") exit subset = sample(list(G.nodes()), S) sigma = 0 ave_d = 0 for i in range(S): node_1 = subset[i] emb_1 = np.array(embedding[node_1]) length = nx.single_source_dijkstra_path_length(G, node_1) for j in range(S): node_2 = subset[j] emb_2 = np.array(embedding[node_2]) distance = length[node_2] if alg == 'L1': embdis = np.sum(np.abs(emb_1-emb_2)) elif alg == 'L2': embdis = math.sqrt(np.dot(emb_1-emb_2, emb_1-emb_2)) sigma += (distance-embdis)*(distance-embdis) ave_d += distance base = S*S sigma = math.sqrt(float(sigma)/base) ave_d = float(ave_d)/base return float(sigma)/ave_d
def initialize(self): # Generate our corridor map, capturing useful information out of the map self.corridor_graph = corridormap.build_graph(self.level.blockHeights, self.level.width, self.level.height) # We use scipy to perform a nearest neighbour look-up. # This allows use to work out which node the bots are closest to. self.kdtree = scipy.spatial.cKDTree([self.corridor_graph.node[n]["position"] for n in self.corridor_graph.nodes()]) for node in self.corridor_graph.nodes(): self.corridor_graph.node[node]["distances"] = nx.single_source_dijkstra_path_length(self.corridor_graph, node, weight="weight") # Using the nearest neighbour tree. For each grid block, which is 1m x 1m, what is the closest node. self.lookup = [[None for y in range(self.level.height)] for x in range(self.level.width)] node_count = len(self.corridor_graph.nodes()) for x, y in itertools.product(range(self.level.width), range(self.level.height)): closest = None for d, i in zip(*self.kdtree.query((x, y), 2, distance_upper_bound=8.0)): if i >= node_count: continue if closest is None or d < closest: self.lookup[x][y] = i closest = d self.terminal_nodes = [] for node in self.corridor_graph.nodes(): # If only one neighbor then it's a terminal node. if len(self.corridor_graph.neighbors(node)) == 1: self.terminal_nodes.append(node) # Initialise all nodes to not having been visited. self.explored = [False for x in range(len(self.corridor_graph.nodes()))] self.initialise = True
def k_skip_graph(G,cover,k): H = nx.Graph() s1=time.time() for node in cover: G2 = share.vincity(G,node,k) SPT = share.SPT(G2,node) SPTD = nx.single_source_dijkstra_path_length(SPT,node) tmp = [node] picked = [] while(len(tmp)>0): x = tmp.pop() picked.append(x) for u in SPT.neighbors(x): if u in picked: continue if u in cover and u != node: H.add_edge(node,u) H[node][u]['weight'] = SPTD[u] else: tmp.insert(0,u) # print '..............................................' t1 = time.time() print '%.4f sec -- kG construct finished' %(t1-s1) return H
def caminhos_minimos_um_no(nx_grafo, no, file_name_prefix): lista_dijkstra_path = [] dijkstra_dict_path = dict( nx.single_source_dijkstra_path(nx_grafo, no, weight='weight')) for key, value in dijkstra_dict_path.items(): lista_dijkstra_path.append([no, key, value]) dijkstra_df_path = pd.DataFrame(lista_dijkstra_path, columns=['origem', 'destino', 'caminho']) dijkstra_df_path.to_csv( 'D:\\repos\\study\\mestrado\\artigos\\UBS\\resultados\\' + str(file_name_prefix) + str(no) + '_dijkstra_path_singlesource.csv', sep=';') # Executando função para pegar as distâncias dos caminhos # mínimos entre todos os nós lista_dijkstra_length = [] dijkstra_dict_length = dict( nx.single_source_dijkstra_path_length(nx_grafo, no, weight='weight')) for key, value in dijkstra_dict_length.items(): lista_dijkstra_length.append([no, key, value]) dijkstra_df_length = pd.DataFrame( lista_dijkstra_length, columns=['origem', 'destino', 'distancia']) # Arredondando valores das distâncias para duas casas decimais dijkstra_df_length = dijkstra_df_length.round(2) dijkstra_df_length.to_csv( 'D:\\repos\\study\\mestrado\\artigos\\UBS\\resultados\\' + str(file_name_prefix) + str(no) + '_dijkstra_length_singlesource.csv', sep=';')
def tree_shortest_paths(adj, undirected=True): """ see https://mathoverflow.net/questions/59680/all-pairs-shortest-paths-in-trees Assumes the 0 is the root :param adj: :param undirected: :return: """ tree = nx.DiGraph(np.triu(adj.cpu().numpy())) N = tree.number_of_nodes() lca = dict( nx.algorithms.lowest_common_ancestors. tree_all_pairs_lowest_common_ancestor(tree, root=0)) lca_mat = np.zeros((N, N), dtype='int') lca_mat[tuple(np.transpose(list(lca.keys())))] = np.array( list(lca.values())) if undirected: lca_mat[tuple(np.transpose(list(lca.keys()))[::-1])] = np.array( list(lca.values())) depths = nx.single_source_dijkstra_path_length(tree, 0) all_depths = np.ones(N, dtype='float32') * -1 node_ids = [x[0] for x in depths.items()] node_depths = [x[1] for x in depths.items()] all_depths[node_ids] = np.array(node_depths) all_sp = all_depths[None, :] + all_depths[:, None] - 2 * (all_depths[lca_mat]) return torch.tensor(all_sp).clamp_min(-1)
def get_local_view(self, n_points, pc_align=False, center_node_id=None, center_coord=None, method="kdtree", verbose=False): if center_node_id is None and center_coord is None: center_node_id = np.random.randint(len(self.vertices)) if center_coord is None: center_coord = self.vertices[center_node_id] n_samples = np.min([n_points, len(self.vertices)]) if method == "kdtree": dists, node_ids = self.kdtree.query(center_coord, n_samples) if verbose: print(np.mean(dists), np.max(dists), np.min(dists)) elif method == "graph": dist_dict = nx.single_source_dijkstra_path_length(self.graph, center_node_id, weight="weight") sorting = np.argsort(np.array(list(dist_dict.values()))) node_ids = np.array(list(dist_dict.keys()))[sorting[:n_points]] else: raise Exception("unknow method") local_vertices = self.vertices[node_ids] if pc_align: local_vertices = self.calc_pc_align(local_vertices) return local_vertices, center_node_id
def run_simple_iteration(G, ground_motion, demand, multi): #G is a graph, demand is a dictionary keyed by source and target of demand per weekday. multi is a boolean that is true if it is a multigraph (can have two parallel edges between nodes) #change edge properties newG, capacities = damage_network(G, ground_motion, multi) #also returns the number of bridges out num_out = sum(x < 100 for x in capacities) # util.write_list(time.strftime("%Y%m%d")+'_bridges_scen_1.txt', capacities) #get max flow start = time.time() #node 5753 is in superdistrict 12, which is santa clara county, and node 3144 is in superdistrict 18, which is alameda county. roughly these are san jose and oakland #node 7619 is in superdistrict 1 (7493 is also), which is sf, and node node 3144 is in superdistrict 18, which is alameda county. roughly these are san francisco and oakland s = '5753' t = '7493' #2702 flow = nx.max_flow(newG, s, t, capacity='capacity') #not supported by multigraph print 'time to get max flow: ', time.time() - start # flow = -1 #get ave. shortest path # start = time.time() sp_dict = nx.single_source_dijkstra_path_length(newG,'7619',weight='distance') sp = sum(sp_dict.values())/float(len(sp_dict.values())) sp2 = 0 for target in demand.keys(): sp2 += sp_dict[target] sp2 = sp2 / float(len(demand.keys())) # print 'time to get shortest path: ', time.time() - start newG = util.clean_up_graph(newG, multi) return (num_out, flow, sp, sp2)
def solve(N, Ei, Si, Dij, U, V): graph = nx.DiGraph() for i in range(N): for j in range(N): if i == j: continue if Dij[i][j] > 0: graph.add_edge(i, j, weight=Dij[i][j]) graph2 = nx.DiGraph() for i in range(N): for t, d in nx.single_source_dijkstra_path_length( graph, i, cutoff=Ei[i]).items(): if d > 0: w = weight = d / Si[i] if graph2.has_edge(i, t): print("hey", w, graph2[i][t]['weight']) w = min(w, graph2[i][t]['weight']) graph2[i][t]['weight'] = w else: graph2.add_edge(i, t, weight=d / Si[i]) solution = "" for i in range(len(U)): solution += "%.8f " % (nx.shortest_path_length( graph2, U[i] - 1, V[i] - 1, weight='weight'), ) return solution
def calc_distance_to_bus(net, bus, respect_switches=True, nogobuses=None, notravbuses=None, weight='weight'): """ Calculates the shortest distance between a source bus and all buses connected to it. INPUT: **net** (pandapowerNet) - Variable that contains a pandapower network. **bus** (integer) - Index of the source bus. OPTIONAL: **respect_switches** (boolean, True) - True: open line switches are being considered (no edge between nodes) False: open line switches are being ignored **nogobuses** (integer/list, None) - nogobuses are not being considered **notravbuses** (integer/list, None) - lines connected to these buses are not being considered **weight** (string, None) – Edge data key corresponding to the edge weight OUTPUT: **dist** - Returns a pandas series with containing all distances to the source bus in km. If weight=None dist is the topological distance (int). EXAMPLE: import pandapower.topology as top dist = top.calc_distance_to_bus(net, 5) """ g = create_nxgraph(net, respect_switches=respect_switches, nogobuses=nogobuses, notravbuses=notravbuses) return pd.Series(nx.single_source_dijkstra_path_length(g, bus, weight=weight))
def nodes_by_distance(self, genome, onlyLeaves=True): """ Returns leaves names sorted by the distance from the given genome. """ graph = nx.Graph() start = [None] def rec_helper(root): if root.identifier == genome: start[0] = root if root.terminal: return for node, _bootstrap, branch_length in root.edges: graph.add_edge(root, node, weight=branch_length) rec_helper(node) rec_helper(self.tree) distances = nx.single_source_dijkstra_path_length(graph, start[0]) if onlyLeaves: nodes = [g for g in distances.keys() if g.terminal and g.identifier != genome] else: nodes = [g for g in distances.keys() if g.identifier != genome] return list(map(str, sorted(nodes, key=distances.get)))
def _update_distance_to_centroid(G, cluster_node, centroid): # create subgraph of cluster. cluster = nx.subgraph(G, cluster_node) # shortest path from centroid to member of cluster. return dict(nx.single_source_dijkstra_path_length(cluster, centroid, weight='cost'))
def main(): matrix = [] with open('src/matrix.txt', 'r', encoding='utf-8') as f: csv_reader = csv.reader(f) for row in csv_reader: matrix.append([int(a) for a in row]) G = nx.DiGraph() G.add_nodes_from([(i, j) for i in range(80) for j in range(8)]) s = (-1, -1) # supersource t = (80, 80) # supersink G.add_nodes_from([s, t]) # supersource and supersink for i in range(80): G.add_edge(s, (i, 0), weight=0) G.add_edge((i, 79), t, weight=matrix[i][-1]) for i in range(80): for j in range(80): w = matrix[i][j] if i > 0: # up G.add_edge((i, j), (i - 1, j), weight=w) if i < 79: # down G.add_edge((i, j), (i + 1, j), weight=w) if j < 79: # right G.add_edge((i, j), (i, j + 1), weight=w) return nx.single_source_dijkstra_path_length(G, source=s)[t]
def distance_main(graph, cluster1, cluster2, nodes1, nodes2): # start = random.choice('ABCDEFGHIJKLMNOPQRSTUVWSYZ') start = input("Enter starting node for most distant nodes: ") nodelist = nx.single_source_dijkstra_path_length(graph, start) print("Two nodes farthest apart are: ") lmin = min(nodelist, key=nodelist.get) rmax = max(nodelist, key=nodelist.get) print('Node', rmax, "------>", "Node", lmin) cum_dist = 0 #v= int(nodelist.values()) for k, v in nodelist.items(): cum_dist = cum_dist + v print(cum_dist) if cum_dist < allowedtime: cluster1.append([k, v]) nodes1.append(k) else: cluster2.append([k, v]) nodes2.append(k) with open("cluster1.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(cluster1)
def calculateGameDistance(self,gameProduct): """Calculates the graph distance from each state in the Automaton to the nearest accepting state, that is it constructs the field lyapFun.""" ###Find all shortest paths from each node to each accepting state #### dictList = list() for acceptingstate in copy.deepcopy(self.acceptingStates): nei = self.graph.predecessors(acceptingstate) if len(nei) > 0: nextDict = nx.single_source_dijkstra_path_length(copy.deepcopy(self.graph.reverse()),acceptingstate) dictList.append(nextDict) else: self.acceptingStates.remove(acceptingstate) self.lyapFun = dict() for state in self.graph.nodes(): self.lyapFun[state] = None for state in self.acceptingStates: self.lyapFun[state] = 0.0 for state in self.graph.nodes(): if gameProduct.gameStates[state[0]].userID[7][0]!='E': #not the environment's turn for d in dictList: if state in d.keys(): if d[state] < self.lyapFun[state] or self.lyapFun[state] is None: self.lyapFun[state] = copy.deepcopy(d[state])# Find closest accepting state for each node
def shortestpath(picking): # iterate through the list of picking and calculate distance between each items # using Graph(setup). Calculates shortest path and returns result # undirected graph, nodes does not repeat p = picking setup = G newsort = [picking[0]] k = picking[0] lowest = [] while len(newsort) != len(p): filteredlist = {} path = nx.single_source_dijkstra_path_length(setup, k, cutoff=None, weight='weight') for x in newsort: if path.has_key(x): del path[x] for key in path: if key in p: filteredlist[key] = path[key] if filteredlist != {}: lowest = min(filteredlist, key=filteredlist.get) newsort.append(lowest) k = lowest return newsort[0:len(p)]
def nodes_by_distance(self, genome, onlyLeaves=True): """ Returns leaves names sorted by the distance from the given genome. """ graph = nx.Graph() start = [None] def rec_helper(root): if root.identifier == genome: start[0] = root if root.terminal: return for node, _bootstrap, branch_length in root.edges: graph.add_edge(root, node, weight=branch_length) rec_helper(node) rec_helper(self.tree) distances = nx.single_source_dijkstra_path_length(graph, start[0]) if onlyLeaves: nodes = [ g for g in distances.keys() if g.terminal and g.identifier != genome ] else: nodes = [g for g in distances.keys() if g.identifier != genome] return list(map(str, sorted(nodes, key=distances.get)))
def destnode(self, node, dest): ''' return the destination node corresponding to a dest ip. node: current node dest: ipdest returns: destination node name ''' # radix trie lpm lookup for destination IP prefix xnode = self.ipdestlpm.get(dest, None) if xnode: dlist = xnode['dests'] best = None if len(dlist) > 1: # in the case that there are multiple egress nodes # for the same IP destination, choose the closest egress best = None bestw = 10e6 for d in dlist: w = single_source_dijkstra_path_length(self.graph, node, d) if w < bestw: bestw = w best = d else: best = dlist[0] return best else: raise InvalidRoutingConfiguration('No route for ' + dest)
def get_one_hop_neighour(G, node): path_lengths = nx.single_source_dijkstra_path_length(G, node) neighbours = [] for node, length in path_lengths.items(): if (length == 1): neighbours.append(node) return neighbours
def average_shortest_path_length(G, weight=None): r"""Return the average shortest path length. The average shortest path length is .. math:: a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)} where `V` is the set of nodes in `G`, `d(s, t)` is the shortest path from `s` to `t`, and `n` is the number of nodes in `G`. Parameters ---------- G : NetworkX graph weight : None or string, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. Raises ------ NetworkXError: if the graph is not connected. Examples -------- >>> G=nx.path_graph(5) >>> print(nx.average_shortest_path_length(G)) 2.0 For disconnected graphs you can compute the average shortest path length for each component: >>> G=nx.Graph([(1,2),(3,4)]) >>> for g in nx.connected_component_subgraphs(G): ... print(nx.average_shortest_path_length(g)) 1.0 1.0 """ if G.is_directed(): if not nx.is_weakly_connected(G): raise nx.NetworkXError("Graph is not connected.") else: if not nx.is_connected(G): raise nx.NetworkXError("Graph is not connected.") avg=0.0 if weight is None: for node in G: path_length=nx.single_source_shortest_path_length(G, node) avg += sum(path_length.values()) else: for node in G: path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight) avg += sum(path_length.values()) n=len(G) return avg/(n*(n-1))
def _landmark_index(self): """ Uses any of the landmark selection algorithms and returns a list of landmarks and the shortest paths to all of its reachable vertices :return: {landmark1: {v1: 5, v2: 10, ...}, landmark2: {v1: 4, v2: 15}} """ landmarks = self._pick_landmarks(self.resolution) return {l: nx.single_source_dijkstra_path_length(self.G, l) for l in landmarks}
def compute_shortest_paths(self, ydim): start = time.time() self.source = self.N.nodes()[argmin(self.P[self.N.nodes(), ydim])] self.shortest_paths = nx.single_source_dijkstra_path(self.N, self.source) self.max_path_len = max(nx.single_source_dijkstra_path_length(self.N, self.source).values()) print 'G compute time: %f seconds' % (time.time() - start)
def GlobalEfficiency(G): avg = 0.0 n = len(G) for node in G: path_length=nx.single_source_dijkstra_path_length(G, node, weight='weight') avg += sum(1.0/v for v in path_length.values() if v !=0) avg *= 1.0/(n*(n-1)) return avg
def AIS(G, alpha, k, uq): H = [] #initialise min-heap H R = {} #result set global clusters global fk global fk_id global max_dist count = 0 length=nx.single_source_dijkstra_path_length(G,uq) for c in clusters: heapq.heappush(H, (clusters[c].MINF, 'Cluster', clusters[c].cluster_id)) #push all clusters into heap with MINF as key while len(H): #while heap is not empty and head's key is less than fk if count<k: temp = heapq.heappop(H) #pop the head item of H if temp[1] == 'Cluster': #if popped item is a cluster cluster = clusters[temp[2]] for u in cluster.users: #push all users in cluster with MINF as key if u != uq: d = math.sqrt((G.node[uq]['x'] - G.node[u]['x'])**2 + (G.node[uq]['y'] - G.node[u]['y'])**2) user_key = alpha*cluster.pcap + (1-alpha)*d/max_dist heapq.heappush(H, (user_key, 'User', u)) else: #if popped item is a user if temp[2] in length: p = length[temp[2]] #implement Dijkstra's here for now d = math.sqrt((G.node[uq]['x'] - G.node[temp[2]]['x'])**2 + (G.node[uq]['y'] - G.node[temp[2]]['y'])**2) f = alpha*p + (1-alpha)*d/max_dist if f>fk: fk = f fk_id = temp[2] R[temp[2]] = f #print(R) count += 1 else: if H[0][0] < fk: temp = heapq.heappop(H) #pop the head item of H if temp[1] == 'Cluster': #if popped item is a cluster cluster = clusters[temp[2]] for u in cluster.users: #push all users in cluster with MINF as key if u != uq: d = math.sqrt((G.node[uq]['x'] - G.node[u]['x'])**2 + (G.node[uq]['y'] - G.node[u]['y'])**2) user_key = alpha*cluster.pcap + (1-alpha)*d/max_dist heapq.heappush(H, (user_key, 'User', u)) else: #if popped item is a user if temp[2] in length: p = length[temp[2]] #implement Dijkstra's here for now d = math.sqrt((G.node[uq]['x'] - G.node[temp[2]]['x'])**2 + (G.node[uq]['y'] - G.node[temp[2]]['y'])**2) f = alpha*p + (1-alpha)*d/max_dist if f<fk: del R[fk_id] R[temp[2]] = f #print(R) fk_id = max(R, key=R.get) fk = R[fk_id] else: break return R
def closeness_centrality(self): """calculate the closeness centrality i.e., the average path length to every other network node """ print '\n++++++++ closeness centrality ++++++++' nc = {} for n in self.graph: distances = nx.single_source_dijkstra_path_length(self.graph, n) nc[n] = sum(distances.values()) / len(self.graph) self.print_centralities(nc)
def neighborhood(self, node, n): """ Determines what nodes are n away from the target node. :param node: name of the target node <string> :param n: number of nodes away from the target node <int> :return: set of nodes set<string> """ path_lengths = nx.single_source_dijkstra_path_length(self._board, node) return {node for node, length in path_lengths.items() if length == n}
def get_travel_times(edges, locations, origin=DEFAULT_ORIGIN, transit_time=5): G = nx.Graph() G.add_weighted_edges_from(map(tuple, list(edges.reset_index().values))) for naptan, location in locations.iterrows(): if location.hub_naptan != '': G.add_weighted_edges_from([(naptan, location.hub_naptan, transit_time)]) times = nx.single_source_dijkstra_path_length(G, origin, weight='weight') return pd.Series(times)
def update_stackdepth(cfg): '''The stack depth is supposed to be independent of path. So dijkstra on the undirected graph suffices (and maybe too strong. we don't need minimality) The `undirected` part is just because we want to work with unreachable code too. ''' bidi = gu.copy_to_bidirectional(cfg, weight='stack_effect') depths = nx.single_source_dijkstra_path_length(bidi, source=0, weight='stack_effect') nx.set_node_attributes(cfg, 'stack_depth', depths) return cfg
def __init__(self, graph_1, graph_2): self.graph_1 = graph_1 self.graph_2 = graph_2 self.num_nodes_graph_1 = self.graph_1.number_of_nodes() self.num_nodes_graph_2 = self.graph_2.number_of_nodes() self.graph_1_edges = self.graph_1.edges() self.graph_2_edges = self.graph_2.edges() self.size_of_min_graph = min(self.num_nodes_graph_1, self.num_nodes_graph_2) self.graph_height_1 = \ max(nx.single_source_dijkstra_path_length(self.graph_1, 0).values()) self.graph_height_2 = \ max(nx.single_source_dijkstra_path_length(self.graph_2, 0).values()) self.max_height = max(self.graph_height_1, self.graph_height_2)
def test_single_source_shortest_path_length(self): l=nx.shortest_path_length(self.cycle,0) assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1}) assert_equal(l,nx.single_source_shortest_path_length(self.cycle,0)) l=nx.shortest_path_length(self.grid,1) assert_equal(l[16],6) # now with weights l=nx.shortest_path_length(self.cycle,0,weighted=True) assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1}) assert_equal(l,nx.single_source_dijkstra_path_length(self.cycle,0)) l=nx.shortest_path_length(self.grid,1,weighted=True) assert_equal(l[16],6)
def overall_average_shortest(G): avg = 0.0 ref = (math.log(N)) for g in nx.connected_component_subgraphs(G): for node in g: path_length=nx.single_source_dijkstra_path_length(g, node) avg += ref - sum(path_length.values()) n=len(g) if n>1: return float(avg)/float(n*(n-1)) else: return 0.0
def computeDistanceMap(self, cells): """Using networkx generate the distance map between pairs of cells. """ start = "start" self.graph.add_node(start) for index in cells: self.graph.add_edge(start, index, weight=1.0) distance_map = nx.single_source_dijkstra_path_length(self.graph, start, weight="weight") del distance_map["start"] self.graph.remove_node(start) return distance_map
def global_efficiency(graph, weight=True, to_undirected=False): """ Compute value of global efficiency for a given graph. :param graph: NetworkX graph :param weight: If True then all shortest paths will be computed as a sum of weights of all traversed edges. Else shortest paths will be sum of jumps needed from one node to every other. :type weight: boolean, (default = True) :param to_undirected: If True all edges will become undirected. :type to_undirected: boolean, (default = False) :return: Value of global efficiency for given graph :rtype: dictionary .. seealso:: :py:func:`local_efficiency` Reference .. [1] V. Latora and M. Marchiori, “Efficient Behavior of Small-World Networks”, Phys.Rev. Lett., vol. 87, no. 19, Oct. 2001. """ n = graph.order() sum_dij = 0 if to_undirected is True: graph = graph.to_undirected() if weight is True: for node in graph.nodes(): shortest_paths = nx.single_source_dijkstra_path_length(graph, node) sum_dij += sum(1 / d_ij for d_ij in shortest_paths.values() if d_ij != 0) else: for node in graph.nodes(): shortest_paths = nx.single_source_shortest_path_length(graph, node) sum_dij += sum(1 / d_ij for d_ij in shortest_paths.values() if d_ij != 0) try: efficiency = 1. / (n * (n - 1)) * sum_dij except ZeroDivisionError: efficiency = 0 return efficiency
def traveltime_centrality(self): """calculate the traveltime centrality i.e., the closeness centrality on the travel and transit time network calculate only between master nodes (and ignore auxiliary nodes) """ print '\n++++++++ traveltime centrality ++++++++' nc = {} for n in debug_iter(self.master_nodes, 10): distances = nx.single_source_dijkstra_path_length(self.graph, n) distances = {k: v for k, v in distances.items() if k in self.master_nodes} nc[n] = sum(distances.values()) / len(self.master_nodes) self.print_centralities(nc)
def weiner_index(G, weight=None): # compute sum of distances between all node pairs # (with optional weights) weiner = 0.0 if weight is None: for n in G: path_length = nx.single_source_shortest_path_length(G, n) weiner += sum(path_length.values()) else: for n in G: path_length = nx.single_source_dijkstra_path_length(G, n, weight=weight) weiner += sum(path_length.values()) return weiner
def get_similar_good_photo_locations(tag, city_id, tag_graph, distance_cutoff=5, minimum_photos=20, best_percentage=0.2): nearby_tags = nx.single_source_dijkstra_path_length(tag_graph, tag, cutoff=5) tags = nearby_tags.keys() views_and_coords = sorted(helpers.get_photos_from_tags(tags, city_id)) saved_coords = [] # Save the top 20, or 10% of photos, whichever is larger for views, photo_id, url, coord in reversed(views_and_coords): saved_coords.append(coord) if len(saved_coords) >= 20 \ and float(len(saved_coords)) / len(views_and_coords) > 0.1: break return saved_coords