def test_biconnected_eppstein(): # tests from http://www.ics.uci.edu/~eppstein/PADS/Biconnectivity.py G1 = nx.Graph({ 0: [1, 2, 5], 1: [0, 5], 2: [0, 3, 4], 3: [2, 4, 5, 6], 4: [2, 3, 5, 6], 5: [0, 1, 3, 4], 6: [3, 4], }) G2 = nx.Graph({ 0: [2, 5], 1: [3, 8], 2: [0, 3, 5], 3: [1, 2, 6, 8], 4: [7], 5: [0, 2], 6: [3, 8], 7: [4], 8: [1, 3, 6], }) assert_true(nx.is_biconnected(G1)) assert_false(nx.is_biconnected(G2)) answer_G2 = [{1, 3, 6, 8}, {0, 2, 5}, {2, 3}, {4, 7}] bcc = list(nx.biconnected_components(G2)) assert_components_equal(bcc, answer_G2)
def findCommunities(filename): G = read_nodeadjlist(filename) #c = nx.connected_components(G) c = nx.biconnected_components(G) #print list(c), type(c) #exit() return c
def block_cutpoint_tree(G, projected=False, verbose=False): input_graph = Graph(G) top_nodes = [] bottom_nodes = [] articulation_points = set(nx.articulation_points(input_graph)) if verbose: print "Articulation points:", articulation_points for biconnected_component in nx.biconnected_components(input_graph): inter = biconnected_component.intersection(articulation_points) if verbose: print "Inter:", inter top_nodes.extend( [json.dumps(sorted(biconnected_component)) for _ in inter] ) #top_nodes.extend([G.subgraph(bcc) for _ in inter]) bottom_nodes.extend([x for x in inter]) #bottom_nodes.extend([G.subgraph(x) for x in inter]) if verbose: print "Top nodes:", top_nodes print "Bottom nodes:", bottom_nodes edges = zip(top_nodes, bottom_nodes) if verbose: print "Edges:", edges bc_tree = Graph() bc_tree.add_edges_from(edges) if projected: return Graph(bipartite.projected_graph(bc_tree, top_nodes)) else: return bc_tree
def scenes(self, threads): g = nx.Graph() # connect adjacent shots for shot1, shot2 in pairwise(threads.itertracks()): g.add_edge(shot1, shot2) # connect threaded shots for label in threads.labels(): for shot1, shot2 in pairwise(threads.subset([label]).itertracks()): g.add_edge(shot1, shot2) scenes = threads.copy() # group all shots of intertwined threads for shots in sorted(sorted(bc) for bc in nx.biconnected_components(g)): if len(shots) < 3: continue common_label = scenes[shots[0]] for shot in shots: scenes[shot] = common_label return scenes
def test_biconnected_karate(): K = nx.karate_club_graph() answer = [{0, 1, 2, 3, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}, {0, 4, 5, 6, 10, 16}, {0, 11}] bcc = list(nx.biconnected_components(K)) assert_components_equal(bcc, answer) assert_equal(set(nx.articulation_points(K)), {0})
def should_alg(self,arg): nodes_not_in_a_cycle = set(arg.nodes()) # filter all nodes which are not in a biconnected component for component in nx.biconnected_components(arg): if len(component) > 2: nodes_not_in_a_cycle -= component # remove all nodes which are not in a biconnected component from # the graph arg.remove_nodes_from(nodes_not_in_a_cycle) return arg
def remove_inclusions(self): """Merge any segments fully contained within other segments.""" bcc = list(biconnected_components(self)) container = [i for i, s in enumerate(bcc) if self.boundary_body in s][0] del bcc[container] # remove the main graph bcc = map(list, bcc) for cc in bcc: cc.sort(key=lambda x: len(self.node[x]['extent']), reverse=True) bcc.sort(key=lambda x: len(self.node[x[0]]['extent'])) for cc in bcc: self.merge_subgraph(cc, cc[0])
def get_biconnected(G): """ Wrapper arround the networkx biconnected_components function. To find out why the biconnected components algorithm is useful for finding constitutive exons check the information section or wikipedia. """ G_undirected = G.to_undirected() # make sure undirected graph for biconnected components components = filter(lambda x: len( x) > 2, map(list, nx.biconnected_components(G_undirected))) # filter out trivial dyad biconnected components # assert len(components) > 0, 'what nothing in it' + str(components) # assert components != None, 'Oddly there is a none object in the biconnected comp' + str(components) return components
def find_planarity(graph): """ int E=0 for each edge of G E = E+1 if E > 3V - 3 then nonplanar divide G into biconnected components for each biconnected component G explore C to number vertices and transform C into a palm tree P find a cycle c in P construct planar representation for c for each piece formed when c is deleted apply algorithm recursively to determine if piece plus cycle is planar if piece plus cycle is planar and piece may be added to planar representation add it else nonplanar """ bad_graph = None result = True graph_nodes = len(graph.nodes()) graph_edges = len(graph.edges()) # Lemma 1 if graph_edges > (3 * graph_nodes - 3): # Graph is nonplanar result = False if result: # Divide G into biconnected components + for each biconnected component G for C in nx.biconnected_components(graph): pass return result, bad_graph
def process(self, args): """ By using a generator of sets of nodes, one set for each biconnected component of the graph(biconnected_components) we remove all vertices which do not belong to a cycle (degree greater than two). The output is a graph including only biconnected components. Args: | *args* : a list containing image array and Graph object """ image, graph = args # create a set of all nodes nodes_not_in_a_cycle = set(graph.nodes()) # filter all nodes which are not in a biconnected component for component in nx.biconnected_components(graph): if len(component) > 2: nodes_not_in_a_cycle -= component # remove all nodes which are not in a biconnected component from # the graph graph.remove_nodes_from(nodes_not_in_a_cycle) print ('discarding a total of', len(nodes_not_in_a_cycle), 'edges ...') self.result['graph'] = graph self.result['img'] = image
pattern = '[0-9]' for lineWeight, lineLatencies in zip(fileWeight, fileLatencies): argsWeight = lineWeight.rstrip().split(" ") argsLatencies = lineLatencies.rstrip().split(" ") node1 = argsWeight[0] node2 = argsWeight[1] width = int(100 * (1 / float(argsWeight[2]))) length = int(float(argsLatencies[2])) graph.add_edge(node1, node2, Width=width, Length=length) graph = max((graph.subgraph(c) for c in nx.biconnected_components(graph)), key=len) graph = nx.convert_node_labels_to_integers(graph) graph = graph.to_directed() print("\n--- Test Network pertaining to %s" % AS) print("\tNumber of Nodes: %d" % graph.number_of_nodes()) print("\tNumber of Links: %d" % graph.number_of_edges()) print("\tNumber of Distinct Widths: %d" % len(set([width for _, _, width in graph.edges.data('Width')]))) for Attribute in [['Hops', 'Length'], ['Width', 'Hops'], ['Width', 'Length'], ['Width', 'Hops', 'Length']]: dirNameTestNetwork = "NetworkDataSets/Rocketfuel/%s" % (AS) fileNameTestNetwork = "%s/%s.tsv" % (dirNameTestNetwork,
number_of_biconnected_components=2 size_of_component=3 counte=0 mmin=1000 while True: # G = nx.erdos_renyi_graph(30,0.024) G = nx.gnp_random_graph(30,0.15) # G = nx.gnp_random_graph(15,0.04) if counte== mmin: print counte mmin+=1000 # print nx.is_biconnected(G) # if nx.is_biconnected(G)==False: # continue testy=sorted(nx.biconnected_components(G), key = len, reverse=True) # print testy uu=0 for g in testy: if len(g)>=size_of_component: uu+=1 if uu>=number_of_biconnected_components: break else: counte+=1 continue # print counte,'a' pos=nx.spring_layout(G,k=0.15,iterations=10)
def detect(self): bcc = nx.biconnected_components(self.network.graph.structure) self._vote_honests_predicted(bcc) return sypy.Results(self)
graph = nx.Graph() for line in open(input_file): line = line.strip().split(',') s = int(line[0]) d = int(line[1]) w = float(line[2]) graph.add_edge(s, d, weight=w) betweenness = nx.betweenness_centrality(graph, normalized=True) closeness = nx.closeness_centrality(graph, normalized=True) # eccentricity = nx.eccentricity(graph) clustering_coeff = nx.clustering(graph) degree = nx.degree_centrality(graph) components = nx.biconnected_components(graph) biconn = defaultdict(int) for component in components: for node in component: biconn[node] += 1 weighted_degree = defaultdict(int) nodes = graph.nodes() for node in nodes: adj_list = graph.neighbors(node) for neighbor in adj_list: weighted_degree[node] += graph[node][neighbor]['weight'] egonet_zero_degree = defaultdict(float) egonet_zero_weight = defaultdict(float)
def biconnected_components(self): return nx.biconnected_components(self)
def condensate_graph(self): graphs = [] connected_components = list( nx.connected_component_subgraphs(self.graph)) counter = 0 if not len(connected_components): self.condensed_graph = nx.Graph() return for comp in connected_components: if len(comp) == 1: g = nx.Graph() n = comp.nodes()[0] g.add_node(n, {"type": "cutpoint"}) graphs.append(g) continue g = nx.Graph() if not len(comp): pass else: components = list(nx.biconnected_components(comp)) max_component_size = max([len(x) for x in components if x]) component_dict = {} cutpoints = set(nx.articulation_points(comp)) i = 0 for c in sorted(components, key=lambda x: -len(x)): nodes = set(c) - cutpoints if not nodes: continue node_id = "Block " + str(i) g.add_node(node_id) component_dict[node_id] = nodes i += 1 g.node[node_id]["nodes"] = " ".join([x for x in nodes]) g.node[node_id]["nodes in block"] = len(nodes) g.node[node_id]["radius"] = max( int(self.max_node_size * float(len(nodes)) / max_component_size), self.min_node_size) g.node[node_id]["type"] = "block" for n in cutpoints: temp_g = comp.copy() temp_g.remove_node(n) main_c = sorted( [x for x in nx.connected_components(temp_g)], key=lambda x: len(x)) robustness = len(main_c[-1]) g.add_node(n) g.node[n]["type"] = "cutpoint" g.node[n]["Potential disconnected nodes"] = len( comp) - robustness - 1 for neigh in comp[n].keys(): if neigh in cutpoints: g.add_edge(n, neigh, {'weight': 1}) # TODO weight else: for k, v in component_dict.items(): if neigh in v: g.add_edge(n, k, {'weight': 1}) # TODO weight g.node[n]["robustness"] = 10 - int( 10 * float(robustness) / len(comp)) g.node[n]["style"] = "cutpoint_" +\ str(10 - int(10*float(robustness) / len(comp))) g.node[n]["radius"] = self.cutpoint_size[g.node[n] ["robustness"]] # let's merge some leaves i = 0 for n, data in g.nodes(data=True): tobemerged = [] mergesize = 0 if data["type"] == "cutpoint": for (neigh, ndata) in g[n].items(): if g.node[neigh]["type"] == "block" and \ len(g[neigh]) == 1: tobemerged.append(neigh) mergesize += g.node[neigh]["nodes in block"] if len(tobemerged) > 1: nodes = " ".join([g.node[y]["nodes"] for y in tobemerged]) g.add_node( i, { "nodes": nodes, "nodes in block": mergesize, "radius": max( int(self.max_node_size * float(len(tobemerged)) / max_component_size), self.min_node_size), "type": "block" }) g.add_edge(i, n, {"weight": 1}) # TODO need weight here i += 1 for n in tobemerged: g.remove_node(n) # then relabel all the blocks blocks = {} for n, data in g.nodes(data=True): if data["type"] == "block": blocks[n] = data["nodes in block"] labels = {} for n in sorted(blocks.items(), key=lambda x: -x[1]): labels[n[0]] = "Block %d" % counter counter += 1 r_g = nx.relabel_nodes(g, labels, copy=True) graphs.append(r_g) self.condensed_graph = nx.union_all(graphs)
def test_null_graph(): G = nx.Graph() assert_false(nx.is_biconnected(G)) assert_equal(list(nx.biconnected_components(G)), []) assert_equal(list(nx.biconnected_component_edges(G)), []) assert_equal(list(nx.articulation_points(G)), [])
def get_descriptor(G, num_iterations=30): G = nx.convert_node_labels_to_integers(G) if G.number_of_nodes() < 10: G = add_multiple_copies(G) A1 = np.matrix( nx.laplacian_matrix(G, nodelist=sorted(G.nodes())).todense()) n = A1.shape[0] desc = {} leaders = [] for num_l_idx, num_leaders in enumerate([ 1, 2, 5, 9, int(n * 2 / 100) + 1, int(n * 5 / 100) + 1, int(n * 10 / 100) + 1, int(n * 20 / 100) + 1, int(n * 30 / 100) + 1 ]): old_n = A1.shape[0] traces = [] ranks = [] min_eigs = [] max_eigs = [] itraces = [] iranks = [] imin_eigs = [] imax_eigs = [] metric_dimension = [] for i in range(num_iterations): follows = np.random.choice(old_n, old_n - num_leaders, replace=False) leaders = list(set(range(old_n)) - set(follows)) A2 = A1[follows, :] A3 = A2[:, follows] A = -1 * A3 n = A.shape[0] mask = np.ones(old_n, dtype=bool) mask[leaders] = False B = A1[mask, :] B = B[:, leaders] A = np.mat(A) B = np.mat(B) if INCLUDE_GRM: grm = controlpy.analysis.controllability_gramian(A, B) rnk = LA.matrix_rank(grm) ranks.append(rnk) traces.append(np.trace(grm)) if INCLUDE_EIGEN_VALUES: w, v = LA.eig(grm) a = np.real(w) a[a == 0] = 0.0001 minval = np.min(a) min_eigs.append(np.min(minval)) max_eigs.append(np.max(a)) if INCLUDE_INVERSE_GRM: try: grm = LA.pinv(grm, hermitian=True) except np.linalg.LinAlgError: return None itraces.append(np.trace(grm)) iranks.append(LA.matrix_rank(grm)) if INCLUDE_EIGEN_VALUES: w, v = LA.eig(grm) a = np.real(w) a[a == 0] = 0.0001 minval = np.min(a) imin_eigs.append(np.min(minval)) imax_eigs.append(np.max(a)) if INCLUDE_METRIC_DIMENSION: metric_dimension.append(compute_metric_dimension(G, leaders)) if INCLUDE_MIN_MAX: desc['GRM_MAX_TRACE_' + str(num_l_idx)] = np.max(traces) desc['GRM_MIN_TRACE_' + str(num_l_idx)] = np.min(traces) desc['GRM_MAX_RANK_' + str(num_l_idx)] = np.max(ranks) desc['GRM_MIN_RANK_' + str(num_l_idx)] = np.min(ranks) if INCLUDE_EIGEN_VALUES: desc['GRM_MAX_of_MIN_EIG_' + str(num_l_idx)] = np.max(min_eigs) desc['GRM_MIN_of_MIN_EIG_' + str(num_l_idx)] = np.min(min_eigs) desc['GRM_MAX_of_MAX_EIG_' + str(num_l_idx)] = np.max(max_eigs) desc['GRM_MIN_of_MAX_EIG_' + str(num_l_idx)] = np.min(max_eigs) if INCLUDE_INVERSE_GRM: desc['INV_GRM_MAX_TRACE_' + str(num_l_idx)] = np.max(itraces) desc['INV_GRM_MIN_TRACE_' + str(num_l_idx)] = np.min(itraces) if INCLUDE_MEAN: desc['GRM_MEAN_TRACE_' + str(num_l_idx)] = np.mean(traces) desc['GRM_MEAN_RANK_' + str(num_l_idx)] = np.mean(ranks) if INCLUDE_EIGEN_VALUES: desc['GRM_MEAN_MAX_EIG_' + str(num_l_idx)] = np.mean(max_eigs) desc['GRM_MEAN_MIN_EIG_' + str(num_l_idx)] = np.mean(min_eigs) if INCLUDE_INVERSE_GRM: desc['INV_GRM_MEAN_TRACE_' + str(num_l_idx)] = np.mean(itraces) desc['INV_GRM_MEAN_RANK_' + str(num_l_idx)] = np.mean(iranks) if INCLUDE_EIGEN_VALUES: desc['INV_GRM_MEAN_MIN_EIG_' + str(num_l_idx)] = np.mean(imin_eigs) desc['INV_GRM_MEAN_MAX_EIG_' + str(num_l_idx)] = np.mean(imax_eigs) if INCLUDE_METRIC_DIMENSION: desc['METRIC_DIMENSION_MEAN' + str(num_l_idx)] = np.mean(metric_dimension) desc['METRIC_DIMENSION_MIN' + str(num_l_idx)] = np.min(metric_dimension) desc['METRIC_DIMENSION_MAX' + str(num_l_idx)] = np.max(metric_dimension) n, m = G.number_of_nodes(), G.number_of_edges() desc['no_nodes'] = n desc['no_edges'] = m desc['no_bi_conn_comp'] = len(list(nx.biconnected_components(G))) if INCLUDE_LAP_SPECT: Ls = sorted(nx.laplacian_spectrum(G)) # desc['LS_0'] = Ls[0] desc['LS_1'] = Ls[1] desc['LS_2'] = Ls[2] if INCLUDE_LAP_SPECT_EXT: desc['LSE_3'] = Ls[3] desc['LSE_4'] = Ls[4] desc['LSE_-1'] = Ls[-1] desc['LSE_-2'] = Ls[-2] desc['LSE_-3'] = Ls[-3] if INCLUDE_CYCLES: if n - m == 1: desc['0cyc'] = 1 else: desc['0cyc'] = 0 if n - m == 0: desc['1cyc'] = 1 else: desc['1cyc'] = 0 if n - m == -1: desc['2cyc'] = 1 else: desc['2cyc'] = 0 if n - m < -1: desc['g2cyc'] = 1 else: desc['g2cyc'] = 0 if INCLUDE_FEATURES: desc = {**desc, **add_features(G)} return (desc)
VN[l[0]]=l[1].replace("\n","").replace("\r","") G.add_node(VN[l[0]]) flag=1 A = [[0 for x in range(len(V))] for x in range(len(V))] flag=0 for each_line in pl: l=each_line.split(',') if len(l)==5: if flag!=0: #print(l[0],l[1],l[3]) A[int(l[0][1:])][int(l[1][1:])]=float(l[3]) edge=(VN[l[0]],VN[l[1]]) G.add_edge(*edge) flag=1 else: continue print nx.is_biconnected(G) comp=list(nx.biconnected_components(G)) print (len(comp)) for i in range(len(comp)): k=0 for j in list(comp[i]): sheet.write(k, i, j) k+=1 book.save("biconnectedness/"+each_file[:-4]+".xls") fp.close()
Gnp = nx.gnp_random_graph(20, 0.8, seed=42) Anp = AntiGraph(nx.complement(Gnp)) Gd = nx.davis_southern_women_graph() Ad = AntiGraph(nx.complement(Gd)) Gk = nx.karate_club_graph() Ak = AntiGraph(nx.complement(Gk)) pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)] # test connected components for G, A in pairs: gc = [set(c) for c in nx.connected_components(G)] ac = [set(c) for c in nx.connected_components(A)] for comp in ac: assert comp in gc # test biconnected components for G, A in pairs: gc = [set(c) for c in nx.biconnected_components(G)] ac = [set(c) for c in nx.biconnected_components(A)] for comp in ac: assert comp in gc # test degree for G, A in pairs: node = list(G.nodes())[0] nodes = list(G.nodes())[1:4] assert G.degree(node) == A.degree(node) assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree()) # AntiGraph is a ThinGraph, so all the weights are 1 assert sum(d for n, d in A.degree()) == sum( d for n, d in A.degree(weight="weight")) assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))
def test_biconnected_davis(): D = nx.davis_southern_women_graph() bcc = list(nx.biconnected_components(D))[0] assert set(D) == bcc # All nodes in a giant bicomponent # So no articulation points assert len(list(nx.articulation_points(D))) == 0
def test_biconnected_components_cycle(): G = nx.cycle_graph(3) G.add_cycle([1, 3, 4]) answer = [{0, 1, 2}, {1, 3, 4}] assert_components_equal(list(nx.biconnected_components(G)), answer)
def condensate_graph(self): graphs = [] connected_components = list(nx.connected_component_subgraphs( self.graph)) counter = 0 if not len(connected_components): self.condensed_graph = nx.Graph() return for comp in connected_components: if len(comp) == 1: g = nx.Graph() c_nodes = comp.nodes().values() if len(c_nodes) >= 1: n = c_nodes[0] g.add_node(n) g.node[n]["type"] = "cutpoint" graphs.append(g) continue g = nx.Graph() if not len(comp): pass else: components = list(nx.biconnected_components(comp)) max_component_size = max([len(x) for x in components if x]) component_dict = {} cutpoints = set(nx.articulation_points(comp)) i = 0 for c in sorted(components, key=lambda x: -len(x)): nodes = set(c) - cutpoints if not nodes: continue node_id = "Block " + str(i) g.add_node(node_id) component_dict[node_id] = nodes i += 1 g.node[node_id]["nodes"] = " ".join([x for x in nodes]) g.node[node_id]["nodes in block"] = len(nodes) g.node[node_id]["radius"] = max(int(self.max_node_size * float(len(nodes)) / max_component_size), self.min_node_size) g.node[node_id]["type"] = "block" dataJson = json.loads(self.netJSON.json()) for n in cutpoints: temp_g = comp.copy() temp_g.remove_node(n) main_c = sorted([x for x in nx.connected_components(temp_g)], key=lambda x: len(x)) connected_components2 = list(nx.connected_component_subgraphs(temp_g)) cut_gat = False for com in connected_components2: nodes2 = com.nodes() x = False for node2 in nodes2: for i in range(0,len(dataJson["nodes"])): if dataJson["nodes"][i].has_key("id") and dataJson["nodes"][i].has_key("properties") and dataJson["nodes"][i]["properties"].has_key("gateway"): if dataJson["nodes"][i]["id"] == node2: if dataJson["nodes"][i]["properties"]["gateway"] == "true": x = True break if x == True: break if x == False: cut_gat = True break robustness = len(main_c[-1]) g.add_node(n) if cut_gat == True: g.node[n]["type"] = "cutpoint_gateway" else: g.node[n]["type"] = "cutpoint" g.node[n]["Potential disconnected nodes"] = len(comp) - robustness - 1 for neigh in comp[n].keys(): if neigh in cutpoints: g.add_edge(n, neigh, weight=1) # TODO weight else: for k, v in component_dict.items(): if neigh in v: g.add_edge(n, k, weight=1) # TODO weight g.node[n]["robustness"] = 10 - int(10*float(robustness) / len(comp)) g.node[n]["style"] = "cutpoint_" +\ str(10 - int(10*float(robustness) / len(comp))) g.node[n]["radius"] = self.cutpoint_size[g.node[n] ["robustness"]] # let's merge some leaves i = 0 for n, data in g.nodes(data=True): tobemerged = [] mergesize = 0 if data["type"] == "cutpoint" or data["type"] == "cutpoint_gateway": for (neigh, ndata) in g[n].items(): if g.node[neigh]["type"] == "block" and \ len(g[neigh]) == 1: tobemerged.append(neigh) mergesize += g.node[neigh]["nodes in block"] if len(tobemerged) > 1: nodes = " ".join([g.node[y]["nodes"] for y in tobemerged]) g.add_node(i) g.node[i]["nodes"] = nodes g.node[i]["nodes in block"] = mergesize g.node[i]["radius"] = (max(int(self.max_node_size * float(len(tobemerged)) / max_component_size), self.min_node_size)) g.node[i]["type"] = "block" g.add_edge(i, n, weight=1) # TODO need weight here i += 1 for n in tobemerged: g.remove_node(n) # then relabel all the blocks blocks = {} for n, data in g.nodes(data=True): if data["type"] == "block": blocks[n] = data["nodes in block"] labels = {} for n in sorted(blocks.items(), key=lambda x: -x[1]): labels[n[0]] = "Block %d" % counter counter += 1 r_g = nx.relabel_nodes(g, labels, copy=True) graphs.append(r_g) self.condensed_graph = nx.union_all(graphs)
def k_components(G, min_density=0.95): r"""Returns the approximate k-component structure of a graph G. A `k`-component is a maximal subgraph of a graph G that has, at least, node connectivity `k`: we need to remove at least `k` nodes to break it into more components. `k`-components have an inherent hierarchical structure because they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which can contain one or more 3-components, and so forth. This implementation is based on the fast heuristics to approximate the `k`-component structure of a graph [1]_. Which, in turn, it is based on a fast approximation algorithm for finding good lower bounds of the number of node independent paths between two nodes [2]_. Parameters ---------- G : NetworkX graph Undirected graph min_density : Float Density relaxation threshold. Default value 0.95 Returns ------- k_components : dict Dictionary with connectivity level `k` as key and a list of sets of nodes that form a k-component of level `k` as values. Examples -------- >>> # Petersen graph has 10 nodes and it is triconnected, thus all >>> # nodes are in a single component on all three connectivity levels >>> from networkx.algorithms import approximation as apxa >>> G = nx.petersen_graph() >>> k_components = apxa.k_components(G) Notes ----- The logic of the approximation algorithm for computing the `k`-component structure [1]_ is based on repeatedly applying simple and fast algorithms for `k`-cores and biconnected components in order to narrow down the number of pairs of nodes over which we have to compute White and Newman's approximation algorithm for finding node independent paths [2]_. More formally, this algorithm is based on Whitney's theorem, which states an inclusion relation among node connectivity, edge connectivity, and minimum degree for any graph G. This theorem implies that every `k`-component is nested inside a `k`-edge-component, which in turn, is contained in a `k`-core. Thus, this algorithm computes node independent paths among pairs of nodes in each biconnected part of each `k`-core, and repeats this procedure for each `k` from 3 to the maximal core number of a node in the input graph. Because, in practice, many nodes of the core of level `k` inside a bicomponent actually are part of a component of level k, the auxiliary graph needed for the algorithm is likely to be very dense. Thus, we use a complement graph data structure (see `AntiGraph`) to save memory. AntiGraph only stores information of the edges that are *not* present in the actual auxiliary graph. When applying algorithms to this complement graph data structure, it behaves as if it were the dense version. See also -------- k_components References ---------- .. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion: Visualization and Heuristics for Fast Computation. https://arxiv.org/pdf/1503.04476v1 .. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf .. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness: A hierarchical conception of social groups. American Sociological Review 68(1), 103--28. http://www2.asanet.org/journals/ASRFeb03MoodyWhite.pdf """ # Dictionary with connectivity level (k) as keys and a list of # sets of nodes that form a k-component as values k_components = defaultdict(list) # make a few functions local for speed node_connectivity = local_node_connectivity k_core = nx.k_core core_number = nx.core_number biconnected_components = nx.biconnected_components density = nx.density combinations = itertools.combinations # Exact solution for k = {1,2} # There is a linear time algorithm for triconnectivity, if we had an # implementation available we could start from k = 4. for component in nx.connected_components(G): # isolated nodes have connectivity 0 comp = set(component) if len(comp) > 1: k_components[1].append(comp) for bicomponent in nx.biconnected_components(G): # avoid considering dyads as bicomponents bicomp = set(bicomponent) if len(bicomp) > 2: k_components[2].append(bicomp) # There is no k-component of k > maximum core number # \kappa(G) <= \lambda(G) <= \delta(G) g_cnumber = core_number(G) max_core = max(g_cnumber.values()) for k in range(3, max_core + 1): C = k_core(G, k, core_number=g_cnumber) for nodes in biconnected_components(C): # Build a subgraph SG induced by the nodes that are part of # each biconnected component of the k-core subgraph C. if len(nodes) < k: continue SG = G.subgraph(nodes) # Build auxiliary graph H = _AntiGraph() H.add_nodes_from(SG.nodes()) for u, v in combinations(SG, 2): K = node_connectivity(SG, u, v, cutoff=k) if k > K: H.add_edge(u, v) for h_nodes in biconnected_components(H): if len(h_nodes) <= k: continue SH = H.subgraph(h_nodes) for Gc in _cliques_heuristic(SG, SH, k, min_density): for k_nodes in biconnected_components(Gc): Gk = nx.k_core(SG.subgraph(k_nodes), k) if len(Gk) <= k: continue k_components[k].append(set(Gk)) return k_components
def test_biconnected_davis(): D = nx.davis_southern_women_graph() bcc = list(nx.biconnected_components(D))[0] assert_true(set(D) == bcc) # All nodes in a giant bicomponent # So no articulation points assert_equal(len(list(nx.articulation_points(D))), 0)
def compute_2_connected_k_dominating_set(G, DA): graphDA = G.subgraph(DA) DB = DA genB = nx.biconnected_components(graphDA) B = [] for item in genB: B.append(list(item)) # print "B" # print B art_points = list(nx.articulation_points(graphDA)) # print "Articulation Points" # print art_points P = [] while len(B) > 1: for block in B: inducedL = list(set(block) - set(art_points)) L = block # print "L" # print L # print "inducedL" # print inducedL if inducedL: break for v in inducedL: tempDB = list(DB) tempDB.remove(v) # Now for nodes in DA, may need DB for u in list(set(graphDA.nodes()) - set(L)): tempDB.remove(u) newG = G.copy() newG.remove_nodes_from(tempDB) # This part can make the algorithm fail if nx.has_path(newG, v, u): tempP = nx.shortest_path(newG, v, u) P.append(tempP) # print "P" # print P minPath = min(P, key=len) # Keep intermediate nodes of path interPath = list(minPath) interPath.pop(0) interPath.pop(-1) for node in interPath: DB.append(node) # Compute new CDS graph and recalculate B tempGraph = G.subgraph(DB) B = [] for item in genB: B.append(list(item)) genB = nx.biconnected_components(tempGraph) # print "B" # print B art_points = list(nx.articulation_points(tempGraph)) # print "Articulation Points" # print art_points return DB
p = hl.pop(0) c = 0 hl2 = copy.deepcopy(hl) while hl2 != [] and ((hl2[0] - p) <= 3): G.add_edge(p, hl2[0]) #print(str(p)+"-->"+str(hl2[0])+" = "+str((hl2[0]-p))) hl2.pop(0) #pos = nx.kamada_kawai_layout(G) #nx.draw_networkx(G, pos=pos, node_size=10, font_size=4, with_labels=True) #plt.savefig("bags.pdf",format="pdf") s = 1 def pathinator(Y, start, stop): c = 0 for path in nx.all_simple_paths(Y, source=start, target=stop): c = c + 1 return (c) for Y in nx.biconnected_components(G.to_undirected()): start = min(list(Y)) stop = max(list(Y)) paths = pathinator(G.subgraph(Y), start, stop) s = s * paths print(s)
else: for w in set(contents) - {word}: if newclus.has_edge(word, w): newclus[word][w]['weight'] += 1 else: newclus.add_edge(word, w, weight=1) if not added and entry['attempts'] >= MAX_ATTEMPTS: max_attempts_reached.add(word) ## Output connected components from newclus as new crowd gold clusters newG = nx.Graph([(u,v,d) for u,v,d in newclus.edges(data=True) if float(d['weight'])/(2*req_anno) >= CLUSTER_AGR_THRESHOLD]) if opts.clustermode == 'clique': new_crowd_gold = {i+1: l for i,l in enumerate(list(nx.find_cliques(newG)))} elif opts.clustermode == 'biconnected': new_crowd_gold = {i+1: l for i,l in enumerate(list(nx.biconnected_components(newG)))} else: sys.stderr.write('Unknown clustermode. Please use one of [clique, biconnected].\n') exit(1) clus_this_rnd = clus_this_rnd | \ set([item for sublist in new_crowd_gold.values() for item in sublist]) try: maxclusnum = max([int(n) for n in thisjson['crowd_gold']['sense_clustering'].keys()]) except ValueError: maxclusnum = 0 for clusnum, wordlist in new_crowd_gold.iteritems():
def test_null_graph(): G = nx.Graph() assert not nx.is_biconnected(G) assert list(nx.biconnected_components(G)) == [] assert list(nx.biconnected_component_edges(G)) == [] assert list(nx.articulation_points(G)) == []
# and the AntiGraph of it's complement, which behaves # as if it were the original graph. Gnp = nx.gnp_random_graph(20,0.8) Anp = AntiGraph(nx.complement(Gnp)) Gd = nx.davis_southern_women_graph() Ad = AntiGraph(nx.complement(Gd)) Gk = nx.karate_club_graph() Ak = AntiGraph(nx.complement(Gk)) pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)] # test connected components for G, A in pairs: gc = [set(c) for c in nx.connected_components(G)] ac = [set(c) for c in nx.connected_components(A)] for comp in ac: assert comp in gc # test biconnected components for G, A in pairs: gc = [set(c) for c in nx.biconnected_components(G)] ac = [set(c) for c in nx.biconnected_components(A)] for comp in ac: assert comp in gc # test degree for G, A in pairs: node = list(G.nodes())[0] nodes = list(G.nodes())[1:4] assert G.degree(node) == A.degree(node) assert sum(G.degree().values()) == sum(A.degree().values()) # AntiGraph is a ThinGraph, so all the weights are 1 assert sum(A.degree().values()) == sum(A.degree(weight='weight').values()) assert sum(G.degree(nodes).values()) == sum(A.degree(nodes).values())
def rel_size_giant_bicomponent(G): G_b = max(nx.biconnected_components(G), key=len) return len(G_b) / len(G)
def test_biconnected_components_cycle(): G=nx.cycle_graph(3) nx.add_cycle(G, [1, 3, 4]) answer = [{0, 1, 2}, {1, 3, 4}] assert_components_equal(list(nx.biconnected_components(G)), answer)
def test_barbell(): G = nx.barbell_graph(8, 4) nx.add_path(G, [7, 20, 21, 22]) nx.add_cycle(G, [22, 23, 24, 25]) pts = set(nx.articulation_points(G)) assert_equal(pts, {7, 8, 9, 10, 11, 12, 20, 21, 22}) answer = [ {12, 13, 14, 15, 16, 17, 18, 19}, {0, 1, 2, 3, 4, 5, 6, 7}, {22, 23, 24, 25}, {11, 12}, {10, 11}, {9, 10}, {8, 9}, {7, 8}, {21, 22}, {20, 21}, {7, 20}, ] assert_components_equal(list(nx.biconnected_components(G)), answer) G.add_edge(2,17) pts = set(nx.articulation_points(G)) assert_equal(pts, {7, 20, 21, 22})