Reputation: 2613
I have created a graph using networkx
in Python
.
import networkx as nx
G = createGraph ('abc.csv') #My function that returns graph from file.
connected_components = nx.connected_components(G)
print (connected_components)
<generator object connected_components at 0x00000000221EF1A8>
nbr_cc = nx.number_connected_components(G)
print (nbr_cc)
57215
I want to convert every connected component into a clique and then write a csv file in following manner:
node1_id node2_id connected_component_id
1 2 1
1 3 1
1 4 1
2 1 1
. . .
. . .
500 600 9
How to do that? Is there any way to achieve that in notworkx or using any other python library?
Upvotes: 0
Views: 631
Reputation: 23827
This answer is effectively identical to PaulPanzer's answer once you look at how the specific algorithms I use are coded in networkx:
G=nx.Graph()
G.add_edges_from([(1,2), (2,3), (4,5), (5,6)])
list(nx.connected_components(G))
> [{1,2,3},{4,5,6}]
#we're done setting G up. Let's do it.
CCs = nx.connected_components(G)
complete_subgraphs = (nx.complete_graph(component) for component in CCs)
H=nx.compose_all(complete_subgraphs)
Here we first find the connected components (technically we create a generator for them). Then we find all the complete graphs using nx.complete_graph(nodes)
for each of those components. Finally we join all the graphs together with compose_all
.
Upvotes: 1
Reputation: 53029
You can use itertools.permutations
:
>>> G
<networkx.classes.graph.Graph object at 0x7f123559f3c8>
>>> list(nx.connected_components(G))
[{0, 4, 5, 6, 7, 9}, {1}, {8, 2}, {3}]
>>> import itertools
>>> import csv
>>>
>>> with open('cliques.csv', 'tw') as f:
... w = csv.writer(f, csv.excel_tab)
... w.writerow(['node1', 'node2', 'clique'])
... w.writerows(p + (i,) for i, n in enumerate(nx.connected_components(G), 1) for p in itertools.permutations(n, 2))
...
20
Creates a file containing:
node1 node2 clique
0 4 1
0 5 1
0 6 1
0 7 1
0 9 1
4 0 1
4 5 1
...
9 6 1
9 7 1
8 2 3
2 8 3
Upvotes: 1