Creating cliques from connected components using networkx

余生长醉 提交于 2020-01-06 06:51:07

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/48416445/creating-cliques-from-connected-components-using-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!