def findCommunitiesInfomap(G, v_mentions=False): im = Infomap("--two-level --flow-model directed") if v_mentions: read_mentions(DATA_PATH, G) return 0 user_node = dict() node_user = [] l = 0 for i, n in enumerate(G.nodes): l = i user_node[n] = l node_user.append(n) last_l = l if not v_mentions: for e in G.edges: im.addLink(user_node[e[0]], user_node[e[1]]) else: for k, v in x_mentions.items(): for m in v: if not user_node.get(m): user_node[m] = l + 1 node_user.append(m) im.addLink(user_node[k], user_node[m]) im.run() print("Found %d top modules with codelength: %f" % (im.numTopModules(), im.codelength)) communities = {} for node_id, module_id in im.modules: if not node_id > last_l: communities[node_user[node_id]] = module_id nx.set_node_attributes(G, communities, 'community') return im.numTopModules()
def _apply_infomap(self): """Partition network with infomap algorithm Annotates node with community_id and returns number of communities found""" infomapWrapper = Infomap("--two-level --directed") print("Building Infomap network from a NetworkX graph...") for e in self.graph.edges(): infomapWrapper.addLink(*e) print("Find communities with Infomap...") infomapWrapper.run() print("Found %d top modules with codelength: %f" % (infomapWrapper.numTopModules(), infomapWrapper.codelength())) communities = {} for node in infomapWrapper.iterTree(): if node.isLeaf(): communities[node.physicalId] = node.moduleIndex() nx.set_node_attributes(self.graph, name='community', values=communities) self.graph = nx.relabel.relabel_nodes(self.graph, self.catalog, copy=True) self.num_modules = infomapWrapper.numTopModules() self.community_labels = set( nx.get_node_attributes(self.graph, "community").values())