Reputation: 175
I want to create a graph of largest strongly connected component of a directed graph. Networkx has a function (components.strongly_connected_components) that can extract a largest strongly connected component, but it only returns a generator of sets of nodes. But this doesn't contain the connection between nodes.
Is there any function that can create a directed graph of largest strongly connected component?
Upvotes: 2
Views: 1610
Reputation: 2821
Please see docs for extracting a subgraph.
You can get the edges of the subgraph containing those nodes.
In this simple example, nodes 2, 3, and 4 are strongly connected, but node 5 is disconnected (completely).
import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([2, 3, 4, 5])
G.add_edge(2, 3)
G.add_edge(4, 3)
G.add_edge(4, 2)
G.add_edge(3, 2)
G.add_edge(3, 4)
G.add_edge(2, 4)
# following results in [{2, 3, 4}, {5}]
strongs = sorted(nx.strongly_connected_components(G), key=len, reverse=True)
for strong in strongs:
print(G.subgraph(strong).edges())
Result (first line is for {2, 3, 4}
, and the second line is for {5}
which has no edges):
[(2, 3), (2, 4), (3, 2), (3, 4), (4, 3), (4, 2)]
[]
Upvotes: 2