Infomap class

class infomap.Infomap

Bases: _InfomapResultsMixin, _InfomapWritersMixin, InfomapWrapper

This class is a thin wrapper around Infomap C++ compiled with SWIG.

Examples

Create an instance and add nodes and links:

>>> from infomap import Infomap
>>> im = Infomap(silent=True)
>>> im.add_node(1)
>>> im.add_node(2)
>>> im.add_link(1, 2)
>>> im.run()
>>> im.codelength
1.0

Create an instance and read a network file:

>>> from infomap import Infomap
>>> im = Infomap(silent=True, num_trials=10)
>>> im.read_file("ninetriangles.net")
>>> im.run()
>>> tol = 1e-4
>>> abs(im.codelength - 3.4622731375264144) < tol
True

For more examples, see the examples directory.

__init__(args=None, cluster_data=None, no_infomap=False, skip_adjust_bipartite_flow=False, bipartite_teleportation=False, weight_threshold=None, include_self_links=None, no_self_links=False, node_limit=None, matchable_multilayer_ids=None, assign_to_neighbouring_module=False, meta_data=None, meta_data_rate=1.0, meta_data_unweighted=False, tree=False, ftree=False, clu=False, verbosity_level=1, silent=False, pretty=False, out_name=None, no_file_output=False, clu_level=None, output=None, hide_bipartite_nodes=False, print_all_trials=False, two_level=False, flow_model=None, directed=None, recorded_teleportation=False, use_node_weights_as_flow=False, to_nodes=False, teleportation_probability=0.15, regularized=False, regularization_strength=1.0, entropy_corrected=False, entropy_correction_strength=1.0, markov_time=1.0, variable_markov_time=False, variable_markov_damping=1.0, variable_markov_min_scale=1.0, preferred_number_of_modules=None, multilayer_relax_rate=0.15, multilayer_relax_limit=-1, multilayer_relax_limit_up=-1, multilayer_relax_limit_down=-1, multilayer_relax_by_jsd=False, seed=123, num_trials=1, core_loop_limit=10, core_level_limit=None, tune_iteration_limit=None, core_loop_codelength_threshold=1e-10, tune_iteration_relative_threshold=1e-05, fast_hierarchical_solution=None, prefer_modular_solution=False, inner_parallelization=False, num_random_moves=None, max_degree_for_random_moves=None)

Create a new Infomap instance.

Keyword arguments mirror the Infomap CLI flags. Use InfomapOptions for a reusable configuration object and the full parameter reference.

Parameters:

args (str, optional) – Raw Infomap arguments to prepend before rendered keyword options.

add_edge_index(edge_index, edge_weight=None, num_nodes=None, directed=True, node_ids=None)

Add links and nodes from a PyG-style edge index.

Parameters:
  • edge_index (array-like) – Two-row edge index where row 0 contains source node ids and row 1 contains target node ids.

  • edge_weight (array-like, optional) – One-dimensional edge weights with one value per edge. If omitted, every edge is treated as weight 1.0.

  • num_nodes (int, optional) – Total number of nodes. Pass this to preserve isolated nodes.

  • directed (bool, optional) – Interpret edges as directed. Default True.

  • node_ids (sequence, optional) – External node ids in internal node order. If omitted, 0..n-1 is used.

Returns:

Dict with internal integer node ids as keys and external node ids as values.

Return type:

dict

add_igraph_graph(g, edge_weights=None, vertex_weights=None, node_id='node_id', layer_id='layer_id', multilayer_inter_intra_format=True)

Add a python-igraph graph.

This method imports igraph lazily, so igraph is not required unless this method is used. It uses igraph’s zero-based vertex indices as state/internal ids, uses the name vertex attribute as Infomap node names when present, and treats node_id/layer_id vertex attributes as state/multilayer metadata.

