def get_infomap_communities(graph: nx.Graph, reddit_edge_weight=None):
    im = Infomap("--flow-model undirected -N 10 --prefer-modular-solution")

    ## im only works with numerical ids, so we need to save a mapping

    ids_to_names = {}
    names_to_ids = {}

    for index, node in enumerate(graph.nodes):
        ids_to_names[index] = node
        names_to_ids[node] = index
        im.add_node(index, name=node)

    # iterate over edges and add them to the im tree, optionally adding the weight
    for e1, e2, data in graph.edges(data=True):
        e1_id = names_to_ids[e1]
        e2_id = names_to_ids[e2]
        weight = data[reddit_edge_weight] if reddit_edge_weight else None
        link = (e1_id, e2_id, weight) if weight else (e1_id, e2_id)
        im.add_link(*link)

    im.run()
    for node in im.tree:
        if node.is_leaf:
            graph.nodes[ids_to_names[node.node_id]][
                "infomap_community"
            ] = node.module_id

    return graph
Beispiel #2
0
def get_benchmark_amis(G,gt):
    # Louvain
    louv = community.best_partition(G)
    louvc = []
    for idx,val in louv.items():
        louvc.append(val)

    louv_ami = metrics.adjusted_mutual_info_score(gt,louvc)
    
    # Fluid communities
    fluid = asyn_fluidc(G,2)
    list_nodes = [set(c) for c in fluid]
    est_idx = np.zeros((nx.number_of_nodes(G),))
    for i in range(len(list_nodes)):
        for idx in list_nodes[i]:
            est_idx[idx] = i

    fluid_ami = metrics.adjusted_mutual_info_score(gt,est_idx)
    
    # FastGreedy
    list_nodes = list(greedy_modularity_communities(G))
    est_idx = np.zeros((nx.number_of_nodes(G),))
    for i in range(len(list_nodes)):
        for idx in list_nodes[i]:
            est_idx[idx] = i

    fg_ami = metrics.adjusted_mutual_info_score(gt,est_idx)
    
    # Infomap
    im = Infomap()
    for node in G.nodes:
        im.add_node(node)
    for edge in G.edges:
        im.add_link(edge[0], edge[1])
        im.add_link(edge[1],edge[0])
    # Run the Infomap search algorithm to find optimal modules
    im.run()
    # print(f"Found {im.num_top_modules} modules with Infomap")
    est_idx = np.zeros((nx.number_of_nodes(G),))
    for node in im.tree:
        if node.is_leaf:
            est_idx[node.node_id] = node.module_id

    im_ami = metrics.adjusted_mutual_info_score(gt,est_idx)
    
    benchmark = {'Louvain':louv_ami,
            'Fluid':fluid_ami,
            'FastGreedy':fg_ami,
            'Infomap':im_ami}
    
    return benchmark
runtime = time.time() - time_s
mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
scores['louvain-noisy'] = mutual_info
runtimes['louvain-noisy'] = runtime

###########################################################
###########################################################
# Method: Infomap
###########################################################
# Raw
time_s = time.time()
im = Infomap()
for node in G.nodes:
    im.add_node(node)
for edge in G.edges:
    im.add_link(edge[0], edge[1])
    im.add_link(edge[1], edge[0])
# Run the Infomap search algorithm to find optimal modules
im.run()
# print(f"Found {im.num_top_modules} modules with Infomap")
est_idx = np.zeros((num_nodes, ))
for node in im.tree:
    if node.is_leaf:
        est_idx[node.node_id] = node.module_id

runtime = time.time() - time_s
mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
scores['infomap-raw'] = mutual_info
runtimes['infomap-raw'] = runtime

# Noisy
from infomap import Infomap

# Command line flags can be added as a string to Infomap
im = Infomap("--two-level --directed")

# Add weight as optional third argument
im.add_link(0, 1)
im.add_link(0, 2)
im.add_link(0, 3)
im.add_link(1, 0)
im.add_link(1, 2)
im.add_link(2, 1)
im.add_link(2, 0)
im.add_link(3, 0)
im.add_link(3, 4)
im.add_link(3, 5)
im.add_link(4, 3)
im.add_link(4, 5)
im.add_link(5, 4)
im.add_link(5, 3)

