Skip to content

Instantly share code, notes, and snippets.

@conradlee
Created November 5, 2011 19:56
Show Gist options
  • Save conradlee/1341940 to your computer and use it in GitHub Desktop.
Save conradlee/1341940 to your computer and use it in GitHub Desktop.
Clique percolation in Python using NetworkX (with indexing)
import networkx as nx
from collections import defaultdict
def get_percolated_cliques(G, k):
perc_graph = nx.Graph()
cliques = [frozenset(c) for c in nx.find_cliques(G) if len(c) >= k]
perc_graph.add_nodes_from(cliques)
# First index which nodes are in which cliques
membership_dict = defaultdict(list)
for clique in cliques:
for node in clique:
membership_dict[node].append(clique)
# For each clique, see which adjacent cliques percolate
for clique in cliques:
for adj_clique in get_adjacent_cliques(clique, membership_dict):
if len(clique.intersection(adj_clique)) >= (k - 1):
perc_graph.add_edge(clique, adj_clique)
# Connected components of clique graph with perc edges
# are the percolated cliques
for component in nx.connected_components(perc_graph):
yield(frozenset.union(*component))
def get_adjacent_cliques(clique, membership_dict):
adjacent_cliques = set()
for n in clique:
for adj_clique in membership_dict[n]:
if clique != adj_clique:
adjacent_cliques.add(adj_clique)
return adjacent_cliques
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment