Python networkx.connected_components() Examples
The following are 30
code examples of networkx.connected_components().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: K3000_gfa_post_treatment.py From DiscoSnp with GNU Affero General Public License v3.0 | 6 votes |
def assign_cc(DG,max_cc_size=sys.maxsize): #CC=list(nx.connected_components(nx.Graph(DG))) #for cc in CC: # remove_outsider_nodes_from_cc(DG,cc) # recompute CC after having removed outsiders from original CCs # assign each node to its cc_id CC=list(nx.connected_components(nx.Graph(DG))) cc_id=0 for cc in CC: cc_id +=1 if len(cc) > max_cc_size: # print ("remove nodes from too large", len(cc) ) for node_id in cc: DG.remove_node(node_id) continue for node_id in cc: DG.nodes[node_id]['cc_id'] = cc_id
Example #2
Source File: connected.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def number_connected_components(G): """Return the number of connected components. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- n : integer Number of connected components See Also -------- connected_components Notes ----- For undirected graphs only. """ return len(list(connected_components(G)))
Example #3
Source File: __init__.py From EDeN with MIT License | 6 votes |
def _max_common_subgraph(GA, GB, pairings): matches = dict([(i, j) for i, j in enumerate(pairings)]) node_ids = [] for i, j in GA.edges(): ii = matches[i] jj = matches[j] li = GA.node[i]['label'] lii = GB.node[ii]['label'] lj = GA.node[j]['label'] ljj = GB.node[jj]['label'] if ((ii, jj) in GB.edges() or (jj, ii) in GB.edges()) and li == lii and lj == ljj: node_ids.append(ii) node_ids.append(jj) G = nx.subgraph(GB, node_ids) cc = nx.connected_components(G) return cc, G
Example #4
Source File: graph_canvas.py From networkx_viewer with GNU General Public License v3.0 | 6 votes |
def _radial_behind(self, home_node, behind_node): """Detect what nodes create a radial string behind the edge from home_node to behind_node""" base_islands = nx.number_connected_components(self.dispG) # If we remove the edge in question, it should radialize the system # and we can then detect the side to remove G = nx.Graph() G.add_nodes_from(self.dispG.nodes()) G.add_edges_from(self.dispG.edges()) G.remove_edge(home_node, behind_node) node_sets = list(nx.connected_components(G)) if len(node_sets) == base_islands: # There is no radial path behind this node return None else: for ns in node_sets: if behind_node in ns: # We know know what nodes to remove from the display graph # to remove the radial string return ns
Example #5
Source File: ego_splitter.py From EgoSplitting with GNU General Public License v3.0 | 6 votes |
def _create_egonet(self, node): """ Creating an ego net, extracting personas and partitioning it. Args: node: Node ID for egonet (ego node). """ ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node)) components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))} new_mapping = {} personalities = [] for k, v in components.items(): personalities.append(self.index) for other_node in v: new_mapping[other_node] = self.index self.index = self.index+1 self.components[node] = new_mapping self.personalities[node] = personalities
Example #6
Source File: ego_splitter.py From karateclub with GNU General Public License v3.0 | 6 votes |
def _create_egonet(self, node): """ Creating an ego net, extracting personas and partitioning it. Arg types: * **node** *(int)* - Node ID for ego-net (ego node). """ ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node)) components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))} new_mapping = {} personalities = [] for k, v in components.items(): personalities.append(self.index) for other_node in v: new_mapping[other_node] = self.index self.index = self.index+1 self.components[node] = new_mapping self.personalities[node] = personalities
Example #7
Source File: script_bp_cut.py From ibeis with Apache License 2.0 | 6 votes |
def rectify_labels(G, labels): # Ensure labels are rebased and # are different between different connected compoments graph = G.copy() node_to_annot_idx = nx.get_node_attributes(graph, 'annot_idx') cut_edges = [] for u, v in graph.edges(): idx1 = node_to_annot_idx[u] idx2 = node_to_annot_idx[v] if labels[idx1] != labels[idx2]: cut_edges.append((u, v)) graph.remove_edges_from(cut_edges) ccs_nodes = list(nx.connected_components(graph)) ccs_idxs = ut.unflat_take(node_to_annot_idx, ccs_nodes) # Make consistent sorting ccs_idxs = [sorted(idxs) for idxs in ccs_idxs] ccs_idxs = ut.sortedby(ccs_idxs, ut.take_column(ccs_idxs, 0)) labels = ut.ungroup([[c] * len(x) for c, x in enumerate(ccs_idxs)], ccs_idxs) labels = np.array(labels) return labels
Example #8
Source File: nx_edge_augmentation.py From ibeis with Apache License 2.0 | 6 votes |
def unconstrained_one_edge_augmentation(G): """Finds the smallest set of edges to connect G. This is a variant of the unweighted MST problem. If G is not empty, a feasible solution always exists. Example ------- >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)]) >>> G.add_nodes_from([6, 7, 8]) >>> sorted(unconstrained_one_edge_augmentation(G)) [(1, 4), (4, 6), (6, 7), (7, 8)] """ ccs1 = list(nx.connected_components(G)) C = collapse(G, ccs1) # When we are not constrained, we can just make a meta graph tree. meta_nodes = list(C.nodes()) # build a path in the metagraph meta_aug = list(zip(meta_nodes, meta_nodes[1:])) # map that path to the original graph inverse = defaultdict(list) for k, v in C.graph['mapping'].items(): inverse[v].append(k) for mu, mv in meta_aug: yield (inverse[mu][0], inverse[mv][0])
Example #9
Source File: kcomponents.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def _generate_partition(G, cuts, k): def has_nbrs_in_partition(G, node, partition): for n in G[node]: if n in partition: return True return False components = [] nodes = ({n for n, d in G.degree().items() if d > k} - {n for cut in cuts for n in cut}) H = G.subgraph(nodes) for cc in nx.connected_components(H): component = set(cc) for cut in cuts: for node in cut: if has_nbrs_in_partition(G, node, cc): component.add(node) if len(component) < G.order(): components.append(component) for component in _consolidate(components, k+1): yield component
Example #10
Source File: mixin_dynamic.py From ibeis with Apache License 2.0 | 6 votes |
def positive_components(infr, graph=None): r""" Generates the positive connected compoments (PCCs) in the graph These will contain both consistent and inconsinstent PCCs. Yields: cc: set: nodes within the PCC """ pos_graph = infr.pos_graph if graph is None or graph is infr.graph: ccs = pos_graph.connected_components() else: unique_labels = { pos_graph.node_label(node) for node in graph.nodes()} ccs = (pos_graph.connected_to(node) for node in unique_labels) for cc in ccs: yield cc
Example #11
Source File: ego_splitting.py From Splitter with GNU General Public License v3.0 | 6 votes |
def _create_egonet(self, node): """ Creating an ego net, extracting personas and partitioning it. Args: node: Node ID for egonet (ego node). """ ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node)) components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))} new_mapping = {} personalities = [] for k, v in components.items(): personalities.append(self.index) for other_node in v: new_mapping[other_node] = self.index self.index = self.index+1 self.components[node] = new_mapping self.personalities[node] = personalities
Example #12
Source File: PercoMCV.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def __k_clique_communities(g, cliques=None): if cliques is None: cliques = nx.find_cliques(g) cliques = [frozenset(c) for c in cliques if len(c) >= 4] # First index which nodes are in which cliques membership_dict = defaultdict(list) for clique in cliques: for node in clique: membership_dict[node].append(clique) # For each clique, see which adjacent cliques percolate perc_graph = nx.Graph() perc_graph.add_nodes_from(cliques) for clique in cliques: for adj_clique in _get_adjacent_cliques(clique, membership_dict): if len(clique.intersection(adj_clique)) >= 3: perc_graph.add_edge(clique, adj_clique) # Connected components of clique graph with perc edges # are the percolated cliques for component in nx.connected_components(perc_graph): yield frozenset.union(*component)
Example #13
Source File: NewApp.py From dr_droid with Apache License 2.0 | 6 votes |
def Tab_split(self): UG1 = self._Callinout.fcgnx_class_level.to_undirected(reciprocal=False) nodelist = list(nx.connected_components(UG1)) #for i in nodelist: # print i threshold = 5 #from 5 to 10 del UG1 max_nodes = max([len(i) for i in nodelist]) if max_nodes < threshold or Global.WHOLE_PROGRAM_ANALYSIS: #not split t = [] for i in nodelist: t = list(t) + list(i) self.new_nodelist = t self.subgraph_num = 1 else: self.new_nodelist = [ i for i in nodelist if len(i) >= threshold ] self.subgraph_num = len(self.new_nodelist) # this part is to find the major components
Example #14
Source File: graphing.py From grocsvs with MIT License | 6 votes |
def visualize_frags(outdir, graphs, options): from rpy2.robjects import r utilities.ensure_dir(outdir) for i, graph in enumerate(graphs): r.pdf(os.path.join(outdir, "fragments.cluster_{}.pdf".format(i))) for component in networkx.connected_components(graph): subgraph = graph.subgraph(component) ends = [node for node,degree in subgraph.degree_iter() if degree==1] breakends = [node for node in list(networkx.shortest_simple_paths(subgraph, ends[0], ends[1]))[0]] # breakends = [breakend_from_label(node) for node in breakends] breakends = breakends[:-1:2] + breakends[-1:] # print ")"*100, breakends for sample, dataset in sorted(options.iter_10xdatasets()): plot_frags(breakends, options, sample, dataset) # plot_frags(breakpoints, options, sample, dataset) r["dev.off"]()
Example #15
Source File: main.py From scTDA with GNU General Public License v3.0 | 6 votes |
def dendritic_graph(self): """ Builds skeleton of the topological representation (used internally) """ diam = networkx.diameter(self.gl) g3 = networkx.Graph() dicdend = {} for n in range(diam-1): nodedist = [] for k in self.pl: dil = networkx.shortest_path_length(self.gl, self.root, k) if dil == n: nodedist.append(str(k)) g2 = self.gl.subgraph(nodedist) dicdend[n] = sorted(networkx.connected_components(g2)) for n2, yu in enumerate(dicdend[n]): g3.add_node(str(n) + '_' + str(n2)) if n > 0: for n3, yu2 in enumerate(dicdend[n-1]): if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))): g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3)) return g3, dicdend
Example #16
Source File: tsp_lazy.py From PySCIPOpt with MIT License | 6 votes |
def findSubtours(self, checkonly, sol): EPS = 1.e-6 edges = [] x = self.model.data for (i, j) in x: if self.model.getSolVal(sol, x[i, j]) > EPS: edges.append((i,j)) G = networkx.Graph() G.add_edges_from(edges) Components = list(networkx.connected_components(G)) if len(Components) == 1: return False elif checkonly: return True for S in Components: self.model.addCons(quicksum(x[i, j] for i in S for j in S if j > i) <= len(S) - 1) print("cut: len(%s) <= %s" % (S, len(S) - 1)) return True
Example #17
Source File: kcomponents.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def _consolidate(sets, k): """Merge sets that share k or more elements. See: http://rosettacode.org/wiki/Set_consolidation The iterative python implementation posted there is faster than this because of the overhead of building a Graph and calling nx.connected_components, but it's not clear for us if we can use it in NetworkX because there is no licence for the code. """ G = nx.Graph() nodes = {i: s for i, s in enumerate(sets)} G.add_nodes_from(nodes) G.add_edges_from((u, v) for u, v in combinations(nodes, 2) if len(nodes[u] & nodes[v]) >= k) for component in nx.connected_components(G): yield set.union(*[nodes[n] for n in component])
Example #18
Source File: nx_edge_kcomponents.py From ibeis with Apache License 2.0 | 6 votes |
def _high_degree_components(G, k): """Helper for filtering components that cant be k-edge-connected. Removes and generates each node with degree less than k. Then generates remaining components where all nodes have degree at least k. """ # Iteravely remove parts of the graph that are not k-edge-connected H = G.copy() singletons = set(_low_degree_nodes(H, k)) while singletons: # Only search neighbors of removed nodes nbunch = set(it.chain.from_iterable(map(H.neighbors, singletons))) nbunch.difference_update(singletons) H.remove_nodes_from(singletons) for node in singletons: yield {node} singletons = set(_low_degree_nodes(H, k, nbunch)) # Note: remaining connected components may not be k-edge-connected if G.is_directed(): for cc in nx.strongly_connected_components(H): yield cc else: for cc in nx.connected_components(H): yield cc
Example #19
Source File: intra_citation.py From arxiv-public-datasets with MIT License | 5 votes |
def biggest_connected_subgraph(G): if G.is_directed(): comps = nx.weakly_connected_components(G) else: comps = nx.connected_components(G) biggest = max(comps, key=len) return G.subgraph(biggest)
Example #20
Source File: graph.py From gunpowder with MIT License | 5 votes |
def relabel_connected_components(self): """ create a new attribute "component" for each node in this Graph """ for i, wcc in enumerate(self.connected_components): for node in wcc: self.__graph.nodes[node]["component"] = i
Example #21
Source File: networkclustering.py From PyPSA with GNU General Public License v3.0 | 5 votes |
def busmap_by_linemask(network, mask): mask = network.lines.loc[:,['bus0', 'bus1']].assign(mask=mask).set_index(['bus0','bus1'])['mask'] G = nx.OrderedGraph() G.add_nodes_from(network.buses.index) G.add_edges_from(mask.index[mask]) return pd.Series(OrderedDict((n, str(i)) for i, g in enumerate(nx.connected_components(G)) for n in g), name='name')
Example #22
Source File: test_connected.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_connected_components(self): cc = nx.connected_components G = self.G C = { frozenset([0, 1, 2, 3]), frozenset([4, 5, 6, 7, 8, 9]), frozenset([10, 11, 12, 13, 14]) } assert_equal({frozenset(g) for g in cc(G)}, C)
Example #23
Source File: graph.py From iva with GNU General Public License v3.0 | 5 votes |
def connected_components(self): return sorted([sorted(x) for x in networkx.connected_components(self.graph)])
Example #24
Source File: algorithm.py From Pixel-Art with GNU General Public License v3.0 | 5 votes |
def create_shapes(self): self.shapes = set() # Identify shapes in the graph by identifying the connected component subgraphs for pcg in (self.pixel_graph.subgraph(c).copy() for c in networkx.connected_components(self.pixel_graph)): pixels = set() value = None corners = set() for pixel, attrs in pcg.nodes(data=True): pixels.add(pixel) corners.update(attrs['corners']) value = attrs['value'] self.shapes.add(Shape(pixels, value, corners)) # Create a separate shape for each connected component subgraph and store all the pixels of the subgraph # in it
Example #25
Source File: algorithm.py From Pixel-Art with GNU General Public License v3.0 | 5 votes |
def add_shape_boundaries(self): self.paths = {} # Add the obtained boundaries to the corresponding shapes for shape in self.shapes: sg = self.outlines_graph.subgraph(shape.corners) for graph in (sg.subgraph(c).copy() for c in networkx.connected_components(sg)): path = self.make_path(graph) if (min(graph.nodes()) == min(sg.nodes())): shape.add_outline(path, True) else: shape.add_outline(path)
Example #26
Source File: cnmf.py From minian with GNU General Public License v3.0 | 5 votes |
def label_connected(adj, only_connected=False): np.fill_diagonal(adj, 0) adj = np.triu(adj) g = nx.convert_matrix.from_numpy_matrix(adj) labels = np.zeros(adj.shape[0], dtype=np.int) for icomp, comp in enumerate(nx.connected_components(g)): comp = list(comp) if only_connected and len(comp) == 1: labels[comp] = -1 else: labels[comp] = icomp return labels
Example #27
Source File: test_clique_merge_operation.py From kgx with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_clique_generation(): """ Test for generation of cliques """ t = PandasTransformer() t.parse(os.path.join(resource_dir, 'cm_nodes.csv')) t.parse(os.path.join(resource_dir, 'cm_edges.csv')) t.report() cm = CliqueMerge(prefix_prioritization_map) cm.build_cliques(t.graph) cliques = list(nx.connected_components(cm.clique_graph)) assert len(cliques) == 2
Example #28
Source File: lammps_main.py From lammps_interface with MIT License | 5 votes |
def compute_molecules(self, size_cutoff=0.5): """Ascertain if there are molecules within the porous structure""" for j in nx.connected_components(self.graph): # return a list of nodes of connected graphs (decisions to isolate them will come later) # Upper limit on molecule size is 100 atoms. if((len(j) <= self.graph.original_size*size_cutoff) or (len(j) < 25)) and (not len(j) > 100) : self.molecules.append(j)
Example #29
Source File: graph.py From gunpowder with MIT License | 5 votes |
def connected_components(self): if not self.directed: return nx.connected_components(self.__graph) else: return nx.weakly_connected_components(self.__graph)
Example #30
Source File: gng.py From GrowingNeuralGas with MIT License | 5 votes |
def cluster_data(self): unit_to_cluster = np.zeros(self.units_created) cluster = 0 for c in nx.connected_components(self.network): for unit in c: unit_to_cluster[unit] = cluster cluster += 1 clustered_data = [] for observation in self.data: nearest_units = self.find_nearest_units(observation) s = nearest_units[0] clustered_data.append((observation, unit_to_cluster[s])) return clustered_data