Parameters:
  • g (igraph.Graph) – A python-igraph graph.

  • edge_weights (str, sequence, or None, optional) – Edge weight attribute name, explicit sequence with one value per edge, or None to treat every edge as weight 1. Default None.

  • vertex_weights (None, optional) – Accepted for igraph API familiarity but not supported yet.

  • node_id (str, optional) – Vertex attribute for physical node ids, implying a state network.

  • layer_id (str, optional) – Vertex attribute for layer ids, implying a multilayer network when node_id is also present.

  • multilayer_inter_intra_format (bool, optional) – Use intra/inter format to simulate inter-layer links. Default True.

Returns:

Dict with igraph vertex indices as keys and vertex names as values when names are present, otherwise vertex indices as values.

Return type:

dict

Add a link.

Notes

If the source or target nodes does not exist, they will be created.

See also

remove_link

Parameters:
  • source_id (int)

  • target_id (int)

  • weight (float, optional)

Add several links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> links = (
...     (1, 2),
...     (1, 3)
... )
>>> im.add_links(links)
>>> import numpy as np
>>> im.add_links(np.array([[2, 3, 1.0], [3, 4, 2.0]]))

See also

add_link, remove_link

Parameters:

links (iterable of tuples or numpy.ndarray) – Iterable of tuples of int of the form (source_id, target_id, [weight]). NumPy arrays must be 2-dimensional with 2 or 3 columns, where the first two columns are source and target ids and the optional third column is link weight.

Add an inter-layer link.

Adds a link between two layers in a multilayer network. The link is specified through a shared physical node, but that jump will not be recorded so Infomap will spread out this link to the next possible steps for the random walker in the target layer.

Notes

This multilayer format requires a directed network, so if the directed flag is not present, it will add all links also in their opposite direction to transform the undirected input to directed. If no inter-layer links are added, Infomap will simulate these by relaxing the random walker’s constraint to its current layer. The final state network will be generated on run, which will clear the temporary data structure that holds the provided inter-layer links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> im.add_multilayer_inter_link(1, 1, 2)
>>> im.add_multilayer_inter_link(1, 2, 2)
>>> im.add_multilayer_inter_link(2, 1, 1)
>>> im.add_multilayer_inter_link(2, 3, 1)
Parameters:
  • source_layer_id (int)

  • node_id (int)

  • target_layer_id (int)

  • weight (float, optional)

Add several inter-layer links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> links = (
...     (1, 1, 2),
...     (1, 2, 2, 2.0),
...     (2, 3, 1),
... )
>>> im.add_multilayer_inter_links(links)
Parameters:

links (iterable of tuples) – Iterable of tuples of the form (source_layer_id, node_id, target_layer_id, [weight]). NumPy arrays must be 2-dimensional with 3 or 4 columns.

Add an intra-layer link.

Adds a link within a layer in a multilayer network.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> im.add_multilayer_intra_link(1, 1, 2)
>>> im.add_multilayer_intra_link(1, 2, 3)
>>> im.add_multilayer_intra_link(2, 1, 3)
>>> im.add_multilayer_intra_link(2, 3, 4)

Notes

This multilayer format requires a directed network, so if the directed flag is not present, it will add all links also in their opposite direction to transform the undirected input to directed. If no inter-layer links are added, Infomap will simulate those by relaxing the random walker’s constraint to its current layer. The final state network will be generated on run, which will clear the temporary data structure that holds the provided intra-layer links.

Parameters:
  • layer_id (int)

  • source_node_id (int)

  • target_node_id (int)

  • weight (float, optional)

Add several intra-layer links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> links = (
...     (1, 1, 2),
...     (1, 2, 3, 2.0),
...     (2, 1, 3),
... )
>>> im.add_multilayer_intra_links(links)
Parameters:

links (iterable of tuples) – Iterable of tuples of the form (layer_id, source_node_id, target_node_id, [weight]). NumPy arrays must be 2-dimensional with 3 or 4 columns.

Add a multilayer link.

Adds a link between layers in a multilayer network.

Examples

Usage with tuples:

