Python networkx.connected_component_subgraphs() Examples
The following are 30
code examples of networkx.connected_component_subgraphs().
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: mapmatcher.py From mapmatching with MIT License | 7 votes |
def getNetworkGraph(segments,segmentlengths): """ Builds a networkx graph from the network file, inluding segment length taken from arcpy. It selects the largest connected component of the network (to prevent errors from routing between unconnected parts) """ #generate the full network path for GDAL to be able to read the file path =str(os.path.join(arcpy.env.workspace,segments)) print path if arcpy.Exists(path): g = nx.read_shp(path) #This selects the largest connected component of the graph sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0] print "graph size (excluding unconnected parts): "+str(len(g)) # Get the length for each road segment and append it as an attribute to the edges in the graph. for n0, n1 in sg.edges(): oid = sg[n0][n1]["OBJECTID"] sg[n0][n1]['length'] = segmentlengths[oid] return sg else: print "network file not found on path: "+path
Example #2
Source File: utility.py From ohmnet with MIT License | 6 votes |
def read_net(fname, weighted, directed, log): if weighted: G = nx.read_edgelist(inodetype=int, data=(('weight', float),), create_using=nx.DiGraph()) else: G = nx.read_edgelist(fname, nodetype=int, create_using=nx.DiGraph()) for edge in G.edges(): G[edge[0]][edge[1]]['weight'] = 1 if not directed: G = G.to_undirected() log.info('N: %d E: %d' % (G.number_of_nodes(), G.number_of_edges())) log.info('CC: %d' % nx.number_connected_components(G)) giant = max(nx.connected_component_subgraphs(G), key=len) log.info('N: %d E: %d' % (giant.number_of_nodes(), giant.number_of_edges())) return giant
Example #3
Source File: layout_unitigs.py From SALSA with MIT License | 6 votes |
def get_seed_scaffold(): g_idx = 1 seed_scaffolds = {} #this stores initial long scaffolds to_merge = set() for subg in nx.connected_component_subgraphs(G): p = [] for node in subg.nodes(): if subg.degree(node) == 1: p.append(node) #If this is 2 then we have found the path! if len(p) == 2: path = nx.shortest_path(subg,p[0],p[1]) seed_scaffolds[g_idx] = path g_idx += 1 #else try to insert these contigs in the long scaffolds generated previously else: for node in subg.nodes(): to_merge.add(node.split(':')[0]) return seed_scaffolds, to_merge
Example #4
Source File: mapmatcher.py From mapmatching with MIT License | 6 votes |
def getNetworkGraph(segments,segmentlengths): """ Builds a networkx graph from the network file, inluding segment length taken from arcpy. It selects the largest connected component of the network (to prevent errors from routing between unconnected parts) """ #generate the full network path for GDAL to be able to read the file path =str(os.path.join(arcpy.env.workspace,segments)) print path if arcpy.Exists(path): g = nx.read_shp(path) #This selects the largest connected component of the graph sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0] print "graph size (excluding unconnected parts): "+str(len(g)) # Get the length for each road segment and append it as an attribute to the edges in the graph. for n0, n1 in sg.edges(): oid = sg[n0][n1]["OBJECTID"] sg[n0][n1]['length'] = segmentlengths[oid] return sg else: print "network file not found on path: "+path
Example #5
Source File: utils.py From graph-generation with MIT License | 6 votes |
def caveman_special(c=2,k=20,p_path=0.1,p_edge=0.3): p = p_path path_count = max(int(np.ceil(p * k)),1) G = nx.caveman_graph(c, k) # remove 50% edges p = 1-p_edge for (u, v) in list(G.edges()): if np.random.rand() < p and ((u < k and v < k) or (u >= k and v >= k)): G.remove_edge(u, v) # add path_count links for i in range(path_count): u = np.random.randint(0, k) v = np.random.randint(k, k * 2) G.add_edge(u, v) G = max(nx.connected_component_subgraphs(G), key=len) return G
Example #6
Source File: molecule.py From rl_graph_generation with BSD 3-Clause "New" or "Revised" License | 6 votes |
def caveman_special(c=2,k=20,p_path=0.1,p_edge=0.3): p = p_path path_count = max(int(np.ceil(p * k)),1) G = nx.caveman_graph(c, k) # remove 50% edges p = 1-p_edge for (u, v) in list(G.edges()): if np.random.rand() < p and ((u < k and v < k) or (u >= k and v >= k)): G.remove_edge(u, v) # add path_count links for i in range(path_count): u = np.random.randint(0, k) v = np.random.randint(k, k * 2) G.add_edge(u, v) G = max(nx.connected_component_subgraphs(G), key=len) return G
Example #7
Source File: utils.py From graph-generation with MIT License | 6 votes |
def n_community(c_sizes, p_inter=0.01): graphs = [nx.gnp_random_graph(c_sizes[i], 0.7, seed=i) for i in range(len(c_sizes))] G = nx.disjoint_union_all(graphs) communities = list(nx.connected_component_subgraphs(G)) for i in range(len(communities)): subG1 = communities[i] nodes1 = list(subG1.nodes()) for j in range(i+1, len(communities)): subG2 = communities[j] nodes2 = list(subG2.nodes()) has_inter_edge = False for n1 in nodes1: for n2 in nodes2: if np.random.rand() < p_inter: G.add_edge(n1, n2) has_inter_edge = True if not has_inter_edge: G.add_edge(nodes1[0], nodes2[0]) #print('connected comp: ', len(list(nx.connected_component_subgraphs(G)))) return G
Example #8
Source File: utils.py From GraphRNN with MIT License | 6 votes |
def caveman_special(c=2,k=20,p_path=0.1,p_edge=0.3): p = p_path path_count = max(int(np.ceil(p * k)),1) G = nx.caveman_graph(c, k) # remove 50% edges p = 1-p_edge for (u, v) in list(G.edges()): if np.random.rand() < p and ((u < k and v < k) or (u >= k and v >= k)): G.remove_edge(u, v) # add path_count links for i in range(path_count): u = np.random.randint(0, k) v = np.random.randint(k, k * 2) G.add_edge(u, v) G = max(nx.connected_component_subgraphs(G), key=len) return G
Example #9
Source File: utils.py From GraphRNN with MIT License | 6 votes |
def n_community(c_sizes, p_inter=0.01): graphs = [nx.gnp_random_graph(c_sizes[i], 0.7, seed=i) for i in range(len(c_sizes))] G = nx.disjoint_union_all(graphs) communities = list(nx.connected_component_subgraphs(G)) for i in range(len(communities)): subG1 = communities[i] nodes1 = list(subG1.nodes()) for j in range(i+1, len(communities)): subG2 = communities[j] nodes2 = list(subG2.nodes()) has_inter_edge = False for n1 in nodes1: for n2 in nodes2: if np.random.rand() < p_inter: G.add_edge(n1, n2) has_inter_edge = True if not has_inter_edge: G.add_edge(nodes1[0], nodes2[0]) #print('connected comp: ', len(list(nx.connected_component_subgraphs(G)))) return G
Example #10
Source File: rg.py From QTop with GNU General Public License v3.0 | 6 votes |
def Partition(UnclusteredGraph, code, type, scale): # Make edges on Unclustered graph # between all nodes separated by distance 'scale' # on Dual Lattice for node1 in UnclusteredGraph.nodes(): for node2 in UnclusteredGraph.nodes(): if node1 != node2: d = code.distance(type, node1, node2) if d <= scale: UnclusteredGraph.add_edge(*(node1, node2), weight=d) Clusters = [] # Networkx connected components analysis subgraphs = nx.connected_component_subgraphs(UnclusteredGraph) for i, sg in enumerate(subgraphs): Clusters.append(sg.nodes(data=True)) return Clusters # Choose fixed node for cluster fusion
Example #11
Source File: greedy_coloring.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def strategy_connected_sequential(G, colors, traversal='bfs'): """ Connected sequential ordering (CS). Yield nodes in such an order, that each node, except the first one, has at least one neighbour in the preceeding sequence. The sequence can be generated using both BFS and DFS search (using the strategy_connected_sequential_bfs and strategy_connected_sequential_dfs method). The default is bfs. """ for component_graph in nx.connected_component_subgraphs(G): source = component_graph.nodes()[0] yield source # Pick the first node as source if traversal == 'bfs': tree = nx.bfs_edges(component_graph, source) elif traversal == 'dfs': tree = nx.dfs_edges(component_graph, source) else: raise nx.NetworkXError( 'Please specify bfs or dfs for connected sequential ordering') for (_, end) in tree: # Then yield nodes in the order traversed by either BFS or DFS yield end
Example #12
Source File: test_subgraph_copies.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setUp(self): self.undirected = [ nx.connected_component_subgraphs, nx.biconnected_component_subgraphs, ] self.directed = [ nx.weakly_connected_component_subgraphs, nx.strongly_connected_component_subgraphs, nx.attracting_component_subgraphs, ] self.subgraph_funcs = self.undirected + self.directed self.D = nx.DiGraph() self.D.add_edge(1, 2, eattr='red') self.D.add_edge(2, 1, eattr='red') self.D.nodes[1]['nattr'] = 'blue' self.D.graph['gattr'] = 'green' self.G = nx.Graph() self.G.add_edge(1, 2, eattr='red') self.G.nodes[1]['nattr'] = 'blue' self.G.graph['gattr'] = 'green'
Example #13
Source File: test_subgraph_copies.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def setUp(self): self.undirected = [ nx.connected_component_subgraphs, nx.biconnected_component_subgraphs, ] self.directed = [ nx.weakly_connected_component_subgraphs, nx.strongly_connected_component_subgraphs, nx.attracting_component_subgraphs, ] self.subgraph_funcs = self.undirected + self.directed self.D = nx.DiGraph() self.D.add_edge(1, 2, eattr='red') self.D.add_edge(2, 1, eattr='red') self.D.nodes[1]['nattr'] = 'blue' self.D.graph['gattr'] = 'green' self.G = nx.Graph() self.G.add_edge(1, 2, eattr='red') self.G.nodes[1]['nattr'] = 'blue' self.G.graph['gattr'] = 'green'
Example #14
Source File: test_connected.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_connected_raise(self): assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG) assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG) assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG) assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG,1) assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG) assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
Example #15
Source File: basic.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def is_bipartite_node_set(G,nodes): """Returns True if nodes and G/nodes are a bipartition of G. Parameters ---------- G : NetworkX graph nodes: list or container Check if nodes are a one of a bipartite set. Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> X = set([1,3]) >>> bipartite.is_bipartite_node_set(G,X) True Notes ----- For connected graphs the bipartite sets are unique. This function handles disconnected graphs. """ S=set(nodes) for CC in nx.connected_component_subgraphs(G): X,Y=sets(CC) if not ( (X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S)) ): return False return True
Example #16
Source File: recognition.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def is_forest(G): """ Returns True if `G` is a forest. A forest is a graph with no undirected cycles. For directed graphs, `G` is a forest if the underlying graph is a forest. The underlying graph is obtained by treating each directed edge as a single undirected edge in a multigraph. Parameters ---------- G : graph The graph to test. Returns ------- b : bool A boolean that is True if `G` is a forest. Notes ----- In another convention, a directed forest is known as a *polyforest* and then *forest* corresponds to a *branching*. See Also -------- is_branching """ if len(G) == 0: raise nx.exception.NetworkXPointlessConcept('G has no nodes.') if G.is_directed(): components = nx.weakly_connected_component_subgraphs else: components = nx.connected_component_subgraphs return all(len(c) - 1 == c.number_of_edges() for c in components(G))
Example #17
Source File: greedy_coloring.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def strategy_connected_sequential(G, colors, traversal='bfs'): """Returns an iterable over nodes in ``G`` in the order given by a breadth-first or depth-first traversal. ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``, representing depth-first traversal or breadth-first traversal, respectively. The generated sequence has the property that for each node except the first, at least one neighbor appeared earlier in the sequence. ``G`` is a NetworkX graph. ``colors`` is ignored. """ if traversal == 'bfs': traverse = nx.bfs_edges elif traversal == 'dfs': traverse = nx.dfs_edges else: raise nx.NetworkXError("Please specify one of the strings 'bfs' or" " 'dfs' for connected sequential ordering") for component in nx.connected_component_subgraphs(G): source = arbitrary_element(component) # Yield the source node, then all the nodes in the specified # traversal order. yield source for (_, end) in traverse(component, source): yield end
Example #18
Source File: test_kcutsets.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def _check_separating_sets(G): for Gc in nx.connected_component_subgraphs(G): if len(Gc) < 3: continue node_conn = nx.node_connectivity(Gc) for cut in nx.all_node_cuts(Gc): assert_equal(node_conn, len(cut)) H = Gc.copy() H.remove_nodes_from(cut) assert_false(nx.is_connected(H))
Example #19
Source File: test_weakly_connected.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_weakly_connected_component_subgraphs(self): wcc = nx.weakly_connected_component_subgraphs cc = nx.connected_component_subgraphs for G, C in self.gc: U = G.to_undirected() w = {frozenset(g) for g in wcc(G)} c = {frozenset(g) for g in cc(U)} assert_equal(w, c)
Example #20
Source File: basic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_bipartite_node_set(G, nodes): """Returns True if nodes and G/nodes are a bipartition of G. Parameters ---------- G : NetworkX graph nodes: list or container Check if nodes are a one of a bipartite set. Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> X = set([1,3]) >>> bipartite.is_bipartite_node_set(G,X) True Notes ----- For connected graphs the bipartite sets are unique. This function handles disconnected graphs. """ S = set(nodes) for CC in nx.connected_component_subgraphs(G): X, Y = sets(CC) if not ((X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S))): return False return True
Example #21
Source File: test_weakly_connected.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_weakly_connected_component_subgraphs(self): wcc = nx.weakly_connected_component_subgraphs cc = nx.connected_component_subgraphs for G, C in self.gc: U = G.to_undirected() w = {frozenset(g) for g in wcc(G)} c = {frozenset(g) for g in cc(U)} assert_equal(w, c)
Example #22
Source File: test_connected.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_connected_raise(self): assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG) assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG) assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG) assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG,1) assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG) assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
Example #23
Source File: test_connected.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_connected_component_subgraphs(self): wcc = nx.weakly_connected_component_subgraphs cc = nx.connected_component_subgraphs for G, C in self.gc: U = G.to_undirected() w = {frozenset(g) for g in wcc(G)} c = {frozenset(g) for g in cc(U)} assert_equal(w, c)
Example #24
Source File: test_kcutsets.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def _check_separating_sets(G): for Gc in nx.connected_component_subgraphs(G): if len(Gc) < 3: continue for cut in nx.all_node_cuts(Gc): assert_equal(nx.node_connectivity(Gc), len(cut)) H = Gc.copy() H.remove_nodes_from(cut) assert_false(nx.is_connected(H))
Example #25
Source File: basic.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def is_bipartite_node_set(G,nodes): """Returns True if nodes and G/nodes are a bipartition of G. Parameters ---------- G : NetworkX graph nodes: list or container Check if nodes are a one of a bipartite set. Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> X = set([1,3]) >>> bipartite.is_bipartite_node_set(G,X) True Notes ----- For connected graphs the bipartite sets are unique. This function handles disconnected graphs. """ S=set(nodes) for CC in nx.connected_component_subgraphs(G): X,Y=sets(CC) if not ( (X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S)) ): return False return True
Example #26
Source File: tripopt.py From BackpackingMapper with GNU General Public License v3.0 | 5 votes |
def establish_groups(self): d = list(nx.connected_component_subgraphs(self.trail_network)) for i, group in enumerate(d): for node in group: self.path_groups[node] = i self.group_list.append(i)
Example #27
Source File: rl_common.py From graph_adversarial_attack with MIT License | 5 votes |
def attackable(classifier, s2v_g, x = None, y = None): g = s2v_g.to_networkx() comps = [c for c in nx.connected_component_subgraphs(g)] set_id = {} for i in range(len(comps)): for j in comps[i].nodes(): set_id[j] = i if x is not None: r_i = [x] else: r_i = range(len(g) - 1) g_list = [] for i in r_i: if y is not None: assert x is not None r_j = [y] else: if x is not None: r_j = range(len(g) - 1) else: r_j = range(i + 1, len(g)) for j in r_j: if set_id[i] != set_id[j]: continue g2 = g.copy() g2.add_edge(i, j) assert nx.number_connected_components(g2) == s2v_g.label g_list.append(S2VGraph(g2, s2v_g.label)) if len(g_list) == 0: print(x, y) print(g.edges(), s2v_g.label) print(set_id) assert len(g_list) _, _, acc = classifier(g_list) return np.sum(acc.view(-1).numpy()) < len(g_list)
Example #28
Source File: rl_common.py From graph_adversarial_attack with MIT License | 5 votes |
def bannedActions(self, g, node_x): comps = [c for c in nx.connected_component_subgraphs(g)] set_id = {} for i in range(len(comps)): for j in comps[i].nodes(): set_id[j] = i banned_actions = set() for i in range(len(g)): if set_id[i] != set_id[node_x] or i == node_x: banned_actions.add(i) return banned_actions
Example #29
Source File: utils.py From graph-generation with MIT License | 5 votes |
def citeseer_ego(): _, _, G = data.Graph_load(dataset='citeseer') G = max(nx.connected_component_subgraphs(G), key=len) G = nx.convert_node_labels_to_integers(G) graphs = [] for i in range(G.number_of_nodes()): G_ego = nx.ego_graph(G, i, radius=3) if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400): graphs.append(G_ego) return graphs
Example #30
Source File: er_trivial_attack.py From graph_adversarial_attack with MIT License | 5 votes |
def propose_attack(model, s2v_g, num_added=1): g = s2v_g.to_networkx() comps = [c for c in nx.connected_component_subgraphs(g)] set_id = {} for i in range(len(comps)): for j in comps[i].nodes(): set_id[j] = i cand = [] for i in range(len(g) - 1): for j in range(i + 1, len(g)): if set_id[i] != set_id[j] or i == j: continue cand.append('%d %d' % (i, j)) if cmd_args.rand_att_type == 'random': added = np.random.choice(cand, num_added) added = [(int(w.split()[0]), int(w.split()[1])) for w in added] g.add_edges_from(added) return S2VGraph(g, s2v_g.label) elif cmd_args.rand_att_type == 'exhaust': g_list = [] for c in cand: x, y = [int(w) for w in c.split()] g2 = g.copy() g2.add_edge(x, y) g_list.append(S2VGraph(g2, s2v_g.label)) _, _, acc = model(g_list) ans = g_list[0] for i in range(len(g_list)): if acc.numpy()[i] < 1: ans = g_list[i] break return ans else: raise NotImplementedError