def test_is_negatively_weighted(self): G = nx.Graph() assert_false(nx.is_negatively_weighted(G)) G.add_node(1) G.add_nodes_from([2, 3, 4, 5]) assert_false(nx.is_negatively_weighted(G)) G.add_edge(1, 2, weight=4) assert_false(nx.is_negatively_weighted(G, (1, 2))) G.add_edges_from([(1, 3), (2, 4), (2, 6)]) G[1][3]['color'] = 'blue' assert_false(nx.is_negatively_weighted(G)) assert_false(nx.is_negatively_weighted(G, (1, 3))) G[2][4]['weight'] = -2 assert_true(nx.is_negatively_weighted(G, (2, 4))) assert_true(nx.is_negatively_weighted(G)) G = nx.DiGraph() G.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ('1', '0', -2), ('0', '2', 2), ('1', '2', -3), ('2', '3', 1)]) assert_true(nx.is_negatively_weighted(G)) assert_false(nx.is_negatively_weighted(G, ('0', '3'))) assert_true(nx.is_negatively_weighted(G, ('1', '0'))) assert_raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
def test_is_negatively_weighted(self): G = nx.Graph() assert not nx.is_negatively_weighted(G) G.add_node(1) G.add_nodes_from([2, 3, 4, 5]) assert not nx.is_negatively_weighted(G) G.add_edge(1, 2, weight=4) assert not nx.is_negatively_weighted(G, (1, 2)) G.add_edges_from([(1, 3), (2, 4), (2, 6)]) G[1][3]["color"] = "blue" assert not nx.is_negatively_weighted(G) assert not nx.is_negatively_weighted(G, (1, 3)) G[2][4]["weight"] = -2 assert nx.is_negatively_weighted(G, (2, 4)) assert nx.is_negatively_weighted(G) G = nx.DiGraph() G.add_weighted_edges_from([ ("0", "3", 3), ("0", "1", -5), ("1", "0", -2), ("0", "2", 2), ("1", "2", -3), ("2", "3", 1), ]) assert nx.is_negatively_weighted(G) assert not nx.is_negatively_weighted(G, ("0", "3")) assert nx.is_negatively_weighted(G, ("1", "0")) pytest.raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
def test_is_negatively_weighted(self): G = nx.Graph() assert_false(nx.is_negatively_weighted(G)) G.add_node(1) G.add_nodes_from([2, 3, 4, 5]) assert_false(nx.is_negatively_weighted(G)) G.add_edge(1, 2, weight=4) assert_false(nx.is_negatively_weighted(G, (1, 2))) G.add_edges_from([(1, 3), (2, 4), (2, 6)]) G[1][3]["color"] = "blue" assert_false(nx.is_negatively_weighted(G)) assert_false(nx.is_negatively_weighted(G, (1, 3))) G[2][4]["weight"] = -2 assert_true(nx.is_negatively_weighted(G, (2, 4))) assert_true(nx.is_negatively_weighted(G)) G = nx.DiGraph() G.add_weighted_edges_from( [("0", "3", 3), ("0", "1", -5), ("1", "0", -2), ("0", "2", 2), ("1", "2", -3), ("2", "3", 1)] ) assert_true(nx.is_negatively_weighted(G)) assert_false(nx.is_negatively_weighted(G, ("0", "3"))) assert_true(nx.is_negatively_weighted(G, ("1", "0"))) assert_raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
def print_graph_features(self, graph): res = {} try: print('diameter: ', nx.diameter(graph)) print('eccentricity: ', nx.eccentricity(graph)) print('center: ', nx.center(graph)) print('periphery: ', nx.periphery(graph)) res['connected'] = True except Exception as e: print('Graph not connected') res['connected'] = False res['density'] = '{:.6f}'.format(nx.density(graph)) res['Avg_degree'] = '{:.6f}'.format(sum([i[1] for i in nx.degree(graph)]) / len(nx.degree(graph))) res['Avg_weight'] = '{:.6f}'.format(sum([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges]) / len( [graph[edge[0]][edge[1]]['weight'] for edge in graph.edges])) res['edges'] = len(graph.edges) res['nodes'] = len(graph.nodes) res['self_loops'] = len(list(nx.nodes_with_selfloops(graph))) res['edge_to_node_ratio'] = '{:.6f}'.format(len(graph.nodes) / len(graph.edges)) res['negative_edges'] = nx.is_negatively_weighted(graph) print(algo.max_clique(graph)) # print('density: ', res['density']) # print('Average degree: ', res['Avg_degree']) # print('Average weight: ', res['Avg_weight']) # print('edges: ', len(graph.edges)) # print('Nodes: ', len(graph.nodes)) # print('self loops: ', res['self_loops']) # print('edges to nodes ratio: ', res['edge_to_node_ratio']) # print('negative edges: ', res['negative_edges']) # nodes = [node for node in graph.nodes] # print(nodes) return res
def extract_simple_features(self, graph): res = {} try: print('diameter: ', nx.diameter(graph)) print('eccentricity: ', nx.eccentricity(graph)) print('center: ', nx.center(graph)) print('periphery: ', nx.periphery(graph)) res['connected'] = True except Exception as e: print('Graph not connected') res['connected'] = False res['density'] = '{:.6f}'.format(nx.density(graph)) res['Avg_degree'] = '{:.6f}'.format( sum([i[1] for i in nx.degree(graph)]) / len(nx.degree(graph))) res['Avg_weight'] = '{:.6f}'.format( sum([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges]) / len([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges])) res['edges'] = len(graph.edges) res['nodes'] = len(graph.nodes) res['self_loops'] = len(list(nx.nodes_with_selfloops(graph))) res['edge_to_node_ratio'] = '{:.6f}'.format( len(graph.nodes) / len(graph.edges)) res['negative_edges'] = nx.is_negatively_weighted(graph) return res
def nx_to_adj_list(G: Union[nx.Graph, nx.DiGraph]) -> tuple: """Converts NetworkX graph to an adj_list. - adj_list format: [ { (neighbor, weight), }, ] - G.nodes() are encoded to a numerical representation [1, n], in order to be used as indexes of adj_list. Args: G (Graph or Digraph) Returns: adj_list (list) decoder (dict) : maps the numerical representation [1, n] back to G.nodes() Raises: Exception : if G is negatively weighted """ if nx.is_negatively_weighted(G): raise Exception("Only non-negative weighted graphs are currently" " supported.") n = G.number_of_nodes() encoder = dict(zip(G.nodes, range(1, n + 1))) decoder = dict(zip(range(1, n + 1), G.nodes)) adj_list = [set() for _ in range(n + 1)] if nx.is_directed(G): if nx.is_weighted(G): for u, v, w in G.edges.data("weight"): adj_list[encoder[u]].add((encoder[v], w)) else: for u, v in G.edges: adj_list[encoder[u]].add((encoder[v], 1)) else: if nx.is_weighted(G): for u, v, w in G.edges.data("weight"): adj_list[encoder[u]].add((encoder[v], w)) adj_list[encoder[v]].add((encoder[u], w)) else: for u, v in G.edges: adj_list[encoder[u]].add((encoder[v], 1)) adj_list[encoder[v]].add((encoder[u], 1)) return adj_list, encoder, decoder
def global_reaching_centrality(G, weight=None, normalized=True): """Returns the global reaching centrality of a directed graph. The *global reaching centrality* of a weighted directed graph is the average over all nodes of the difference between the local reaching centrality of the node and the greatest local reaching centrality of any node in the graph [1]_. For more information on the local reaching centrality, see :func:`local_reaching_centrality`. Informally, the local reaching centrality is the proportion of the graph that is reachable from the neighbors of the node. Parameters ---------- G : DiGraph A networkx DiGraph. weight : None or string, optional (default=None) Attribute to use for edge weights. If ``None``, each edge weight is assumed to be one. A higher weight implies a stronger connection between nodes and a *shorter* path length. normalized : bool, optional (default=True) Whether to normalize the edge weights by the total sum of edge weights. Returns ------- h : float The global reaching centrality of the graph. Examples -------- >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edge(1, 2) >>> G.add_edge(1, 3) >>> nx.global_reaching_centrality(G) 1.0 >>> G.add_edge(3, 2) >>> nx.global_reaching_centrality(G) 0.75 See also -------- local_reaching_centrality References ---------- .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek. "Hierarchy Measure for Complex Networks." *PLoS ONE* 7.3 (2012): e33799. https://doi.org/10.1371/journal.pone.0033799 """ if nx.is_negatively_weighted(G, weight=weight): raise nx.NetworkXError('edge weights must be positive') total_weight = G.size(weight=weight) if total_weight <= 0: raise nx.NetworkXError('Size of G must be positive') # If provided, weights must be interpreted as connection strength # (so higher weights are more likely to be chosen). However, the # shortest path algorithms in NetworkX assume the provided "weight" # is actually a distance (so edges with higher weight are less # likely to be chosen). Therefore we need to invert the weights when # computing shortest paths. # # If weight is None, we leave it as-is so that the shortest path # algorithm can use a faster, unweighted algorithm. if weight is not None: def as_distance(u, v, d): return total_weight / d.get(weight, 1) shortest_paths = nx.shortest_path(G, weight=as_distance) else: shortest_paths = nx.shortest_path(G) centrality = local_reaching_centrality # TODO This can be trivially parallelized. lrc = [ centrality(G, node, paths=paths, weight=weight, normalized=normalized) for node, paths in shortest_paths.items() ] max_lrc = max(lrc) return sum(max_lrc - c for c in lrc) / (len(G) - 1)
def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True): """Returns the local reaching centrality of a node in a directed graph. The *local reaching centrality* of a node in a directed graph is the proportion of other nodes reachable from that node [1]_. Parameters ---------- G : DiGraph A NetworkX DiGraph. v : node A node in the directed graph `G`. paths : dictionary (default=None) If this is not `None` it must be a dictionary representation of single-source shortest paths, as computed by, for example, :func:`networkx.shortest_path` with source node `v`. Use this keyword argument if you intend to invoke this function many times but don't want the paths to be recomputed each time. weight : None or string, optional (default=None) Attribute to use for edge weights. If `None`, each edge weight is assumed to be one. A higher weight implies a stronger connection between nodes and a *shorter* path length. normalized : bool, optional (default=True) Whether to normalize the edge weights by the total sum of edge weights. Returns ------- h : float The local reaching centrality of the node ``v`` in the graph ``G``. Examples -------- >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3)]) >>> nx.local_reaching_centrality(G, 3) 0.0 >>> G.add_edge(3, 2) >>> nx.local_reaching_centrality(G, 3) 0.5 See also -------- global_reaching_centrality References ---------- .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek. "Hierarchy Measure for Complex Networks." *PLoS ONE* 7.3 (2012): e33799. https://doi.org/10.1371/journal.pone.0033799 """ if paths is None: if nx.is_negatively_weighted(G, weight=weight): raise nx.NetworkXError('edge weights must be positive') total_weight = G.size(weight=weight) if total_weight <= 0: raise nx.NetworkXError('Size of G must be positive') if weight is not None: # Interpret weights as lengths. def as_distance(u, v, d): return total_weight / d.get(weight, 1) paths = nx.shortest_path(G, source=v, weight=as_distance) else: paths = nx.shortest_path(G, source=v) # If the graph is unweighted, simply return the proportion of nodes # reachable from the source node ``v``. if weight is None and G.is_directed(): return (len(paths) - 1) / (len(G) - 1) if normalized and weight is not None: norm = G.size(weight=weight) / G.size() else: norm = 1 # TODO This can be trivially parallelized. avgw = (_average_weight(G, path, weight=weight) for path in paths.values()) sum_avg_weight = sum(avgw) / norm return sum_avg_weight / (len(G) - 1)
def global_reaching_centrality(G, weight=None, normalized=True): """Returns the global reaching centrality of a directed graph. The *global reaching centrality* of a weighted directed graph is the average over all nodes of the difference between the local reaching centrality of the node and the greatest local reaching centrality of any node in the graph [1]_. For more information on the local reaching centrality, see :func:`local_reaching_centrality`. Informally, the local reaching centrality is the proportion of the graph that is reachable from the neighbors of the node. Parameters ---------- G : DiGraph A networkx DiGraph. weight : None or string, optional (default=None) Attribute to use for edge weights. If ``None``, each edge weight is assumed to be one. A higher weight implies a stronger connection between nodes and a *shorter* path length. normalized : bool, optional (default=True) Whether to normalize the edge weights by the total sum of edge weights. Returns ------- h : float The global reaching centrality of the graph. Examples -------- >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edge(1, 2) >>> G.add_edge(1, 3) >>> nx.global_reaching_centrality(G) 1.0 >>> G.add_edge(3, 2) >>> nx.global_reaching_centrality(G) 0.75 See also -------- local_reaching_centrality References ---------- .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek. "Hierarchy Measure for Complex Networks." *PLoS ONE* 7.3 (2012): e33799. https://dx.doi.org/10.1371/journal.pone.0033799 """ if nx.is_negatively_weighted(G, weight=weight): raise nx.NetworkXError('edge weights must be positive') total_weight = G.size(weight=weight) if total_weight <= 0: raise nx.NetworkXError('Size of G must be positive') # If provided, weights must be interpreted as connection strength # (so higher weights are more likely to be chosen). However, the # shortest path algorithms in NetworkX assume the provided "weight" # is actually a distance (so edges with higher weight are less # likely to be chosen). Therefore we need to invert the weights when # computing shortest paths. # # If weight is None, we leave it as-is so that the shortest path # algorithm can use a faster, unweighted algorithm. if weight is not None: as_distance = lambda u, v, d: total_weight / d.get(weight, 1) shortest_paths = nx.shortest_path(G, weight=as_distance) else: shortest_paths = nx.shortest_path(G) centrality = local_reaching_centrality # TODO This can be trivially parallelized. lrc = [centrality(G, node, paths=paths, weight=weight, normalized=normalized) for node, paths in shortest_paths.items()] max_lrc = max(lrc) return sum(max_lrc - c for c in lrc) / (len(G) - 1)
def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True): """Returns the local reaching centrality of a node in a directed graph. The *local reaching centrality* of a node in a directed graph is the proportion of other nodes reachable from that node [1]_. Parameters ---------- G : DiGraph A NetworkX DiGraph. v : node A node in the directed graph `G`. paths : dictionary (default=None) If this is not `None` it must be a dictionary representation of single-source shortest paths, as computed by, for example, :func:`networkx.shortest_path` with source node `v`. Use this keyword argument if you intend to invoke this function many times but don't want the paths to be recomputed each time. weight : None or string, optional (default=None) Attribute to use for edge weights. If `None`, each edge weight is assumed to be one. A higher weight implies a stronger connection between nodes and a *shorter* path length. normalized : bool, optional (default=True) Whether to normalize the edge weights by the total sum of edge weights. Returns ------- h : float The local reaching centrality of the node ``v`` in the graph ``G``. Examples -------- >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3)]) >>> nx.local_reaching_centrality(G, 3) 0.0 >>> G.add_edge(3, 2) >>> nx.local_reaching_centrality(G, 3) 0.5 See also -------- global_reaching_centrality References ---------- .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek. "Hierarchy Measure for Complex Networks." *PLoS ONE* 7.3 (2012): e33799. https://dx.doi.org/10.1371/journal.pone.0033799 """ if paths is None: if nx.is_negatively_weighted(G, weight=weight): raise nx.NetworkXError('edge weights must be positive') total_weight = G.size(weight=weight) if total_weight <= 0: raise nx.NetworkXError('Size of G must be positive') if weight is not None: # Interpret weights as lengths. as_distance = lambda u, v, d: total_weight / d.get(weight, 1) paths = nx.shortest_path(G, source=v, weight=as_distance) else: paths = nx.shortest_path(G, source=v) # If the graph is unweighted, simply return the proportion of nodes # reachable from the source node ``v``. if weight is None and G.is_directed(): return (len(paths) - 1) / (len(G) - 1) if normalized and weight is not None: norm = G.size(weight=weight) / G.size() else: norm = 1 # TODO This can be trivially parallelized. avgw = (_average_weight(G, path, weight=weight) for path in paths.values()) sum_avg_weight = sum(avgw) / norm return sum_avg_weight / (len(G) - 1)
''' A = np.loadtxt(open("Results/temp_adjMat.csv", "rb"), delimiter=",") G = nx.from_numpy_matrix(A) G.edges(data=True) nx.draw_networkx(G, pos=None, with_labels=True, font_weight='bold') plt.savefig("Results/inputGraph.png") EPSILON = 1e-7 # to prevent divided by zero weight = None edge_list = None method = "OTD" verbose = False print(nx.is_weighted(G)) print(nx.is_negatively_weighted(G)) #print(nx.negative_edge_cycle(G)) length = dict(nx.all_pairs_dijkstra_path_length(G, weight='weight')) hop_distance = dict(nx.all_pairs_bellman_ford_path_length(G, weight='weight')) #print(length) if not edge_list: edge_list = G.edges() print(edge_list) args = [(G, source, target, length, hop_distance, verbose, method) for source, target in edge_list] args scalar = 0