>>> from infomap import Infomap
>>> im = Infomap()
>>> source_multilayer_node = (0, 1) # layer_id, node_id
>>> target_multilayer_node = (1, 2) # layer_id, node_id
>>> im.add_multilayer_link(source_multilayer_node, target_multilayer_node)

Usage with MultilayerNode

>>> from infomap import Infomap, MultilayerNode
>>> im = Infomap()
>>> source_multilayer_node = MultilayerNode(layer_id=0, node_id=1)
>>> target_multilayer_node = MultilayerNode(layer_id=1, node_id=2)
>>> im.add_multilayer_link(source_multilayer_node, target_multilayer_node)

Notes

This is the full multilayer format that supports both undirected and directed links. Infomap will not make any changes to the network.

Parameters:
  • source_multilayer_node (tuple of int, or MultilayerNode) – If passed a tuple, it should be of the format (layer_id, node_id).

  • target_multilayer_node (tuple of int, or MultilayerNode) – If passed a tuple, it should be of the format (layer_id, node_id).

  • weight (float, optional)

Add several multilayer links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> links = (
...     ((0, 1), (1, 2)),
...     ((0, 3), (1, 2))
... )
>>> im.add_multilayer_links(links)
Parameters:

links (iterable of tuples) – Iterable of tuples of the form (source_node, target_node, [weight]). NumPy arrays must be 2-dimensional with 4 or 5 columns of the form (source_layer_id, source_node_id, target_layer_id, target_node_id, [weight]).

add_networkx_graph(g, weight='weight', node_id='node_id', layer_id='layer_id', multilayer_inter_intra_format=True)

Add a NetworkX graph.

Uses weighted links if present on the weight attribute. Treats the graph as a state network if the node_id attribute is present and as a multilayer network if also the layer_id attribute is present on the nodes.

Examples

>>> import networkx as nx
>>> from infomap import Infomap
>>> G = nx.Graph([("a", "b"), ("a", "c")])
>>> im = Infomap(silent=True)
>>> mapping = im.add_networkx_graph(G)
>>> mapping
{0: 'a', 1: 'b', 2: 'c'}
>>> im.run()
>>> for node in im.nodes:
...     print(node.node_id, node.module_id, node.flow, mapping[node.node_id])
0 1 0.5 a
1 1 0.25 b
2 1 0.25 c

Usage with a state network

>>> import networkx as nx
>>> from infomap import Infomap
>>> G = nx.Graph()
>>> G.add_node("a", node_id=1)
>>> G.add_node("b", node_id=2)
>>> G.add_node("c", node_id=3)
>>> G.add_node("d", node_id=1)
>>> G.add_node("e", node_id=4)
>>> G.add_node("f", node_id=5)
>>> G.add_edge("a", "b")
>>> G.add_edge("a", "c")
>>> G.add_edge("b", "c")
>>> G.add_edge("d", "e")
>>> G.add_edge("d", "f")
>>> G.add_edge("e", "f")
>>> im = Infomap(silent=True)
>>> mapping = im.add_networkx_graph(G)
>>> mapping
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
>>> im.run()
>>> for node in im.nodes:
...     print(node.state_id, node.node_id, node.module_id, node.flow)
0 1 1 0.16666666666666666
1 2 1 0.16666666666666666
2 3 1 0.16666666666666666
3 1 2 0.16666666666666666
4 4 2 0.16666666666666666
5 5 2 0.16666666666666666

Usage with a multilayer network

>>> import networkx as nx
>>> from infomap import Infomap
>>> G = nx.Graph()
>>> G.add_node(11, node_id=1, layer_id=1)
>>> G.add_node(21, node_id=2, layer_id=1)
>>> G.add_node(22, node_id=2, layer_id=2)
>>> G.add_node(32, node_id=3, layer_id=2)
>>> G.add_edge(11, 21, weight=2)
>>> G.add_edge(22, 32)
>>> im = Infomap(silent=True)
>>> mapping = im.add_networkx_graph(G)
>>> im.run()
>>> for node in sorted(im.nodes, key=lambda n: n.state_id):
...     print(node.state_id, node.module_id, f"{node.flow:.2f}", node.node_id, node.layer_id)
11 1 0.28 1 1
21 1 0.28 2 1
22 2 0.22 2 2
32 2 0.22 3 2

