def test_torrents_and_ferraro_detail_3_and_4(): solution = { 3: [ {25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 42}, {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 61}, {63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 79, 80}, {81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 93, 94, 95, 99, 100}, {39, 40, 41, 42, 43}, {58, 59, 60, 61, 62}, {76, 77, 78, 79, 80}, {96, 97, 98, 99, 100}, ], 4: [ {35, 36, 37, 38, 42}, {39, 40, 41, 42, 43}, {54, 55, 56, 57, 61}, {58, 59, 60, 61, 62}, {73, 74, 75, 79, 80}, {76, 77, 78, 79, 80}, {93, 94, 95, 99, 100}, {96, 97, 98, 99, 100}, ], } G = torrents_and_ferraro_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
def test_torrents_and_ferraro_detail_3_and_4(): solution = { 3: [{25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 42}, {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 61}, {63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 79, 80}, {81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 93, 94, 95, 99, 100}, {39, 40, 41, 42, 43}, {58, 59, 60, 61, 62}, {76, 77, 78, 79, 80}, {96, 97, 98, 99, 100}, ], 4: [{35, 36, 37, 38, 42}, {39, 40, 41, 42, 43}, {54, 55, 56, 57, 61}, {58, 59, 60, 61, 62}, {73, 74, 75, 79, 80}, {76, 77, 78, 79, 80}, {93, 94, 95, 99, 100}, {96, 97, 98, 99, 100}, ], } G = torrents_and_ferraro_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
def _check_connectivity(G): result = nx.k_components(G) for k, components in result.items(): if k < 3: continue for component in components: C = G.subgraph(component) assert_true(nx.node_connectivity(C) >= k)
def _check_connectivity(G): result = nx.k_components(G) for k, components in result.items(): if k < 3: continue for component in components: C = G.subgraph(component) K = nx.node_connectivity(C) assert_greater_equal(K, k)
def score_graph_use_kcomponents(hits, G): can_trkx = nx.k_components(G)[1] n_candidates = len(can_trkx) results = [] for itrk, tracks in enumerate(can_trkx): results += [(G.nodes[track]['hit_id'], itrk) for track in tracks] trk_df = pd.DataFrame(results, columns=['hit_id', 'track_id']) score = score_event(hits, trk_df) print("{} track candidates with score: {:.4f}".format(n_candidates, score)) return trk_df, score
def test_karate_component_number(): karate_k_num = { 0: 4, 1: 4, 2: 4, 3: 4, 4: 3, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2, 10: 3, 11: 1, 12: 2, 13: 4, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 3, 20: 2, 21: 2, 22: 2, 23: 3, 24: 3, 25: 3, 26: 2, 27: 3, 28: 3, 29: 3, 30: 4, 31: 3, 32: 4, 33: 4 } G = nx.karate_club_graph() k_components = nx.k_components(G) k_num = build_k_number_dict(k_components) assert_equal(karate_k_num, k_num)
def extract_power_k_connected(verbose=False): """Utility function to break Strogatz Watts power grid data into n-connected graphs.""" nxg = ig_to_nx(ig.Graph.Read_GML('data/power.gml')) k_connected = nx.k_components(nxg) for k, components in k_connected.items(): for i, component in enumerate(components): subgraph = nx.Graph(nxg.subgraph(component)) file_name = "data/power_{}_connected_subset_{:>04}_{:>02}.gml".format( k, len(component), i) if verbose: print("Writing {}".format(file_name)) nx_to_ig(subgraph).write_gml(file_name)
def test_torrents_and_ferraro_graph(): G = torrents_and_ferraro_graph() result = nx.k_components(G) _check_connectivity(G, result) # In this example graph there are 8 3-components, 4 with 15 nodes # and 4 with 5 nodes. assert_equal(len(result[3]), 8) assert_equal(len([c for c in result[3] if len(c) == 15]), 4) assert_equal(len([c for c in result[3] if len(c) == 5]), 4) # There are also 8 4-components all with 5 nodes. assert_equal(len(result[4]), 8) assert_true(all(len(c) == 5 for c in result[4]))
def approximation(self): result = {} result['all_pairs_node_connectivity'] = nx.all_pairs_node_connectivity( self.graph) result['node_connectivity'] = nx.node_connectivity(self.graph) if self.directed == 'undirected': result['k_components'] = nx.k_components(self.graph) result['average_clustering'] = nx.average_clustering(self.graph) fname_approx = self.DIR + '/appoximation.json' with open(fname_approx, "w") as f: json.dump(result, f, cls=SetEncoder, indent=2) print(fname_approx)
def _calc_quanzi_informal_leader(self, M): G = nx.from_numpy_matrix(M) G.remove_node(0) informs = defaultdict(list) if G.number_of_edges() == 0: self._logger.debug("no quanzi in graph") return informs for c in nx.k_components(G)[1]: if len(c) < 3: continue H = nx.subgraph(G, c) leader = sorted(H.degree, key=lambda x: x[1], reverse=True)[0][0] informs[leader] = list(H.neighbors(leader)) self._logger.debug("informal leader quanzi: {}".format(informs)) return informs
def kconnected(R, k): RG = R.copy() #RG = RG.to_undirected() N = nx.k_components(RG.to_undirected()) N = list(N[k][0]) G = nx.DiGraph() G.add_nodes_from(N) for u in N: for v in N: if (u, v) in RG.edges(): G.add_edge(u, v) G = nx.convert_node_labels_to_integers(G, first_label=0) return G
def is_connected(self, k=1): """ Checks if the graph is k-connected. Parameters ---------- k: int, optional (default=1) Check for k-connectivity. Returns ------- bool True iff the graph is k-connected. """ # TODO Check if this works the way intended. connectivity_dict = nx.k_components(self.to_networkx_graph()) return len(connectivity_dict[k][0]) == self.number_of_nodes
def solve_l_do_not_use_it(G): comp = nx.k_components(G)[2] nodes = dict() for i in G.nodes: nodes[i] = "#FFFFFF" i = 1 for component in comp: for ISO in component: nodes[ISO] = COLORS[i] i += 1 color = list() for c in nodes: color.append(nodes[c]) block_cut_tree = nx.Graph() block_cut_tree.add_nodes_from([1, 2, 3]) block_cut_tree.add_edges_from([(1, 2), (3, 2)]) show_graph(G, color=color) show_graph(block_cut_tree, color=[COLORS[1], COLORS[3], COLORS[2]])
def test_torrents_and_ferraro_detail_3_and_4(): G = torrents_and_ferraro_graph() result = nx.k_components(G) # In this example graph there are 8 3-components, 4 with 15 nodes # and 4 with 5 nodes. assert_equal(len(result[3]), 8) assert_equal(len([c for c in result[3] if len(c) == 15]), 4) assert_equal(len([c for c in result[3] if len(c) == 5]), 4) # There are also 8 4-components all with 5 nodes. assert_equal(len(result[4]), 8) assert_true(all(len(c) == 5 for c in result[4])) # Finally check that the k-components detected have actually node # connectivity >= k. for k, components in result.items(): if k < 3: continue for component in components: K = nx.node_connectivity(G.subgraph(component)) assert_greater_equal(K, k)
def test_random_gnp(): G = nx.gnp_random_graph(50, 0.2) result = nx.k_components(G) _check_connectivity(G, result)
def test_directed(): with pytest.raises(nx.NetworkXNotImplemented): G = nx.gnp_random_graph(10, 0.2, directed=True, seed=42) nx.k_components(G)
resultList.append( [index for index, value in enumerate(labeledVertex) if value == l]) sortedResultList = sorted(resultList, key=lambda e: (len(e), e[0])) numOfConnectComponent = len(np.unique(labeledVertex)) outputFile.write("%s\n" % numOfConnectComponent) for sArr in sortedResultList: printArrayToFile(outputFile, sArr) maTranKe = docTapTinMaTranKe(input_arg) if len(maTranKe) == 0: print('The input file is empty') else: G = nx.from_numpy_matrix(maTranKe) nx.k_components(G) print(nx.k_components(G)) print('Do thi nay lien thong?', nx.is_connected(G)) if option_arg == 'd': print('Su dung DFS!!!') danhSachDaGanNhan = connectedComponentsDFS(G) output_file = open(output_arg, "wt") putToOutput(output_file, danhSachDaGanNhan) elif option_arg == 'b': print('Su dung BFS!!!') danhSachDaGanNhan = connectedComponentsBFS(G) print('danh sach da gan Nhan:', danhSachDaGanNhan) output_file = open(output_arg, "wt") putToOutput(output_file, danhSachDaGanNhan)
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [ { 'Nora Fayette', 'E10', 'Myra Liddel', 'E12', 'E14', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'E1', 'Verne Sanderson', 'E3', 'E2', 'Theresa Anderson', 'Pearl Oglethorpe', 'Katherina Rogers', 'Brenda Rogers', 'E13', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], 4: [ { 'Nora Fayette', 'E10', 'Verne Sanderson', 'E12', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'Myra Liddel', 'E3', 'Theresa Anderson', 'Katherina Rogers', 'Brenda Rogers', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
def test_karate(): G = nx.karate_club_graph() result = nx.k_components(G) _check_connectivity(G, result)
def test_directed(): G = nx.gnp_random_graph(10, 0.2, directed=True) nx.k_components(G)
def test_shell(): constructor = [(20, 80, 0.8), (80, 180, 0.6)] G = nx.random_shell_graph(constructor) result = nx.k_components(G) _check_connectivity(G, result)
def eval_kcomponents(graph): """this evaluates the main function and cach it for speed up.""" return nx.k_components(graph)
def test_configuration(): deg_seq = nx.random_powerlaw_tree_sequence(100, tries=5000) G = nx.Graph(nx.configuration_model(deg_seq)) G.remove_edges_from(nx.selfloop_edges(G)) result = nx.k_components(G) _check_connectivity(G, result)
print("Connectivity: True") print("Network diameter: ", nx.diameter(G)) else: print("Connectivity: False") triadic_closure = nx.transitivity(G) print("Triadic closure (transitivity):", triadic_closure) degree_dict = dict(G.degree(G.nodes())) nx.set_node_attributes(G, degree_dict, 'degree') sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True) print("Top 25 nodes by degree:") for d in sorted_degree[:25]: print(d) print ("Node Connectivity: ", nx.node_connectivity(G)) print ("K-component Structure: ", nx.k_components(G)) print("To centrality...") print("Calculating betweenness centrality...") betweenness_dict = nx.betweenness_centrality(G, normalized=True) print("Calculating eigenvector centrality...") eigenvector_dict = nx.eigenvector_centrality(G) print("Betweenness centrality...") nx.set_node_attributes(G, betweenness_dict, 'betweenness') print("Eigenvector centrality...") nx.set_node_attributes(G, eigenvector_dict, 'eigenvector') print("Sorting betweenness...") sorted_betweenness = sorted(betweenness_dict.items(), key=itemgetter(1), reverse=True)
import networkx as nx import matplotlib.pyplot as plt import numpy G = nx.read_gml('test1.gml') # k_components = nx.k_components(G) # print(k_components) a = list(nx.articulation_points(G)) # print(a) G.add_edge(3, 7) k_components = nx.k_components(G) # print(k_components) a = list(nx.articulation_points(G)) # print(a) A = numpy.matrix([[0, 1, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]) H = nx.from_numpy_matrix(A) k_components = nx.k_components(H) print(k_components) bicomponents = list(nx.biconnected_component_subgraphs(H)) print(bicomponents[0].nodes()) plt.show()
def test_davis_southern_women(): G = nx.davis_southern_women_graph() result = nx.k_components(G) _check_connectivity(G, result)
def getKComps(UDG): kcomps = nx.k_components(UDG) return kcomps
def one_bond_breaking(mol_name, G_mol_list, bond_breaking={ 'CH': [], 'OH': [], 'CO': [], 'CC': [], 'CCd': [], 'COd': [] }, original={ 'CH': [], 'OH': [], 'CO': [], 'CC': [], 'CCd': [], 'COd': [] }, bonds=[], nums=0): """ G_mol_list should be one original molecule graph this function return one bond breaking results of this molecule """ for G_mol in G_mol_list: #break one chemical bond #nx.draw(G_mol,with_labels=True) #plt.show() new_mol = [] elements = [] #print G_mol.edges(data=True) if len(G_mol.edges()) > 0: for edge in G_mol.edges(): element_1 = edge[0] element_2 = edge[1] new_G_mol = G_mol.copy() new_G_mol.remove_edge(*edge) elements.append([element_1, element_2]) new_mol.append(new_G_mol) all_products = [] element_products = [] em = iso.categorical_edge_match('order', 0) nm = iso.categorical_node_match(['element'], ['X']) for num, i in enumerate(new_mol): if len(i.nodes()) > 2: k = nx.k_components(i) products = [] for nk in k: frags = k[nk] if len(frags) == 1: for sets in frags: subg = i.subgraph(sets) frag_0 = [ node for node in i.nodes() if node not in sets ] subg_0 = i.subgraph(frag_0) products.append(subg) products.append(subg_0) else: for sets in frags: subg = i.subgraph(sets) products.append(subg) if len(products) != 0: element_products.append(elements[num]) all_products.append(products) elif len(i.nodes()) == 2: element_products.append(elements[num]) products = [] for node in i.nodes(): subg = i.subgraph(node) products.append(subg) all_products.append(products) #print element_products for num, element in enumerate(element_products): if 'C' in element[0] and 'H' in element[1]: bond_breaking['CH'].append(all_products[num]) original['CH'].append(G_mol) elif 'C' in element[1] and 'H' in element[0]: bond_breaking['CH'].append(all_products[num]) original['CH'].append(G_mol) elif 'C' in element[0] and 'O' in element[1]: if G_mol[element[0]][element[1]]['order'] == 2: bond_breaking['COd'].append(all_products[num]) original['COd'].append(G_mol) elif G_mol[element[0]][element[1]]['order'] == 1: bond_breaking['CO'].append(all_products[num]) original['CO'].append(G_mol) elif 'C' in element[1] and 'O' in element[0]: if G_mol[element[0]][element[1]]['order'] == 2: bond_breaking['COd'].append(all_products[num]) original['COd'].append(G_mol) elif G_mol[element[0]][element[1]]['order'] == 1: bond_breaking['CO'].append(all_products[num]) original['CO'].append(G_mol) elif 'C' in element[0] and 'C' in element[1]: #print element if G_mol[element[0]][element[1]]['order'] == 2: bond_breaking['CCd'].append(all_products[num]) original['CCd'].append(G_mol) elif G_mol[element[0]][element[1]]['order'] == 1: bond_breaking['CC'].append(all_products[num]) original['CC'].append(G_mol) else: bond_breaking['OH'].append(all_products[num]) original['OH'].append(G_mol) #print bond_breaking bond = {} bond['CC'] = bond_breaking['CC'][:] bond['CH'] = bond_breaking['CH'][:] bond['CO'] = bond_breaking['CO'][:] bond['OH'] = bond_breaking['OH'][:] bond['CCd'] = bond_breaking['CCd'][:] bond['COd'] = bond_breaking['COd'][:] #print bond original_m = {} original_m['CC'] = original['CC'][:] original_m['CH'] = original['CH'][:] original_m['CO'] = original['CO'][:] original_m['OH'] = original['OH'][:] original_m['CCd'] = original['CCd'][:] original_m['COd'] = original['COd'][:] origins = { 'CH': [], 'OH': [], 'CO': [], 'CC': [], 'CCd': [], 'COd': [] } for key in bond_breaking.keys(): for num, products in enumerate(bond_breaking[key]): bond[key].remove(products) origin = original_m[key][num] if len(bond[key]) != 0: if True in [ nx.is_isomorphic(products[0], ps[1], nm, em) and nx.is_isomorphic(products[1], ps[0], nm, em) for ps in bond[key] ]: origins[key].append(origin) elif True in [ nx.is_isomorphic(products[0], ps[0], nm, em) and nx.is_isomorphic(products[1], ps[1], nm, em) for ps in bond[key] ]: origins[key].append(origin) else: bond[key].append(products) else: bond[key].append(products) for key in origins.keys(): for i in origins[key]: original_m[key].remove(i) new_mol_list = [] for key in bond.keys(): for products in bond[key]: for graph in products: new_mol_list.append(graph) bond_l = [] for key in bond.keys(): #print key l = len(bond[key]) bond_l.append(l) bonds.append(bond_l) #print bonds if nums > 1: if bonds[nums] == bonds[nums - 1]: return bond, original_m nums += 1 with open(mol_name + '/rxn/%s.pickle' % (str(nums)), 'w+') as f: pickle.dump([new_mol_list, bond, original_m, bonds, nums], f) return one_bond_breaking(mol_name, G_mol_list=new_mol_list, bond_breaking=bond, original=original_m, bonds=bonds, nums=nums)
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [{ "Nora Fayette", "E10", "Myra Liddel", "E12", "E14", "Frances Anderson", "Evelyn Jefferson", "Ruth DeSand", "Helen Lloyd", "Eleanor Nye", "E9", "E8", "E5", "E4", "E7", "E6", "E1", "Verne Sanderson", "E3", "E2", "Theresa Anderson", "Pearl Oglethorpe", "Katherina Rogers", "Brenda Rogers", "E13", "Charlotte McDowd", "Sylvia Avondale", "Laura Mandeville", }], 4: [{ "Nora Fayette", "E10", "Verne Sanderson", "E12", "Frances Anderson", "Evelyn Jefferson", "Ruth DeSand", "Helen Lloyd", "Eleanor Nye", "E9", "E8", "E5", "E4", "E7", "E6", "Myra Liddel", "E3", "Theresa Anderson", "Katherina Rogers", "Brenda Rogers", "Charlotte McDowd", "Sylvia Avondale", "Laura Mandeville", }], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert len(components) == len(solution[k]) for component in components: assert component in solution[k]
def test_davis_southern_women_detail_3_and_4(): solution = { 3: [{ 'Nora Fayette', 'E10', 'Myra Liddel', 'E12', 'E14', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'E1', 'Verne Sanderson', 'E3', 'E2', 'Theresa Anderson', 'Pearl Oglethorpe', 'Katherina Rogers', 'Brenda Rogers', 'E13', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], 4: [{ 'Nora Fayette', 'E10', 'Verne Sanderson', 'E12', 'Frances Anderson', 'Evelyn Jefferson', 'Ruth DeSand', 'Helen Lloyd', 'Eleanor Nye', 'E9', 'E8', 'E5', 'E4', 'E7', 'E6', 'Myra Liddel', 'E3', 'Theresa Anderson', 'Katherina Rogers', 'Brenda Rogers', 'Charlotte McDowd', 'Sylvia Avondale', 'Laura Mandeville', }, ], } G = nx.davis_southern_women_graph() result = nx.k_components(G) for k, components in result.items(): if k < 3: continue assert_true(len(components) == len(solution[k])) for component in components: assert_true(component in solution[k])
# -*- coding: utf-8 -*- """ Created on Sun Oct 25 18:47:11 2020 @author: Mikes_Surface2 """ from Org_Network import Org_Network import Create_Network import networkx as nx org_members = Org_Network("facebook",True).load_results() net = Create_Network.match_collaborators(org_members) #%% #nx.draw_spring(net, node_size=10, width = 1) a = nx.k_components(net)
def k_components(self): return nx.k_components(self.graph)