def test_complete_graphs(): for n in range(5, 25, 5): G = nx.complete_graph(n) assert_equal(n-1, nx.node_connectivity(G)) assert_equal(n-1, nx.node_connectivity(G.to_directed())) assert_equal(n-1, nx.edge_connectivity(G)) assert_equal(n-1, nx.edge_connectivity(G.to_directed()))
def test_brandes_erlebach(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4), (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8), (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) assert_equal(3, local_edge_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(3, nx.edge_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(2, local_node_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(2, nx.node_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal( 2, nx.edge_connectivity(G, **kwargs), # node 5 has degree 2 msg=msg.format(flow_func.__name__)) assert_equal(2, nx.node_connectivity(G, **kwargs), msg=msg.format(flow_func.__name__))
def test_complete_graphs(): for n in range(5, 25, 5): G = nx.complete_graph(n) assert_equal(n - 1, nx.node_connectivity(G)) assert_equal(n - 1, nx.node_connectivity(G.to_directed())) assert_equal(n - 1, nx.edge_connectivity(G)) assert_equal(n - 1, nx.edge_connectivity(G.to_directed()))
def test_directed_edge_connectivity(): G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges assert_equal(1, nx.edge_connectivity(G)) assert_equal(1, nx.local_edge_connectivity(G, 1, 4)) assert_equal(1, nx.edge_connectivity(G, 1, 4)) assert_equal(2, nx.edge_connectivity(D)) assert_equal(2, nx.local_edge_connectivity(D, 1, 4)) assert_equal(2, nx.edge_connectivity(D, 1, 4))
def test_directed_edge_connectivity(): G = nx.cycle_graph(10,create_using=nx.DiGraph()) # only one direction D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges assert_equal(1, nx.edge_connectivity(G)) assert_equal(1, nx.local_edge_connectivity(G,1,4)) assert_equal(1, nx.edge_connectivity(G,1,4)) assert_equal(2, nx.edge_connectivity(D)) assert_equal(2, nx.local_edge_connectivity(D,1,4)) assert_equal(2, nx.edge_connectivity(D,1,4))
def print_robustness(): #What is the smallest number of nodes that can be removed from this graph in order to disconnect it? # 1) whole graph: nx.node_connectivity(G) #1 - too small, When higher - it is good nx.minimum_node_cut(G) #{'Чкаловская'} nx.edge_connectivity(G) # 1 nx.minimum_edge_cut(G) #{('Марьино', 'Чкаловская')} # 2) concrete path nx.node_connectivity(G, 'Киевская', 'Чкаловская') #2 - better nx.minimum_node_cut(G, 'Киевская', 'Чкаловская') #{'Курская', 'Сретенский бульвар'} nx.edge_connectivity(G, 'Киевская', 'Чкаловская') #2 - better nx.minimum_edge_cut(G, 'Киевская', 'Чкаловская') #{('Курская', 'Чкаловская'), ('Сретенский бульвар', 'Чкаловская')}
def search_one(self,words_lst): print(words_lst) ROOT = 'ROOT' result = [] words_lst_dct_base = self.to_dict(words_lst) for word in words_lst: forbiden =['MPH','DONGHAO','DYH','LOUC','HSH','XIAOQU'] if word.split('/')[1] in forbiden: #if self.di.has_node(ROOT) and self.di.has_node(word) and nx.edge_connectivity(self.di,ROOT,word)>0: if True: #shortest_path = nx.get_shortest_path(self.di,ROOT,word) #result.extend(shortest_path) result.append(word) continue if self.di.has_node(ROOT) and self.di.has_node(word) and nx.edge_connectivity(self.di,ROOT,word)>0: print('bellman_ford_path:',ROOT,word) best_result = nx.shortest_path(self.di,ROOT,word,'wealth') #best_result= nx.bellman_ford_path(self.di,ROOT,word,'wealth') print(best_result) result.extend(best_result) print(result) ROOT = word else: if self.di.has_node('ROOT') and self.di.has_node(word) and nx.edge_connectivity(self.di,'ROOT',word)>0: best_result = nx.shortest_path(self.di,'ROOT',word,'wealth') #best_result = nx.bellman_ford_path(self.di,'ROOT',word,'wealth') result.extend(best_result) dct = self.to_dict(result) print(dct) output_result = [] for key in myconfig.COLUMNS: value = dct.get(key,'nan') if value=='nan': continue elif '&' in value: words = value.split('&') l0 = 0 w0 = "" for word in words: standard_value = words_lst_dct_base.get(key,'nan') print(standard_value) print(word) #pdb.set_trace() sub_word = list(standard_value) and list(word) if standard_value == 'nan': sub_word = list(word) l1 = len(sub_word) if l1>l0: w0 = word l0 = l1 output_result.append('%s/%s '%(w0,key)) else: output_result.append('%s/%s '%(value,key)) return " ".join(output_result) + " "
def calculate_edge_connectivity(graph, graph_type): if graph_type == 'subscription': user_nodes = set(n for n, d in graph.nodes(data=True) if d.get('bipartite') == 0) results = [ nx.edge_connectivity(graph, s=start, t=end) for start, end in combinations(user_nodes, 2) ] return min(results) if results else 0 elif graph_type == 'mention': return nx.edge_connectivity(graph)
def test_brandes_erlebach(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4), (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8), (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) assert_equal(3, nx.local_edge_connectivity(G, 1, 11)) assert_equal(3, nx.edge_connectivity(G, 1, 11)) assert_equal(2, nx.local_node_connectivity(G, 1, 11)) assert_equal(2, nx.node_connectivity(G, 1, 11)) assert_equal(2, nx.edge_connectivity(G)) # node 5 has degree 2 assert_equal(2, nx.node_connectivity(G))
def test_brandes_erlebach(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(2,3),(2,6),(3,4), (3,6),(4,6),(4,7),(5,7),(6,8),(6,9),(7,8), (7,10),(8,11),(9,10),(9,11),(10,11)]) assert_equal(3,nx.local_edge_connectivity(G,1,11)) assert_equal(3,nx.edge_connectivity(G,1,11)) assert_equal(2,nx.local_node_connectivity(G,1,11)) assert_equal(2,nx.node_connectivity(G,1,11)) assert_equal(2,nx.edge_connectivity(G)) # node 5 has degree 2 assert_equal(2,nx.node_connectivity(G))
def test_complete_graphs(): for n in range(5, 20, 5): for flow_func in flow_funcs: G = nx.complete_graph(n) errmsg = f"Assertion failed in function: {flow_func.__name__}" assert n - 1 == nx.node_connectivity(G, flow_func=flow_func), errmsg assert n - 1 == nx.node_connectivity(G.to_directed(), flow_func=flow_func), errmsg assert n - 1 == nx.edge_connectivity(G, flow_func=flow_func), errmsg assert n - 1 == nx.edge_connectivity(G.to_directed(), flow_func=flow_func), errmsg
def test_directed_edge_connectivity(): G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges for flow_func in flow_funcs: errmsg = f"Assertion failed in function: {flow_func.__name__}" assert 1 == nx.edge_connectivity(G, flow_func=flow_func), errmsg assert 1 == local_edge_connectivity(G, 1, 4, flow_func=flow_func), errmsg assert 1 == nx.edge_connectivity(G, 1, 4, flow_func=flow_func), errmsg assert 2 == nx.edge_connectivity(D, flow_func=flow_func), errmsg assert 2 == local_edge_connectivity(D, 1, 4, flow_func=flow_func), errmsg assert 2 == nx.edge_connectivity(D, 1, 4, flow_func=flow_func), errmsg
def test_complete_graphs(): for n in range(5, 20, 5): for flow_func in flow_funcs: G = nx.complete_graph(n) assert_equal(n-1, nx.node_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(n-1, nx.node_connectivity(G.to_directed(), flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(n-1, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(n-1, nx.edge_connectivity(G.to_directed(), flow_func=flow_func), msg=msg.format(flow_func.__name__))
def test_not_connected(): G = nx.Graph() nx.add_path(G, [1, 2, 3]) nx.add_path(G, [4, 5]) for flow_func in flow_funcs: assert nx.node_connectivity(G) == 0, msg.format(flow_func.__name__) assert nx.edge_connectivity(G) == 0, msg.format(flow_func.__name__)
def tarjan_condition(edge: Tuple[int, int], graph: nx.DiGraph, edges_used: Set[Tuple[int, int]], connectivity: int, destination: str) -> bool: """ Checks the condition for arborescence decomposition construction according to Tarjan (1974). :param edge: the edge for which the condition should be checked :param graph: the original graph of the arborescence decomposition :param edges_used: all edges used for arborescences up to this point :param connectivity: the desired connectivity, i.e. the number of arborescences that still need to be constructed :param destination: the destination vertex of the decomposition :return: a boolean, indicating if the condition is fulfilled """ if connectivity == 0: return True reduced_graph = graph.copy() reduced_graph.remove_edges_from(edges_used) reduced_graph.remove_edge(edge[0], edge[1]) # TODO: not mentioned in Tarjan? for i in range(1, connectivity + 1): reduced_graph.add_edge(edge[0], f"helper_node_{i}") reduced_graph.add_edge(f"helper_node_{i}", destination) return nx.edge_connectivity(reduced_graph, edge[0], edge[1]) >= connectivity
def test_petersen(): G = nx.petersen_graph() for flow_func in flow_funcs: assert 3 == nx.node_connectivity(G, flow_func=flow_func), msg.format( flow_func.__name__) assert 3 == nx.edge_connectivity(G, flow_func=flow_func), msg.format( flow_func.__name__)
def test_octahedral(): G = nx.octahedral_graph() for flow_func in flow_funcs: assert 4 == nx.node_connectivity(G, flow_func=flow_func), msg.format( flow_func.__name__) assert 4 == nx.edge_connectivity(G, flow_func=flow_func), msg.format( flow_func.__name__)
def test_empty_graphs(): for k in range(5, 25, 5): G = nx.empty_graph(k) for flow_func in flow_funcs: errmsg = f"Assertion failed in function: {flow_func.__name__}" assert 0 == nx.node_connectivity(G, flow_func=flow_func), errmsg assert 0 == nx.edge_connectivity(G, flow_func=flow_func), errmsg
def test_edge_connectivity_flow_vs_stoer_wagner(): graph_funcs = [ nx.icosahedral_graph, nx.octahedral_graph, nx.dodecahedral_graph ] for graph_func in graph_funcs: G = graph_func() assert nx.stoer_wagner(G)[0] == nx.edge_connectivity(G)
def test_graph_from_pr_2053(): G = nx.Graph() G.add_edges_from([ ("A", "B"), ("A", "D"), ("A", "F"), ("A", "G"), ("B", "C"), ("B", "D"), ("B", "G"), ("C", "D"), ("C", "E"), ("C", "Z"), ("D", "E"), ("D", "F"), ("E", "F"), ("E", "Z"), ("F", "Z"), ("G", "Z"), ]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) errmsg = f"Assertion failed in function: {flow_func.__name__}" # edge disjoint paths edge_paths = list(nx.edge_disjoint_paths(G, "A", "Z", **kwargs)) assert are_edge_disjoint_paths(G, edge_paths), errmsg assert nx.edge_connectivity(G, "A", "Z") == len(edge_paths), errmsg # node disjoint paths node_paths = list(nx.node_disjoint_paths(G, "A", "Z", **kwargs)) assert are_node_disjoint_paths(G, node_paths), errmsg assert nx.node_connectivity(G, "A", "Z") == len(node_paths), errmsg
def draw_graph(nodes, edges, graphs_dir, default_lang='all'): lang_graph = nx.MultiDiGraph() lang_graph.add_nodes_from(nodes) for edge in edges: if edges[edge] == 0: lang_graph.add_edge(edge[0], edge[1]) else: lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge])) # print graph info in stdout # degree centrality print('-----------------\n\n') print(default_lang) print(nx.info(lang_graph)) try: # When ties are associated to some positive aspects such as friendship or collaboration, # indegree is often interpreted as a form of popularity, and outdegree as gregariousness. DC = nx.degree_centrality(lang_graph) max_dc = max(DC.values()) max_dc_list = [item for item in DC.items() if item[1] == max_dc] except ZeroDivisionError: max_dc_list = [] # https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8 print('maxdc', str(max_dc_list), sep=': ') # assortativity coef AC = nx.degree_assortativity_coefficient(lang_graph) print('AC', str(AC), sep=': ') # connectivity print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph)) print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph)) print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph)) print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph)) print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph)) print("число вершинной связности: ", nx.node_connectivity(lang_graph)) print("число рёберной связности: ", nx.edge_connectivity(lang_graph)) # other info print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph)) print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(), key=itemgetter(1), reverse=True)) # best for small graphs, and our graphs are pretty small print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True)) plt.figure(figsize=(16.0, 9.0), dpi=80) plt.axis('off') pos = graphviz_layout(lang_graph) nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True) nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green') nx.draw_networkx_edge_labels(lang_graph, pos, edges) # saving file to draw it with dot-graphviz # changing overall graph view, default is top-bottom lang_graph.graph['graph'] = {'rankdir': 'LR'} # marking with blue nodes with maximum degree centrality for max_dc_node in max_dc_list: lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue' write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot')) # plt.show() plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100) plt.close()
def kOutOfN(self, k): flat_list = [item for sublist in list(self.sys_cond.values()) for item in sublist] random_combo = sample(flat_list, k) """ Changing the states of randomly selected configuration to 'up' or 'down'. """ for i, val in enumerate(random_combo): random_combo[i] = self.list_complement(val) index_list = [] for i in range(len(self.sys_cond.values())): index_list.append(len(self.sys_cond[str(i + 1)])) index_list = list(accumulate(index_list, add)) total_rel = defaultdict(list) for i, val in enumerate(random_combo): if val.count(1) < nx.edge_connectivity(self.graph): for key, index in enumerate(index_list): if flat_list.index(val) < index: if self.sys_states[key] == 'up': self.sys_states[key] = 'down' else: self.sys_states[key] = 'up' rel = self.get_total_rel() return rel
def test_edge_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50,0.2) cutset = nx.minimum_edge_cut(G) assert_equal(nx.edge_connectivity(G), len(cutset)) G.remove_edges_from(cutset) assert_false(nx.is_connected(G))
def embed_metrics_connectivity(graph, metrics, g, namefield): connectivity = dict() print('connectivity_edge') connectivity['connectivity_edge'] = networkx.edge_connectivity(g) print('connectivity_node') connectivity['connectivity_node'] = networkx.node_connectivity(g) return connectivity
def test_graph_from_pr_2053(): G = nx.Graph() G.add_edges_from([ ('A', 'B'), ('A', 'D'), ('A', 'F'), ('A', 'G'), ('B', 'C'), ('B', 'D'), ('B', 'G'), ('C', 'D'), ('C', 'E'), ('C', 'Z'), ('D', 'E'), ('D', 'F'), ('E', 'F'), ('E', 'Z'), ('F', 'Z'), ('G', 'Z')]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge disjoint paths edge_paths = list(nx.edge_disjoint_paths(G, 'A', 'Z', **kwargs)) assert_true(are_edge_disjoint_paths(G, edge_paths), msg=msg.format(flow_func.__name__)) assert_equal( nx.edge_connectivity(G, 'A', 'Z'), len(edge_paths), msg=msg.format(flow_func.__name__), ) # node disjoint paths node_paths = list(nx.node_disjoint_paths(G, 'A', 'Z', **kwargs)) assert_true(are_node_disjoint_paths(G, node_paths), msg=msg.format(flow_func.__name__)) assert_equal( nx.node_connectivity(G, 'A', 'Z'), len(node_paths), msg=msg.format(flow_func.__name__), )
def find_which_nodes_and_edges_to_remove(G, n1, n2): a = nx.node_connectivity(G, n1, n2) b = nx.minimum_node_cut(G, n1, n2) c = nx.edge_connectivity(G, n1, n2) d = nx.minimum_edge_cut(G, n1, n2) print(a, b, c, d) return (a, b, c, d)
def test_edge_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50, 0.2) cutset = nx.minimum_edge_cut(G) assert_equal(nx.edge_connectivity(G), len(cutset)) G.remove_edges_from(cutset) assert_false(nx.is_connected(G))
def test_graph_from_pr_2053(): G = nx.Graph() G.add_edges_from([ ('A', 'B'), ('A', 'D'), ('A', 'F'), ('A', 'G'), ('B', 'C'), ('B', 'D'), ('B', 'G'), ('C', 'D'), ('C', 'E'), ('C', 'Z'), ('D', 'E'), ('D', 'F'), ('E', 'F'), ('E', 'Z'), ('F', 'Z'), ('G', 'Z') ]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge disjoint paths edge_paths = list(nx.edge_disjoint_paths(G, 'A', 'Z', **kwargs)) assert_true(are_edge_disjoint_paths(G, edge_paths), msg=msg.format(flow_func.__name__)) assert_equal( nx.edge_connectivity(G, 'A', 'Z'), len(edge_paths), msg=msg.format(flow_func.__name__), ) # node disjoint paths node_paths = list(nx.node_disjoint_paths(G, 'A', 'Z', **kwargs)) assert_true(are_node_disjoint_paths(G, node_paths), msg=msg.format(flow_func.__name__)) assert_equal( nx.node_connectivity(G, 'A', 'Z'), len(node_paths), msg=msg.format(flow_func.__name__), )
def test_tutte(): G = nx.tutte_graph() for flow_func in flow_funcs: assert_equal(3, nx.node_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__))
def test_icosahedral(): G=nx.icosahedral_graph() for flow_func in flow_funcs: assert_equal(5, nx.node_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(5, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__))
def main(): done = [ 'dfn_58.graphml', 'colt_153.graphml', 'gts_ce_149.graphml', 'intellifiber_73.graphml', 'triangle.graphml' ] networks = ['abilene_11.graphml'] for net_file in networks: node_connectivity = {} edge_connectivity = {} graphml_network = nx.read_graphml(net_file, node_type=int) for u in graphml_network.nodes(): u_id = f'pop{u}' node_connectivity[u_id] = {} edge_connectivity[u_id] = {} for v in graphml_network.nodes(): v_id = f'pop{v}' if u_id != v_id: node_connectivity[u_id][v_id] = nx.node_connectivity( graphml_network, s=u, t=v) edge_connectivity[u_id][v_id] = nx.edge_connectivity( graphml_network, s=u, t=v) os.makedirs('connectivity/', exist_ok=True) with open(f'connectivity/{net_file}_node_con.json', 'w') as fp: json.dump(node_connectivity, fp) with open(f'connectivity/{net_file}_edge_con.json', 'w') as fp: json.dump(edge_connectivity, fp)
def is_k_edge_connected(G, k): """ Tests to see if a graph is k-edge-connected See Also -------- is_locally_k_edge_connected Example ------- >>> G = nx.barbell_graph(10, 0) >>> is_k_edge_connected(G, k=1) True >>> is_k_edge_connected(G, k=2) False """ if k < 1: raise ValueError('k must be positive, not {}'.format(k)) # First try to quickly determine if G is not k-edge-connected if G.number_of_nodes() < k + 1: return False elif any(d < k for n, d in G.degree()): return False else: # Otherwise perform the full check if k == 1: return nx.is_connected(G) elif k == 2: return not nx.has_bridges(G) else: # return nx.edge_connectivity(G, cutoff=k) >= k return nx.edge_connectivity(G) >= k
def test_directed_edge_connectivity(): G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges for flow_func in flow_funcs: assert_equal(1, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(1, local_edge_connectivity(G, 1, 4, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(1, nx.edge_connectivity(G, 1, 4, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(2, nx.edge_connectivity(D, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(2, local_edge_connectivity(D, 1, 4, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(2, nx.edge_connectivity(D, 1, 4, flow_func=flow_func), msg=msg.format(flow_func.__name__))
def data_analysis(self, graph): data_vec = [0] * 13 num_vertex = nx.number_of_nodes(graph) data_vec[0] = nx.average_clustering(graph) sq_values = list(nx.square_clustering(graph).values()) data_vec[1] = sum(sq_values) / len(sq_values) g = nx.path_graph(num_vertex) data_vec[2] = nx.average_shortest_path_length( graph) / nx.average_shortest_path_length(g) data_vec[3] = nx.degree_pearson_correlation_coefficient(graph) if math.isnan(data_vec[3]) is True: data_vec[3] = 0 data_vec[4] = nx.diameter(graph) / (num_vertex - 1) data_vec[5] = nx.density(graph) data_vec[6] = nx.edge_connectivity(graph) / (num_vertex - 1) g = nx.star_graph(num_vertex - 1) Freeman_degree_norm = self.freeman_centralization( nx.degree_centrality(g)) Freeman_close_norm = self.freeman_centralization( nx.closeness_centrality(g)) Freeman_between_norm = self.freeman_centralization( nx.betweenness_centrality(g)) # need to change Freeman_eigen_norm = self.freeman_centralization( nx.eigenvector_centrality_numpy(g)) data_vec[7] = self.freeman_centralization( nx.degree_centrality(graph)) / Freeman_degree_norm data_vec[8] = self.freeman_centralization( nx.closeness_centrality(graph)) / Freeman_close_norm data_vec[9] = self.freeman_centralization( nx.betweenness_centrality(graph)) / Freeman_between_norm # warning, the way it normalized may not correct data_vec[10] = self.freeman_centralization( nx.eigenvector_centrality_numpy(graph)) / Freeman_eigen_norm egvl_lap = nx.laplacian_spectrum(graph) egvl_lap = np.sort(egvl_lap) egvl_lap = np.delete(egvl_lap, 0, 0) summ = 0 for mu in egvl_lap: summ += (1 / mu) summ = summ * num_vertex data_vec[11] = (num_vertex - 1) / summ # for simple graph(adj matrix is symmetric), eigenvalue must be real number. egvl_adj = np.real(nx.adjacency_spectrum(graph)) data_vec[12] = max(egvl_adj) / (num_vertex - 1) return data_vec
def diffnet_connectivity( n, src=None, tgt=None): ''' Compute the connectivity in the difference network of n[i,j]. If src and tgt are given, compute the local connectivity between the src and tgt nodes. ''' g = nx.from_numpy_matrix( n) return nx.edge_connectivity( g, src, tgt)
def test_empty_graphs(): for k in range(5, 25, 5): G = nx.empty_graph(k) for flow_func in flow_funcs: assert_equal(0, nx.node_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(0, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__))
def test_white_harary_2(): # Figure 8 white and harary (2001) # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) G.add_edge(0,4) # kappa <= lambda <= delta assert_equal(3, min(nx.core_number(G).values())) assert_equal(1, nx.node_connectivity(G)) assert_equal(1, nx.edge_connectivity(G))
def test_edge_connectivity_flow_vs_stoer_wagner(): graph_funcs = [ nx.icosahedral_graph, nx.octahedral_graph, nx.dodecahedral_graph, ] for graph_func in graph_funcs: G = graph_func() assert_equal(nx.stoer_wagner(G)[0], nx.edge_connectivity(G))
def test_not_connected(): G = nx.Graph() G.add_path([1, 2, 3]) G.add_path([4, 5]) for flow_func in flow_funcs: assert_equal(nx.node_connectivity(G), 0, msg=msg.format(flow_func.__name__)) assert_equal(nx.edge_connectivity(G), 0, msg=msg.format(flow_func.__name__))
def _memo_connectivity(G, u, v, memo): edge = (u, v) if edge in memo: return memo[edge] if not G.is_directed(): redge = (v, u) if redge in memo: return memo[redge] memo[edge] = nx.edge_connectivity(G, *edge) return memo[edge]
def test_edge_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50,0.2) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = next(ccs)[0] G.add_edges_from( (start,c[0]) for c in ccs ) cutset = nx.minimum_edge_cut(G) assert_equal(nx.edge_connectivity(G), len(cutset)) G.remove_edges_from(cutset) assert_false(nx.is_connected(G))
def test_brandes_erlebach(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4), (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8), (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) assert_equal(3, local_edge_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(3, nx.edge_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(2, local_node_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(2, nx.node_connectivity(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(2, nx.edge_connectivity(G, **kwargs), # node 5 has degree 2 msg=msg.format(flow_func.__name__)) assert_equal(2, nx.node_connectivity(G, **kwargs), msg=msg.format(flow_func.__name__))
def _assert_subgraph_edge_connectivity(G, ccs_subgraph, k): """ tests properties of k-edge-connected subgraphs the actual edge connectivity should be no less than k unless the cc is a single node. """ for cc in ccs_subgraph: C = G.subgraph(cc) if len(cc) > 1: connectivity = nx.edge_connectivity(C) assert_greater_equal(connectivity, k)
def test_edge_cutset_random_graphs(): for flow_func in flow_funcs: for i in range(3): G = nx.fast_gnp_random_graph(50, 0.25) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = arbitrary_element(next(ccs)) G.add_edges_from((start, arbitrary_element(c)) for c in ccs) cutset = nx.minimum_edge_cut(G, flow_func=flow_func) assert_equal(nx.edge_connectivity(G), len(cutset), msg=msg.format(flow_func.__name__)) G.remove_edges_from(cutset) assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__))
def test_white_harary_1(): # Figure 1b white and harary (2001) # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF # A graph with high adhesion (edge connectivity) and low cohesion # (vertex connectivity) G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) G.remove_node(7) for i in range(4,7): G.add_edge(0,i) G = nx.disjoint_union(G, nx.complete_graph(4)) G.remove_node(G.order()-1) for i in range(7,10): G.add_edge(0,i) assert_equal(1, nx.node_connectivity(G)) assert_equal(3, nx.edge_connectivity(G))
def _assert_local_cc_edge_connectivity(G, ccs_local, k, memo): """ tests properties of k-edge-connected components the local edge connectivity between each pair of nodes in the the original graph should be no less than k unless the cc is a single node. """ for cc in ccs_local: if len(cc) > 1: # Strategy for testing a bit faster: If the subgraph has high edge # connectivity then it must have local connectivity C = G.subgraph(cc) connectivity = nx.edge_connectivity(C) if connectivity < k: # Otherwise do the brute force (with memoization) check _all_pairs_connectivity(G, cc, k, memo)
def is_k_edge_connected(G, k): """Tests to see if a graph is k-edge-connected. Is it impossible to disconnect the graph by removing fewer than k edges? If so, then G is k-edge-connected. Parameters ---------- G : NetworkX graph An undirected graph. k : integer edge connectivity to test for Returns ------- boolean True if G is k-edge-connected. See Also -------- :func:`is_locally_k_edge_connected` Example ------- >>> G = nx.barbell_graph(10, 0) >>> nx.is_k_edge_connected(G, k=1) True >>> nx.is_k_edge_connected(G, k=2) False """ if k < 1: raise ValueError('k must be positive, not {}'.format(k)) # First try to quickly determine if G is not k-edge-connected if G.number_of_nodes() < k + 1: return False elif any(d < k for n, d in G.degree()): return False else: # Otherwise perform the full check if k == 1: return nx.is_connected(G) elif k == 2: return not nx.has_bridges(G) else: return nx.edge_connectivity(G, cutoff=k) >= k
def test_karate(): G = nx.karate_club_graph() for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge disjoint paths edge_dpaths = list(nx.edge_disjoint_paths(G, 0, 33, **kwargs)) assert_true(are_edge_disjoint_paths(G, edge_dpaths), msg=msg.format(flow_func.__name__)) assert_equal( nx.edge_connectivity(G, 0, 33), len(edge_dpaths), msg=msg.format(flow_func.__name__), ) # node disjoint paths node_dpaths = list(nx.node_disjoint_paths(G, 0, 33, **kwargs)) assert_true(are_node_disjoint_paths(G, node_dpaths), msg=msg.format(flow_func.__name__)) assert_equal( nx.node_connectivity(G, 0, 33), len(node_dpaths), msg=msg.format(flow_func.__name__), )
def test_florentine_families(): G = nx.florentine_families_graph() for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge disjoint paths edge_dpaths = list(nx.edge_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs)) assert_true(are_edge_disjoint_paths(G, edge_dpaths), msg=msg.format(flow_func.__name__)) assert_equal( nx.edge_connectivity(G, 'Medici', 'Strozzi'), len(edge_dpaths), msg=msg.format(flow_func.__name__), ) # node disjoint paths node_dpaths = list(nx.node_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs)) assert_true(are_node_disjoint_paths(G, node_dpaths), msg=msg.format(flow_func.__name__)) assert_equal( nx.node_connectivity(G, 'Medici', 'Strozzi'), len(node_dpaths), msg=msg.format(flow_func.__name__), )
def visualize(graph): import networkx as nx import matplotlib.pyplot as plt # from networkx import graphviz_layout G = nx.Graph() for node, remotes in graph.items(): # print node[:8] for r in set(remotes): # print '\t', r[:8] G.add_edge(node, r, weight=weight(node, r)) # G.add_edge(node, r) # print 'estrada_index', nx.estrada_index(G) # print 'eigenvector_centrality', nx.eigenvector_centrality(G) # print 'degree_centrality', nx.degree_centrality(G) # print 'communicability', nx.communicability(G) num_peers = [len(v) for v in graph.values()] metrics = OrderedDict(num_nodes=len(graph)) metrics['max_peers'] = max(num_peers) metrics['min_peers'] = min(num_peers) metrics['avg_peers'] = sum(num_peers) / len(num_peers) metrics['diameter '] = nx.diameter(G) metrics['edge_connectivity'] = nx.edge_connectivity(G) metrics['avg_shortest_path'] = nx.average_shortest_path_length(G) text = '' for k, v in metrics.items(): text += '%s: %.2f\n' % (k, v) # pos = nx.graphviz_layout(G, prog='twopi', args='') pos = nx.spring_layout(G) plt.figure(figsize=(8, 8)) nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False) plt.text(0.02, 0.02, text, transform=plt.gca().transAxes) plt.axis('equal') plt.savefig('circular_tree.png') plt.show()
def extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False): """ Calculate extended topological stats and metrics for a graph. Many of these algorithms have an inherently high time complexity. Global topological analysis of large complex networks is extremely time consuming and may exhaust computer memory. Consider using function arguments to not run metrics that require computation of a full matrix of paths if they will not be needed. Parameters ---------- G : networkx multidigraph connectivity : bool if True, calculate node and edge connectivity anc : bool if True, calculate average node connectivity ecc : bool if True, calculate shortest paths, eccentricity, and topological metrics that use eccentricity bc : bool if True, calculate node betweenness centrality cc : bool if True, calculate node closeness centrality Returns ------- stats : dict dictionary of network measures containing the following elements (some only calculated/returned optionally, based on passed parameters): - avg_neighbor_degree - avg_neighbor_degree_avg - avg_weighted_neighbor_degree - avg_weighted_neighbor_degree_avg - degree_centrality - degree_centrality_avg - clustering_coefficient - clustering_coefficient_avg - clustering_coefficient_weighted - clustering_coefficient_weighted_avg - pagerank - pagerank_max_node - pagerank_max - pagerank_min_node - pagerank_min - node_connectivity - node_connectivity_avg - edge_connectivity - eccentricity - diameter - radius - center - periphery - closeness_centrality - closeness_centrality_avg - betweenness_centrality - betweenness_centrality_avg """ stats = {} full_start_time = time.time() # create a DiGraph from the MultiDiGraph, for those metrics that require it G_dir = nx.DiGraph(G) # create an undirected Graph from the MultiDiGraph, for those metrics that # require it G_undir = nx.Graph(G) # get the largest strongly connected component, for those metrics that # require strongly connected graphs G_strong = get_largest_component(G, strongly=True) # average degree of the neighborhood of each node, and average for the graph avg_neighbor_degree = nx.average_neighbor_degree(G) stats['avg_neighbor_degree'] = avg_neighbor_degree stats['avg_neighbor_degree_avg'] = sum(avg_neighbor_degree.values())/len(avg_neighbor_degree) # average weighted degree of the neighborhood of each node, and average for # the graph avg_weighted_neighbor_degree = nx.average_neighbor_degree(G, weight='length') stats['avg_weighted_neighbor_degree'] = avg_weighted_neighbor_degree stats['avg_weighted_neighbor_degree_avg'] = sum(avg_weighted_neighbor_degree.values())/len(avg_weighted_neighbor_degree) # degree centrality for a node is the fraction of nodes it is connected to degree_centrality = nx.degree_centrality(G) stats['degree_centrality'] = degree_centrality stats['degree_centrality_avg'] = sum(degree_centrality.values())/len(degree_centrality) # calculate clustering coefficient for the nodes stats['clustering_coefficient'] = nx.clustering(G_undir) # average clustering coefficient for the graph stats['clustering_coefficient_avg'] = nx.average_clustering(G_undir) # calculate weighted clustering coefficient for the nodes stats['clustering_coefficient_weighted'] = nx.clustering(G_undir, weight='length') # average clustering coefficient (weighted) for the graph stats['clustering_coefficient_weighted_avg'] = nx.average_clustering(G_undir, weight='length') # pagerank: a ranking of the nodes in the graph based on the structure of # the incoming links pagerank = nx.pagerank(G_dir, weight='length') stats['pagerank'] = pagerank # node with the highest page rank, and its value pagerank_max_node = max(pagerank, key=lambda x: pagerank[x]) stats['pagerank_max_node'] = pagerank_max_node stats['pagerank_max'] = pagerank[pagerank_max_node] # node with the lowest page rank, and its value pagerank_min_node = min(pagerank, key=lambda x: pagerank[x]) stats['pagerank_min_node'] = pagerank_min_node stats['pagerank_min'] = pagerank[pagerank_min_node] # if True, calculate node and edge connectivity if connectivity: start_time = time.time() # node connectivity is the minimum number of nodes that must be removed # to disconnect G or render it trivial stats['node_connectivity'] = nx.node_connectivity(G_strong) # edge connectivity is equal to the minimum number of edges that must be # removed to disconnect G or render it trivial stats['edge_connectivity'] = nx.edge_connectivity(G_strong) log('Calculated node and edge connectivity in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate average node connectivity if anc: # mean number of internally node-disjoint paths between each pair of # nodes in G, i.e., the expected number of nodes that must be removed to # disconnect a randomly selected pair of non-adjacent nodes start_time = time.time() stats['node_connectivity_avg'] = nx.average_node_connectivity(G) log('Calculated average node connectivity in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate shortest paths, eccentricity, and topological metrics # that use eccentricity if ecc: # precompute shortest paths between all nodes for eccentricity-based # stats start_time = time.time() sp = {source:dict(nx.single_source_dijkstra_path_length(G_strong, source, weight='length')) for source in G_strong.nodes()} log('Calculated shortest path lengths in {:,.2f} seconds'.format(time.time() - start_time)) # eccentricity of a node v is the maximum distance from v to all other # nodes in G eccentricity = nx.eccentricity(G_strong, sp=sp) stats['eccentricity'] = eccentricity # diameter is the maximum eccentricity diameter = nx.diameter(G_strong, e=eccentricity) stats['diameter'] = diameter # radius is the minimum eccentricity radius = nx.radius(G_strong, e=eccentricity) stats['radius'] = radius # center is the set of nodes with eccentricity equal to radius center = nx.center(G_strong, e=eccentricity) stats['center'] = center # periphery is the set of nodes with eccentricity equal to the diameter periphery = nx.periphery(G_strong, e=eccentricity) stats['periphery'] = periphery # if True, calculate node closeness centrality if cc: # closeness centrality of a node is the reciprocal of the sum of the # shortest path distances from u to all other nodes start_time = time.time() closeness_centrality = nx.closeness_centrality(G, distance='length') stats['closeness_centrality'] = closeness_centrality stats['closeness_centrality_avg'] = sum(closeness_centrality.values())/len(closeness_centrality) log('Calculated closeness centrality in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate node betweenness centrality if bc: # betweenness centrality of a node is the sum of the fraction of # all-pairs shortest paths that pass through node start_time = time.time() betweenness_centrality = nx.betweenness_centrality(G, weight='length') stats['betweenness_centrality'] = betweenness_centrality stats['betweenness_centrality_avg'] = sum(betweenness_centrality.values())/len(betweenness_centrality) log('Calculated betweenness centrality in {:,.2f} seconds'.format(time.time() - start_time)) log('Calculated extended stats in {:,.2f} seconds'.format(time.time()-full_start_time)) return stats
def test_petersen(): G = nx.petersen_graph() assert_equal(3, nx.node_connectivity(G)) assert_equal(3, nx.edge_connectivity(G))
def test_empty_graphs(): for k in range(5, 25, 5): G = nx.empty_graph(k) assert_equal(0, nx.node_connectivity(G)) assert_equal(0, nx.edge_connectivity(G))
def test_not_weakly_connected(): G = nx.DiGraph() G.add_path([1,2,3]) G.add_path([4,5]) assert_equal(nx.node_connectivity(G), 0) assert_equal(nx.edge_connectivity(G), 0)
def test_edge_missing_target(): G = nx.path_graph(4) nx.edge_connectivity(G,1, 10)