# Run the Infomap search algorithm to find optimal modules
im.run()

print(f"Found {im.num_top_modules} modules with codelength: {im.codelength}")

print("Result")
print("\n#node module")
for node in im.tree:
    if node.is_leaf:
        print(node.node_id, node.module_id)
from infomap import Infomap

# Compare codelengths for two different partitions of a network
# composed of two triangles {0,1,2} and {5,6,7} connected by a
# chain of two nodes in the middle {3,4}.

im = Infomap(two_level=True, silent=True)

# Add weight as an optional third argument
im.add_link(0, 1)
im.add_link(0, 2)
im.add_link(1, 2)
im.add_link(2, 3)
im.add_link(3, 4)
im.add_link(4, 5)
im.add_link(5, 6)
im.add_link(5, 7)
im.add_link(6, 7)

# Three modules, with the chain in its own module
partition1 = {
    0: 0,
    1: 0,
    2: 0,
    3: 1,
    4: 1,
    5: 2,
    6: 2,
    7: 2,
}
Beispiel #6
0
im = Infomap(two_level=True, silent=True)

im.set_name(1, "PRE")
im.set_name(2, "SCIENCE")
im.set_name(3, "PRL")
im.set_name(4, "BIO")

im.add_state_node(0, 1)
im.add_state_node(1, 2)
im.add_state_node(2, 3)
im.add_state_node(3, 2)
im.add_state_node(4, 2)
im.add_state_node(5, 4)

im.add_link(0, 1)
im.add_link(1, 2)
im.add_link(3, 2)
im.add_link(4, 5)

im.run()

print(
    f"Found {im.num_top_modules} modules with codelength {im.codelength:.8f} bits"
)

print("\n#node_id module")
for node, module in im.get_modules(states=True).items():
    print(node, module)

print("\nState nodes:")
Beispiel #7
0
from infomap import Infomap

im = Infomap(two_level=True, silent=True)

# Add weight as an optional third argument
im.add_link(1, 2)
im.add_link(1, 3)
im.add_link(2, 3)
im.add_link(3, 4)
im.add_link(4, 5)
im.add_link(4, 6)
im.add_link(5, 6)

im.run()

print(
    f"Found {im.num_top_modules} modules with codelength {im.codelength:.8f} bits"
)

modules = im.get_modules()

print("Modify the network and test partition...")

# Do some modification to the network
im.add_link(1, 5)
# Note that removing links will not remove nodes if they become unconnected
im.remove_link(5, 6)

# Run again with the optimal partition from the original network as initial solution
# Set no_infomap to skip optimization and just calculate the codelength
im.run(initial_partition=modules, no_infomap=True)
Beispiel #8
0
from infomap import Infomap

im = Infomap(two_level=True, silent=True)

# Set the start id for bipartite nodes
im.bipartite_start_id = 5

# Add weight as an optional third argument
im.add_link(5, 0)
im.add_link(5, 1)
im.add_link(5, 2)
im.add_link(6, 2, 0.5)
im.add_link(6, 3)
im.add_link(6, 4)

im.run()

print(
    f"Found {im.num_top_modules} modules with codelength {im.codelength:.8f} bits"
)

print("\n#node module:")
for node, module in im.modules:
    print(node, module)
Beispiel #9
0
from infomap import Infomap

# Changing eta to 2 results in three modules that maps to metadata categories
eta = 1
im = Infomap(two_level=True, silent=True, meta_data_rate=eta)

# Two triangles connected by {2, 3}
im.add_link(0, 1)
im.add_link(0, 2)
im.add_link(2, 1)
im.add_link(2, 3)
im.add_link(3, 4)
im.add_link(3, 5)
im.add_link(4, 5)

im.set_meta_data(0, 2)
im.set_meta_data(1, 2)
im.set_meta_data(2, 1)
im.set_meta_data(3, 1)
im.set_meta_data(4, 3)
im.set_meta_data(5, 3)

im.run()

print(
    f"\nFound {im.num_top_modules} modules with codelength {im.codelength:.8f} bits"
)
print(
    f" - Codelength = index codelength ({im.index_codelength:.8f}) + module codelength ({im.module_codelength:.8f})"
)
print(