pythongraphnetworkxclique

networkx: decomposing cliques into unique edges


I have a dictionary in the following form

{   0: [1, 2, 3, 4, 5]
    1: [6, 2, 3, 4, 5]
    2: [3, 4, 5, 6, 7]
    3: [8, 9]
    ...
}

Each of the values (unsorted lists) correspond to a clique that I want to induce in my graph. Unfortunately, as you can see, many of the cliques share vertices that are also part of other cliques. Right now I do a straight-forward inducing of these cliques:

for clique in clique_dict.itervalues(): 
    graph.add_edges_from(combinations(clique, 2))

But this is time-consuming in the sense that many pairs of edges are already induced earlier as part of other clique induction. Is there a more efficient way to go about inducing these cliques? Maybe some post processing on these cliques themselves?


Solution

  • You may get some slight improvement if you prepare a list of all unique edges and then add them all at once:

    edges = set(chain.from_iterable([tuple(sorted(pair)) for pair 
                in combinations(clique, 2)] for clique in clique_dict.values()))
    graph.add_edges_from(edges)
    

    Sorting is added to avoid having anti-parallel edges like (2,3) and (3,2).