Creating Cliques From Connected Components Using Networkx
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_c
Solution 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>>>>>>withopen('cliques.csv', 'tw') as f:... w = csv.writer(f, csv.excel_tab)... w.writerow(['node1', 'node2', 'clique'])... w.writerows(p + (i,) for i, n inenumerate(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
Solution 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
.
Post a Comment for "Creating Cliques From Connected Components Using Networkx"