Infomap class¶
- class infomap.Infomap¶
Bases:
_InfomapResultsMixin,_InfomapWritersMixin,InfomapWrapperThis 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, no_overwrite=False, print_config_fingerprint=False, timing_json=None, summary_json=None, manifest_json=None, memory_report=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, parallel_trials=False, num_threads=None, threads=None, trial_offset=None, trial_results=None, no_final_output=False, num_random_moves=None, max_degree_for_random_moves=None)¶
Create a new Infomap instance.
Keyword arguments mirror the Infomap CLI flags. Use
InfomapOptionsfor 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-1is used.
- Returns:
Dict with internal integer node ids as keys and external node ids as values.
- Return type:
- 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
namevertex attribute as Infomap node names when present, and treatsnode_id/layer_idvertex 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
Noneto treat every edge as weight 1. DefaultNone.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_idis 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:
- add_link(source_id, target_id, weight=1.0)¶
Add a link.
Notes
If the source or target nodes does not exist, they will be created.
See also
- add_links(links)¶
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
- 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_multilayer_inter_link(source_layer_id, node_id, target_layer_id, weight=1.0)¶
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)
- add_multilayer_inter_links(links)¶
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)
See also
- 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_multilayer_intra_link(layer_id, source_node_id, target_node_id, weight=1.0)¶
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.
- add_multilayer_intra_links(links)¶
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)
See also
- 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_multilayer_link(source_multilayer_node, target_multilayer_node, weight=1.0)¶
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_multilayer_links(links)¶
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)
See also
- 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 thedirectedflag toTrue.- 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:
- add_node(node_id, name=None, teleportation_weight=None)¶
Add a node.
- add_nodes(nodes)¶
Add nodes.
See also
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'}
- 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 rowito columnj. DefaultFalse.weighted (bool, optional) – Use sparse matrix values as link weights. If
False, every nonzero entry is treated as weight1.0. DefaultTrue.node_ids (sequence, optional) – External node ids in matrix row order. If omitted,
0..n-1is used.
- Returns:
Dict with internal integer node ids as keys and external node ids as values.
- Return type:
- 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.
- add_state_nodes(state_nodes)¶
Add state nodes.
See also
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
- property codelength¶
Get the total (hierarchical) codelength.
See also
- Returns:
The codelength
- Return type:
- property codelengths¶
Get the total (hierarchical) codelength for each trial.
See also
- property effective_num_leaf_modules¶
The flow weighted effective number of leaf modules.
Measured as the perplexity of the module flow distribution.
- Returns:
The effective number of top modules
- Return type:
- property effective_num_top_modules¶
The flow weighted effective number of top modules.
Measured as the perplexity of the module flow distribution.
- Returns:
The effective number of top modules
- Return type:
- property elapsed_time¶
Get the elapsed run time in seconds.
- Returns:
The elapsed run time in seconds.
- Return type:
- property entropy_rate¶
Get the entropy rate of the network.
The entropy rate is an indication of the sparsity of a network. A higher entropy rate corresponds to a densely connected network.
Notes
This value is only accessible after running the optimizer (
im.run()).Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True, no_infomap=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> f"{im.entropy_rate:.5f}" '1.25070'
- Returns:
The entropy rate
- Return type:
- property flow_links¶
A view of the currently assigned links and their flow.
The sources and targets are state ids when we have a state or multilayer network.
Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> for link in im.flow_links: ... print(link) (1, 2, 0.14285714285714285) (1, 3, 0.14285714285714285) (2, 3, 0.14285714285714285) (3, 4, 0.14285714285714285) (4, 5, 0.14285714285714285) (4, 6, 0.14285714285714285) (5, 6, 0.14285714285714285)
See also
- classmethod from_edge_index(edge_index, *, edge_weight=None, num_nodes=None, directed=True, node_ids=None, args=None, **infomap_options)¶
Create an
Infomapinstance from a PyG-style edge index.
- classmethod from_options(options, args=None)¶
Create an
Infomapinstance fromInfomapOptions.
- classmethod from_scipy_sparse_matrix(A, *, directed=False, weighted=True, node_ids=None, args=None, **infomap_options)¶
Create an
Infomapinstance from a SciPy sparse adjacency matrix.
- get_dataframe(columns: Sequence[str] | None = None, *, states: bool = True, depth_level: int = 1) Any¶
Get a Pandas DataFrame with the selected columns.
Deprecated. Use
to_dataframe()for dataframe exports.Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> im.to_dataframe(columns=["path", "flow", "name", "node_id"], states=True) path flow name node_id 0 (1, 1) 0.214286 C 3 1 (1, 2) 0.142857 A 1 2 (1, 3) 0.142857 B 2 3 (2, 1) 0.214286 D 4 4 (2, 2) 0.142857 E 5 5 (2, 3) 0.142857 F 6 >>> im.to_dataframe(columns=["node_id", "module_id"], states=True) node_id module_id 0 3 1 1 1 1 2 2 1 3 4 2 4 5 2 5 6 2
- Parameters:
columns (list(str), optional) – A list of columns that should be extracted from each node. Must be available as an attribute of
InfoNode,InfomapLeafIterator(for state nodes), orInfomapLeafIteratorPhysical. One exception to this is"name"which is looked up internally. Default["path", "flow", "name", "node_id"].states (bool, optional) – Use state-node iterators when
Trueand physical-node iterators whenFalse. DefaultTrue.depth_level (int, optional) – Depth level passed to
get_nodes(). Default1.
- Raises:
ImportError – If the pandas package is not available. Install it with
python -m pip install "infomap[pandas]".AttributeError – If a column name is not available as an
InfoNodeattribute.
- Returns:
A DataFrame containing the selected columns.
- Return type:
- get_effective_num_modules(depth_level=1)¶
The flow weighted effective number of modules.
Measured as the perplexity of the module flow distribution.
- Parameters:
depth_level (int, optional) – The module level returned by
iterator.depth. Set to1(default) to return the top modules (coarsest level). Set to2for second coarsest level etc. Set to-1to return the bottom level modules (finest level).- Returns:
The effective number of modules
- Return type:
- get_links(data='weight')¶
A view of the currently assigned links and their weights or flow.
The sources and targets are state ids when we have a state or multilayer network.
Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> for link in im.get_links(): ... print(link) (1, 2, 1.0) (1, 3, 1.0) (2, 3, 1.0) (3, 4, 1.0) (4, 5, 1.0) (4, 6, 1.0) (5, 6, 1.0) >>> for link in im.get_links(data="flow"): ... print(link) (1, 2, 0.14285714285714285) (1, 3, 0.14285714285714285) (2, 3, 0.14285714285714285) (3, 4, 0.14285714285714285) (4, 5, 0.14285714285714285) (4, 6, 0.14285714285714285) (5, 6, 0.14285714285714285)
See also
- get_modules(depth_level=1, states=False)¶
Get a dict with node ids as keys and module ids as values for a given depth in the hierarchical tree.
Level Root 0 ┌─┐ ┌─────────┴─┴────────┐ │ │ │ │ │ │ Path │ Module Path │ Module 1 1 ┌┼┐ 1 2 ┌┼┐ 2 ┌───┴─┴───┐ ┌───┴─┴───┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ 2 1 ┌┼┐ 1 2 ┌┼┐ 2 1 ┌┼┐ 3 2 ┌┼┐ 3 ┌───┴─┴───┐ └─┴────┐ └─┘ └─┘ │ │ │ │ │ │ ▲ ▲ │ │ │ └────┬────┘ │ │ │ │ 3 1 ┌┼┐ 2 ┌┼┐ 1 ┌┼┐ └─┘ └─┘ └─┘ ◄─── Leaf-nodesPath to the left of the nodes. Depth dependent module ids to the right. The five leaf-nodes are network-nodes. All other tree-nodes are modules.
For example:
The left-most node on level 3 has path 1:1:1 and belong to module 1 on level 1.
The right-most node on level 2 has path 2:2 and belong to module 2 on level 1 which is renamed to module 3 on level 2 as we have more modules in total on this level.
Assuming the nodes are labelled 1-5 from left to right, then the first three nodes are in module 1, and the last two nodes are in module 2:
> im.get_modules(depth_level=1) {1: 1, 2: 1, 3: 1, 4: 2, 5: 2}
However, at level 2, the first two nodes are in module 1, the third node in module 2, and the last two nodes are in module 3:
> im.get_modules(depth_level=2) {1: 1, 2: 1, 3: 2, 4: 3, 5: 3}
Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> im.get_modules() {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2}
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("states.net") >>> im.run() >>> im.get_modules(states=True) {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2}
Notes
In a higher-order network, a physical node (defined by
node_id) may partially exist in multiple modules. However, thenode_idcan not exist multiple times as a key in the node-to-module map, so only one occurrence of a physical node will be retrieved. To get all states, useget_modules(states=True).- Parameters:
depth_level (int, optional) – The level in the hierarchical tree. Set to
1(default) to return the top modules (coarsest level). Set to2for second coarsest level etc. Set to-1to return the bottom level modules (finest level). Default1.states (bool, optional) – For higher-order networks, if
statesis True, it will return state node ids. Otherwise it will return physical node ids, merging state nodes with samenode_idif they are in the same module. Note that the same physical node may end up on different paths in the tree. Defaultfalse.
- Returns:
Dict with node ids as keys and module ids as values.
- Return type:
- get_multilevel_modules(states=False)¶
Get a dict with node ids as keys and a tuple of module ids as values. Each position in the tuple corresponds to a depth in the hierarchical tree, with the first level being the top level.
See also
Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True, num_trials=10) >>> im.read_file("ninetriangles.net") >>> im.run() >>> for modules in sorted(im.get_multilevel_modules().values()): ... print(modules) (1, 1) (1, 1) (1, 1) (1, 2) (1, 2) (1, 2) (1, 3) (1, 3) (1, 3) (2, 4) (2, 4) (2, 4) (2, 5) (2, 5) (2, 5) (2, 6) (2, 6) (2, 6) (3, 7) (3, 7) (3, 7) (4, 8) (4, 8) (4, 8) (5, 9) (5, 9) (5, 9)
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("states.net") >>> im.run() >>> for node, modules in im.get_multilevel_modules(states=True).items(): ... print(node, modules) 1 (1,) 2 (1,) 3 (1,) 4 (2,) 5 (2,) 6 (2,)
Notes
In a higher-order network, a physical node (defined by
node_id) may partially exist in multiple modules. However, thenode_idcan not exist multiple times as a key in the node-to-module map, so only one occurrence of a physical node will be retrieved. To get all states, useget_multilevel_modules(states=True).- Parameters:
states (bool, optional) – For higher-order networks, if
statesis True, it will return state node ids. Otherwise it will return physical node ids, merging state nodes with samenode_idif they are in the same module. Note that the same physical node may end up on different paths in the tree. Defaultfalse.- Returns:
Dict with node ids as keys and tuple of module ids as values.
- Return type:
- get_name(node_id, default=None)¶
Get the name of a node.
Notes
If the node name is an empty string, the
defaultwill be returned.
- get_names()¶
Get all node names.
- Returns:
A dict with node ids as keys and node names as values.
- Return type:
dict of string
- get_nodes(depth_level=1, states=False)¶
A view of the nodes in the hierarchical tree, iterating depth first from the root.
- Parameters:
depth_level (int, optional) – The module level returned by
iterator.module_id. Set to1(default) to return the top modules (coarsest level). Set to2for second coarsest level etc. Set to-1to return the bottom level modules (finest level). Default1.states (bool, optional) – For higher-order networks, if
statesis True, it will iterate over state nodes. Otherwise it will iterate over physical nodes, merging state nodes with samenode_idif they are in the same module. Note that the same physical node may end up on different paths in the tree. See notes onphysical_tree. Defaultfalse.
Notes
For higher-order networks, each node is represented by a set of state nodes with the same
node_id, where each state node represents a different constraint on the random walker. This enables overlapping modules, where state nodes with the samenode_idend up in different modules. However, the state nodes with the samenode_idwithin each module are only visible as one (partial) physical node (ifstates = False).- Returns:
An iterator over each node in the tree, depth first from the root
- Return type:
- get_tree(depth_level=1, states=False)¶
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes.
- Parameters:
depth_level (int, optional) – The module level returned by
iterator.module_id. Set to1(default) to return the top modules (coarsest level). Set to2for second coarsest level etc. Set to-1to return the bottom level modules (finest level).states (bool, optional) – For higher-order networks, if
statesis True, it will iterate over state nodes. Otherwise it will iterate over physical nodes, merging state nodes with samenode_idif they are in the same module. Note that the same physical node may end up on different paths in the tree. Defaultfalse.
Notes
For higher-order networks, each node is represented by a set of state nodes with the same
node_id, where each state node represents a different constraint on the random walker. This enables overlapping modules, where state nodes with the samenode_idend up in different modules. However, the state nodes with the samenode_idwithin each module are only visible as one (partial) physical node (ifstates = False).- Returns:
An iterator over each node in the tree, depth first from the root
- Return type:
- property have_memory¶
Returns true for multilayer and memory networks.
- Returns:
True if the network is a multilayer or memory network.
- Return type:
- property index_codelength¶
Get the two-level index codelength.
See also
- Returns:
The two-level index codelength
- Return type:
- 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).
- property leaf_modules¶
A view of the leaf modules, i.e. the bottom modules containing leaf nodes.
See also
- Returns:
An iterator over each leaf module in the tree, depth first from the root
- Return type:
- property links¶
A view of the currently assigned links and their weights.
The sources and targets are state ids when we have a state or multilayer network.
Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> im.run() >>> for link in im.links: ... print(link) (1, 2, 1.0) (1, 3, 1.0) (2, 3, 1.0) (3, 4, 1.0) (4, 5, 1.0) (4, 6, 1.0) (5, 6, 1.0)
See also
- property max_depth¶
Get the max depth of the hierarchical tree.
- Returns:
The max depth
- Return type:
- property meta_codelength¶
Get the meta codelength.
This is the meta entropy times the meta data rate.
See also
- Returns:
The meta codelength
- Return type:
- property meta_entropy¶
Get the meta entropy (unweighted by meta data rate).
See also
- Returns:
The meta entropy
- Return type:
- property module_codelength¶
Get the total codelength of the modules.
The module codelength is defined such that
codelength = index_codelength + module_codelengthFor a hierarchical solution, the module codelength is the sum of codelengths for each top module.
See also
- Returns:
The module codelength
- Return type:
- property modules¶
A view of the top-level modules, mapping
node_idtomodule_id.Notes
In a higher-order network, a physical node (defined by
node_id) may partially exist in multiple modules. However, thenode_idcan not exist multiple times as a key in the node-to-module map, so only one occurrence of a physical node will be retrieved. To get all states, useget_modules(states=True).Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True, num_trials=5) >>> im.read_file("twotriangles.net") >>> im.run() >>> for node_id, module_id in im.modules: ... print(node_id, module_id) ... 1 1 2 1 3 1 4 2 5 2 6 2
See also
- Yields:
tuple of int, int – An iterator of
(node_id, module_id)pairs.
- property multilevel_modules¶
A view of the multilevel modules, mapping
node_idto a tuple ofmodule_id.Notes
In a higher-order network, a physical node (defined by
node_id) may partially exist in multiple modules. However, thenode_idcan not exist multiple times as a key in the node-to-module map, so only one occurrence of a physical node will be retrieved. To get all states, useget_multilevel_modules(states=True).See also
- Yields:
tuple of (int, tuple of int) – An iterator of
(node_id, (module_ids...)pairs.
- property names¶
Get all node names.
Short-hand for
get_names.- Returns:
A dict with node ids as keys and node names as values.
- Return type:
dict of string
- property network¶
Get the internal network.
- property nodes¶
A view of the nodes in the hierarchical tree, iterating depth first from the root.
Convenience method for
get_nodes(depth_level=1, states=True).See also
- Returns:
An iterator over each leaf node in the tree, depth first from the root
- Return type:
- property num_leaf_modules¶
Get the number of leaf modules in the tree
- Returns:
The number of leaf modules
- Return type:
- property num_levels¶
Get the max depth of the hierarchical tree. Alias of
max_depth.See also
- Returns:
The max depth
- Return type:
- property num_nodes¶
The number of state nodes if we have a higher order network, or the number of physical nodes.
See also
- Returns:
The number of nodes
- Return type:
- property num_non_trivial_top_modules¶
Get the number of non-trivial top modules in the tree
A trivial module is a module with either one or all nodes within.
- Returns:
The number of non-trivial top modules
- Return type:
- property num_physical_nodes¶
The number of physical nodes.
See also
- Returns:
The number of nodes
- Return type:
- property num_top_modules¶
Get the number of top modules in the tree
- Returns:
The number of top modules
- Return type:
- property one_level_codelength¶
Get the one-level codelength.
See also
- Returns:
The one-level codelength
- Return type:
- property physical_nodes¶
A view of the nodes in the hierarchical tree, iterating depth first from the root. All state nodes with the same
node_idare merged to one physical node.Convenience method for
get_nodes(depth_level=1, states=False).See also
- Returns:
An iterator over each physical leaf node in the tree, depth first from the root
- Return type:
- property physical_tree¶
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes. All state nodes with the same
node_idare merged to one physical node.Convenience method for
get_tree(depth_level=1, states=False).See also
- Returns:
An iterator over each physical node in the tree, depth first from the root
- Return type:
- read_file(filename, accumulate=True)¶
Read network data from file.
- property relative_codelength_savings¶
Get the relative codelength savings.
This is defined as the reduction in codelength relative to the non-modular one-level solution:
S_L = 1 - L / L_1
where
Lis thecodelengthandL_1theone_level_codelength.See also
- Returns:
The relative codelength savings
- Return type:
- remove_link(source_id, target_id)¶
Remove a link.
Notes
Removing links will not remove nodes if they become disconnected.
See also
- remove_links(links)¶
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
- 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, no_overwrite=False, print_config_fingerprint=False, timing_json=None, summary_json=None, manifest_json=None, memory_report=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, parallel_trials=False, num_threads=None, threads=None, trial_offset=None, trial_results=None, no_final_output=False, num_random_moves=None, max_degree_for_random_moves=None)¶
Run Infomap.
Keyword arguments mirror the Infomap CLI flags. Use
InfomapOptionsfor the full parameter reference andrun_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.
See also
- run_with_options(options, *, args=None, initial_partition=None)¶
Run Infomap using a reusable
InfomapOptionsinstance.
- 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
- 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'}
- 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. Afterrun(), it also includes module counts, codelength components, entropy rate, and elapsed time.
- to_dataframe(columns: Sequence[str] | None = None, *, states: bool = False, level: int = 1, index: str | bool | None = None, sort: bool | str | Sequence[str] = False, depth_level: int | None = None) Any¶
Get a pandas-friendly DataFrame with Infomap results.
Compared with
get_dataframe(), this method defaults to physical nodes and includesmodule_idfor analysis workflows.- Parameters:
columns (sequence of str, optional) – Columns to include.
"community"is accepted as an alias for"module_id". Default["node_id", "module_id", "flow", "path", "name"].states (bool, optional) – Use state-node iterators when
Trueand physical-node iterators whenFalse. DefaultFalse.level (int, optional) – Depth level passed to
get_nodes(). Default1.index (str, bool, or None, optional) – Column to set as the DataFrame index. Use
FalseorNoneto keep the default RangeIndex.sort (bool, str, or sequence of str, optional) – Sort by one or more columns. Use
Trueto sort by["module_id", "node_id"]when available. DefaultFalse.depth_level (int, optional) – Backward-compatible alias for
level.
- property tree¶
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes.
Convenience method for
get_tree(depth_level=1, states=True).See also
- Returns:
An iterator over each node in the tree, depth first from the root
- Return type:
- write(filename, *args, **kwargs)¶
Write results to file.
- Raises:
NotImplementedError – If the file format is not supported.
- Parameters:
filename (str) – The filename.
- write_clu(filename, states=False, depth_level=1)¶
Write result to a clu file.
See also
- write_csv(filename, states=False)¶
Write result to a CSV file.
See also
- write_flow_tree(filename, states=False)¶
Write result to a ftree file.
See also
- write_json(filename, states=False)¶
Write result to a JSON file.
See also
- write_newick(filename, states=False)¶
Write result to a Newick file.
See also
- write_pajek(filename, flow=False)¶
Write network to a Pajek file.
See also
- write_state_network(filename)¶
Write internal state network to file.
See also
- Parameters:
filename (str)
- write_tree(filename, states=False)¶
Write result to a tree file.
See also