Notes

Transforms non-int labels to unique int ids. Assumes that all nodes are of the same type. If node type is string, they are added as names to Infomap. If the NetworkX graph is directed (nx.DiGraph), and no flow model has been specified in the constructor, this method sets the directed flag to True.

Parameters:
  • g (nx.Graph) – A NetworkX graph.

  • weight (str, optional) – Key to look up link weight in edge data if present. Default "weight".

  • node_id (str, optional) – Node attribute for physical node ids, implying a state network.

  • layer_id (str, optional) – Node attribute for layer ids, implying a multilayer network.

  • multilayer_inter_intra_format (bool, optional) – Use intra/inter format to simulate inter-layer links. Default True.

Returns:

Dict with the internal node ids as keys and original labels as values.

Return type:

dict

add_node(node_id, name=None, teleportation_weight=None)

Add a node.

See also

set_name, add_nodes

Parameters:
  • node_id (int)

  • name (str, optional)

  • teleportation_weight (float, optional) – Used for teleporting between layers in multilayer networks.

add_nodes(nodes)

Add nodes.

See also

add_node

Examples

Add nodes

>>> from infomap import Infomap
>>> im = Infomap()
>>> im.add_nodes(range(4))

Add named nodes

>>> from infomap import Infomap
>>> im = Infomap()
>>> nodes = (
...     (1, "Node 1"),
...     (2, "Node 2"),
...     (3, "Node 3")
... )
>>> im.add_nodes(nodes)
>>> im.names
{1: 'Node 1', 2: 'Node 2', 3: 'Node 3'}

Add named nodes with teleportation weights

>>> from infomap import Infomap
>>> im = Infomap()
>>> nodes = (
...     (1, "Node 1", 0.5),
...     (2, "Node 2", 0.2),
...     (3, "Node 3", 0.8)
... )
>>> im.add_nodes(nodes)
>>> im.names
{1: 'Node 1', 2: 'Node 2', 3: 'Node 3'}

Add named nodes using dict

>>> from infomap import Infomap
>>> im = Infomap()
>>> nodes = {
...     1: "Node 1",
...     2: "Node 2",
...     3: "Node 3"
... }
>>> im.add_nodes(nodes)
>>> im.names
{1: 'Node 1', 2: 'Node 2', 3: 'Node 3'}

Add named nodes with teleportation weights using dict

>>> from infomap import Infomap
>>> im = Infomap()
>>> nodes = {
...     1: ("Node 1", 0.5),
...     2: ("Node 2", 0.2),
...     3: ("Node 3", 0.8)
... }
>>> im.add_nodes(nodes)
>>> im.names
{1: 'Node 1', 2: 'Node 2', 3: 'Node 3'}
Parameters:

nodes (iterable of tuples or iterable of int or dict of int: str or dict of int: tuple of (str, float)) – Iterable of tuples on the form (node_id, [name], [teleportation_weight])

add_scipy_sparse_matrix(A, directed=False, weighted=True, node_ids=None)

Add links and nodes from a SciPy sparse adjacency matrix.

Parameters:
  • A (scipy.sparse matrix or array) – Square sparse adjacency matrix.

  • directed (bool, optional) – Interpret A[i, j] as a directed edge from row i to column j. Default False.

  • weighted (bool, optional) – Use sparse matrix values as link weights. If False, every nonzero entry is treated as weight 1.0. Default True.

  • node_ids (sequence, optional) – External node ids in matrix row order. If omitted, 0..n-1 is used.

Returns:

Dict with internal integer node ids as keys and external node ids as values.

Return type:

dict

add_state_node(state_id, node_id)

Add a state node.

Notes

If a physical node with id node_id does not exist, it will be created. If you want to name the physical node, use set_name.

