I'd like to extract connected components (as bipartite graphs) from a bipartite graph using networkx
. But connected components in networkx
is not for bipartite graphs but general undirected and direct graphs. Is there an example of bipartite graphs? Thanks.
Asked
Active
Viewed 1,360 times
0

fuglede
- 17,388
- 2
- 54
- 99

user1424739
- 11,937
- 17
- 63
- 152
-
1What do you mean by connected components of a bipartite graph, if they're not the connected components of the underlying undirected graph? – fuglede Apr 17 '20 at 19:39
-
They are. But the components need to be represented as bipartite graphs. I don't think the connected components general graphs will automatically do so. – user1424739 Apr 17 '20 at 19:47
-
Could you post your full testing code as an answer? Thanks. – user1424739 Apr 17 '20 at 20:05
1 Answers
1
The subgraphs corresponding to connected components of a bipartite graphs (and indeed any graph) themselves carry over all node attributes, so that in particular, you can use those to mark your partitions, as in the docs:
In [28]: B = nx.Graph()
...: B.add_nodes_from([1, 2, 3, 4], bipartite=0)
...: B.add_nodes_from(['a', 'b', 'c'], bipartite=1)
...: B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'a'), (3, 'c'), (4, 'c')])
...:
...: G = B.subgraph(next(nx.connected_components(B)))
In [30]: G.nodes
Out[30]: NodeView((1, 2, 'a', 'b'))
In [31]: G.nodes[1]
Out[31]: {'bipartite': 0}

fuglede
- 17,388
- 2
- 54
- 99
-
How to get the nodes from bipartite 0 and 1. ` for g in nx.connected_components(B): print([x for x in g if B.nodes(data=True)[x]['bipartite'] == 0]) print([x for x in g if B.nodes(data=True)[x]['bipartite'] == 1]) ` I use something like this. I am not sure if this is the most efficient way. – user1424739 Apr 17 '20 at 20:58
-
This is cleaner: `B.nodes[x]['bipartite']` rather than `B.nodes(data=True)[x]['bipartite']`. I'm not sure whether it's more efficient, since I'm not sure how `B.nodes(data=True)` is implemented, but it might be quite a bit faster. It's definitely not slower. – Joel Apr 17 '20 at 22:12
-
My guess would be that the moment you're setting up the bipartite graph in the first case, you'll have some way of indexing the partitions, so you never even have to look up the attributes. – fuglede Apr 18 '20 at 18:14