Parameters:
  • state_id (int)

  • node_id (int) – Id of the physical node the state node should be added to.

add_state_nodes(state_nodes)

Add state nodes.

See also

add_state_node

Examples

With tuples

>>> from infomap import Infomap
>>> im = Infomap()
>>> states = (
...     (1, 1),
...     (2, 1),
...     (3, 2)
... )
>>> im.add_state_nodes(states)

With dict

>>> from infomap import Infomap
>>> im = Infomap()
>>> states = {
...     1: 1,
...     2: 1,
...     3: 2
... }
>>> im.add_state_nodes(states)
Parameters:

state_nodes (iterable of tuples or dict of int: int) – Iterable of tuples of the form (state_id, node_id) or dict of the form {state_id: node_id}.

property bipartite_start_id

Get or set the bipartite start id.

Examples

>>> from infomap import Infomap
>>> im = Infomap(silent=True, num_trials=10)
>>> im.add_node(1, "Left 1")
>>> im.add_node(2, "Left 2")
>>> im.bipartite_start_id = 3
>>> im.add_node(3, "Right 3")
>>> im.add_node(4, "Right 4")
>>> im.add_link(1, 3)
>>> im.add_link(1, 4)
>>> im.add_link(2, 4)
>>> im.run()
>>> tol = 1e-4
>>> abs(im.codelength - 0.9182958340544896) < tol
True
Parameters:

start_id (int) – The node id where the second node type starts.

Returns:

The node id where the second node type starts.

Return type:

int

property codelength

Get the total (hierarchical) codelength.

See also

index_codelength, module_codelength

Returns:

The codelength

Return type:

float

property codelengths

Get the total (hierarchical) codelength for each trial.

See also

codelength

Returns:

The codelengths for each trial

Return type:

tuple of float

property elapsed_time

Get the elapsed run time in seconds.

Returns:

The elapsed run time in seconds.

Return type:

float

classmethod from_edge_index(edge_index, *, edge_weight=None, num_nodes=None, directed=True, node_ids=None, args=None, **infomap_options)

Create an Infomap instance from a PyG-style edge index.

classmethod from_options(options, args=None)

Create an Infomap instance from InfomapOptions.

classmethod from_scipy_sparse_matrix(A, *, directed=False, weighted=True, node_ids=None, args=None, **infomap_options)

Create an Infomap instance from a SciPy sparse adjacency matrix.

property initial_partition

Get or set the initial partition.

This is a initial configuration of nodes into modules where Infomap will start the optimizer.

Examples

>>> from infomap import Infomap
>>> im = Infomap(silent=True)
>>> im.add_node(1)
>>> im.add_node(2)
>>> im.add_node(3)
>>> im.add_node(4)
>>> im.add_link(1, 2)
>>> im.add_link(1, 3)
>>> im.add_link(2, 3)
>>> im.add_link(2, 4)
>>> im.initial_partition = {
...     1: 0,
...     2: 0,
...     3: 1,
...     4: 1
... }
>>> im.run(no_infomap=True)
>>> tol = 1e-4
>>> abs(im.codelength - 3.4056390622295662) < tol
True

Notes

The initial partition is saved between runs. If you want to use an initial partition for one run only, use run(initial_partition=partition).

Parameters:

module_ids (dict of int, or None) – Dict with node ids as keys and module ids as values.

Returns:

Dict with node ids as keys and module ids as values.

Return type:

dict of int

property network

Get the internal network.

read_file(filename, accumulate=True)

Read network data from file.

Parameters:
  • filename (str)

  • accumulate (bool, optional) – If the network data should be accumulated to already added nodes and links. Default True.

Remove a link.

Notes

Removing links will not remove nodes if they become disconnected.

See also

add_link

Parameters:
  • source_id (int)

  • target_id (int)

Remove several links.

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> links = (
...     (1, 2),
...     (1, 3)
... )
>>> im.add_links(links)
>>> im.remove_links(links)
>>> im.num_links
0

See also

remove_link

Parameters:

links (iterable of tuples) – Iterable of tuples of the form (source_id, target_id)

run(args=None, initial_partition=None, cluster_data=None, no_infomap=False, skip_adjust_bipartite_flow=False, bipartite_teleportation=False, weight_threshold=None, include_self_links=None, no_self_links=False, node_limit=None, matchable_multilayer_ids=None, assign_to_neighbouring_module=False, meta_data=None, meta_data_rate=1.0, meta_data_unweighted=False, tree=False, ftree=False, clu=False, verbosity_level=1, silent=False, pretty=False, out_name=None, no_file_output=False, clu_level=None, output=None, hide_bipartite_nodes=False, print_all_trials=False, two_level=False, flow_model=None, directed=None, recorded_teleportation=False, use_node_weights_as_flow=False, to_nodes=False, teleportation_probability=0.15, regularized=False, regularization_strength=1.0, entropy_corrected=False, entropy_correction_strength=1.0, markov_time=1.0, variable_markov_time=False, variable_markov_damping=1.0, variable_markov_min_scale=1.0, preferred_number_of_modules=None, multilayer_relax_rate=0.15, multilayer_relax_limit=-1, multilayer_relax_limit_up=-1, multilayer_relax_limit_down=-1, multilayer_relax_by_jsd=False, seed=123, num_trials=1, core_loop_limit=10, core_level_limit=None, tune_iteration_limit=None, core_loop_codelength_threshold=1e-10, tune_iteration_relative_threshold=1e-05, fast_hierarchical_solution=None, prefer_modular_solution=False, inner_parallelization=False, num_random_moves=None, max_degree_for_random_moves=None)

Run Infomap.

Keyword arguments mirror the Infomap CLI flags. Use InfomapOptions for the full parameter reference and run_with_options() when reusing a saved configuration.

Parameters:
  • args (str, optional) – Raw Infomap arguments to prepend before rendered keyword options.

  • initial_partition (dict, optional) – Initial partition to use for this run only. See initial_partition.

run_with_options(options, *, args=None, initial_partition=None)

Run Infomap using a reusable InfomapOptions instance.

set_meta_data(node_id, meta_category)

Set meta data to a node.

Examples

>>> from infomap import Infomap
>>> im = Infomap(silent=True, num_trials=10)
>>> im.add_links((
...     (1, 2), (1, 3), (2, 3),
...     (3, 4),
...     (4, 5), (4, 6), (5, 6)
... ))
>>> im.set_meta_data(1, 0)
>>> im.set_meta_data(2, 0)
>>> im.set_meta_data(3, 1)
>>> im.set_meta_data(4, 1)
>>> im.set_meta_data(5, 0)
>>> im.set_meta_data(6, 0)
>>> im.run(meta_data_rate=0)
>>> im.num_top_modules
2
>>> im.run(meta_data_rate=2)
>>> im.num_top_modules
3
Parameters:
  • node_id (int)

  • meta_category (int)

set_name(node_id, name)

Set the name of a node.

Parameters:
set_names(names)

Set names to several nodes at once.

Examples

With tuples

>>> from infomap import Infomap
>>> im = Infomap()
>>> names = (
...     (1, "Node 1"),
...     (2, "Node 2")
... )
>>> im.set_names(names)
>>> im.names
{1: 'Node 1', 2: 'Node 2'}

With dict

>>> from infomap import Infomap
>>> im = Infomap()
>>> names = {
...     1: "Node 1",
...     2: "Node 2"
... }
>>> im.set_names(names)
>>> im.names
{1: 'Node 1', 2: 'Node 2'}

See also

set_name, names

Parameters:

names (iterable of tuples or dict of int: str) – Iterable of tuples on the form (node_id, name) or dict of the form {node_id: name}.

summary()

Return a compact dictionary with network and result state.

Before run(), the summary contains loaded network counts and higher-order state-node information. After run(), it also includes module counts, codelength components, entropy rate, and elapsed time.