Infomap class¶
Infomap is the stateful entry point for the whole workflow: build a
network, run the search, then read the partition back. The typical usage is
four calls.
im = infomap.Infomap(num_trials=10, seed=42) # 1. configure
im.add_networkx_graph(graph) # 2. build
result = im.run() # 3. search
result.modules() # 4. read
Everything else on this page refines one of those four steps. The tables below group the members by purpose; the full reference, with signatures and docstrings, follows underneath.
Note
run() returns a Result; read metrics and modules from it. The
on-instance accessors below (get_modules, codelength, …) predate the
Result API and remain for backward compatibility. For one-shot use, prefer
infomap.run(); the stateful class is the way to build incrementally
and to write the native output files. See The stateful Infomap class.
Building a network¶
Most users need only one of the first group. The rest are for higher-order inputs and fine control.
From a graph library, matrix, or file (the common entry points):
|
Add a NetworkX graph. |
|
Add a python-igraph graph. |
|
Add links and nodes from a SciPy sparse adjacency matrix. |
|
Create an |
|
Add links and nodes from a PyG-style edge index. |
|
Create an |
|
Read network data from file. |
Links and nodes directly:
|
Add a link. |
|
Add several links. |
|
Add a node. |
|
Add nodes. |
|
Remove a link. |
|
Remove several links. |
Multilayer and state-node inputs:
|
Add a state node. |
|
Add state nodes. |
|
Add an intra-layer link. |
|
Add several intra-layer links. |
|
Add an inter-layer link. |
|
Add several inter-layer links. |
|
Add a multilayer link. |
|
Add several multilayer links. |
Names, metadata, and setup:
|
Set the name of a node. |
|
Set names to several nodes at once. |
|
Set meta data to a node. |
Get or set the bipartite start id. |
|
Get or set the initial partition. |
Running Infomap¶
|
Run Infomap. |
|
Run Infomap using a reusable |
|
Reading the partition¶
|
Get a dict with node ids as keys and module ids as values for a given depth in the hierarchical tree. |
A view of the top-level modules, mapping |
|
|
Get a dict with node ids as keys and a tuple of module ids as values. |
A view of the multilevel modules, mapping |
|
|
A view of the nodes in the hierarchical tree, iterating depth first from the root. |
A view of the nodes in the hierarchical tree, iterating depth first from the root. |
|
A view of the nodes in the hierarchical tree, iterating depth first from the root. |
|
A view of the leaf modules, i.e. the bottom modules containing leaf nodes. |
|
|
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes. |
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes. |
|
A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes. |
|
|
A view of the currently assigned links and their weights or flow. |
A view of the currently assigned links and their weights. |
|
A view of the currently assigned links and their flow. |
|
Get the internal network. |
|
|
Get a pandas-friendly DataFrame with Infomap results. |
|
Get a Pandas DataFrame with the selected columns. |
|
Get the name of a node. |
Get all node names. |
|
Get all node names. |
|
Get all state-node names. |
|
Get all state-node names. |
Solution metrics¶
Get the total (hierarchical) codelength. |
|
Get the total (hierarchical) codelength for each trial. |
|
Get the two-level index codelength. |
|
Get the total codelength of the modules. |
|
Get the meta codelength. |
|
Get the one-level codelength. |
|
Get the relative codelength savings. |
|
Get the number of top modules in the tree |
|
Get the number of leaf modules in the tree |
|
Get the number of non-trivial top modules in the tree |
|
Get the max depth of the hierarchical tree. |
|
Get the max depth of the hierarchical tree. |
|
The number of state nodes if we have a higher order network, or the number of physical nodes. |
|
The number of links. |
|
The number of physical nodes. |
|
The flow weighted effective number of top modules. |
|
The flow weighted effective number of leaf modules. |
|
|
The flow weighted effective number of modules. |
Get the entropy rate of the network. |
|
Get the meta entropy (unweighted by meta data rate). |
|
Returns true for multilayer and memory networks. |
|
Get the elapsed run time in seconds. |
|
|
Return a compact dictionary with network and result state. |
Writing output¶
|
Write results to file. |
|
Write result to a clu file. |
|
Write result to a tree file. |
|
Write result to a ftree file. |
|
Write internal state network to file. |
|
Write result to a JSON file. |
|
Write result to a Newick file. |
|
Write network to a Pajek file. |
|
Write result to a CSV file. |
Full reference¶
- class infomap.Infomap¶
The stateful entry point to the algorithm: build a network with the
add_*verbs, then callrun()to get an immutableResult. Internally it composes aNetwork(input) and anOptionsconfig over a singleCoreboundary to the SWIG-compiled engine, rather than exposing that engine directly. For one-shot use prefer the functionalinfomap.run(); for incremental construction preferNetwork.Examples
Build a network, run Infomap, and read the results off the returned
Result:>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.add_node(1) >>> im.add_node(2) >>> im.add_link(1, 2) >>> result = im.run() >>> result.codelength 1.0
Read a network file and inspect a few metrics on the result:
>>> from infomap import Infomap >>> im = Infomap(silent=True, num_trials=10) >>> im.read_file("ninetriangles.net") >>> result = im.run() >>> result.codelength 3.3858 >>> result.num_top_modules 3
Iterate the partition via
Result.modules()(node_id -> module_id) orResult.nodes()(per-node views):>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.add_links(((1, 2), (1, 3), (2, 3), (4, 5), (4, 6), (5, 6), (3, 4))) >>> result = im.run() >>> for node_id, module_id in sorted(result.modules().items()): ... print(node_id, module_id) 1 1 2 1 3 1 4 2 5 2 6 2
run()returns an immutableResult; read collections via methods (result.modules(),result.nodes(),result.tree(),result.links(),result.to_dataframe()) and scalars via properties (result.codelength,result.num_top_modules).For more examples, see the examples directory.
- 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.Deprecated since version Use:
Network.from_edge_index()orinfomap.run(edge_index).
- classmethod from_options(options, args=None)¶
Create an
Infomapinstance fromOptions.Deprecated since version Pass: options to
infomap.run()orInfomap.run()instead, e.g.infomap.run(graph, options=options).
- 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.Deprecated since version Use:
Network.from_scipy_sparse_matrix()orinfomap.run(matrix).
- __init__(args=None, include_self_links=None, skip_adjust_bipartite_flow=False, bipartite_teleportation=False, weight_threshold=None, no_self_links=False, node_limit=None, matchable_multilayer_ids=None, cluster_data=None, assign_to_neighbouring_module=False, meta_data=None, meta_data_rate=1.0, meta_data_unweighted=False, no_infomap=False, out_name=None, no_file_output=False, tree=False, ftree=False, clu=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, trial_offset=None, trial_results=None, no_final_output=False, verbosity_level=1, silent=False, pretty=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, preferred_number_of_levels=None, preferred_number_of_levels_strength=1.0, multilayer_relax_rate=0.15, multilayer_relax_limit=-1, multilayer_relax_limit_up=-1, multilayer_relax_limit_down=-1, multilayer_relax_by_jsd=False, multilayer_relax_to_self=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, inner_parallelization=False, parallel_trials=False, converge=False, num_threads=None, threads=None, prefer_modular_solution=False, num_random_moves=None, max_degree_for_random_moves=None)¶
Create a new Infomap instance.
Keyword arguments mirror the Infomap CLI flags. Use
Optionsfor a reusable configuration object and the full parameter reference.- Parameters:
args (str, optional) – Raw Infomap arguments to prepend before rendered keyword options.
include_self_links (bool, optional) – Deprecated. Self-links are included by default; use no_self_links=True to exclude them.
skip_adjust_bipartite_flow (bool, optional) – Keep flow on bipartite nodes instead of distributing it to primary nodes.
bipartite_teleportation (bool, optional) – Use bipartite teleportation instead of the default two-step unipartite teleportation.
weight_threshold (float, optional) – Ignore input links with weight below this threshold.
no_self_links (bool, optional) – Exclude self-links from the input network.
node_limit (int, optional) – Read only nodes up to this node id and ignore links connected to higher node ids.
matchable_multilayer_ids (int, optional) – Construct state ids from node ids and layer ids that stay comparable across networks. Set at least to the largest layer id among networks to match.
cluster_data (str, optional) – Read an initial partition from a clu file or a hierarchy from a tree/ftree file. Tree input may use physical or state nodes for higher-order networks.
assign_to_neighbouring_module (bool, optional) – With –cluster-data, assign nodes missing module ids to a neighboring node’s module when possible.
meta_data (str, optional) – Read metadata to encode from a clu-format file.
meta_data_rate (float, optional) – With –meta-data, set the metadata encoding rate. The default encodes metadata at each step.
meta_data_unweighted (bool, optional) – With –meta-data, encode metadata without weighting by node flow.
no_infomap (bool, optional) – Skip optimization. Use this to calculate codelength for –cluster-data or to print non-modular statistics.
out_name (str, optional) – Base name for output files, for example [out_directory]/[out-name].tree.
no_file_output (bool, optional) – Do not write output files.
tree (bool, optional) – Write the modular hierarchy to a tree file. Enabled by default when no other output format is selected.
ftree (bool, optional) – Write the modular hierarchy and aggregated links between nested modules to an ftree file. Used by Network Navigator.
clu (bool, optional) – Write top-level module ids for each node to a clu file.
clu_level (int, optional) – With –clu or –output clu, write module ids at this depth from the root. Use -1 for bottom-level modules.
output (sequence of str, optional) – Write selected output formats as a comma-separated list without spaces, e.g. -o clu,tree,ftree. Options: clu, tree, ftree, newick, json, csv, network, states, flow.
hide_bipartite_nodes (bool, optional) – Hide bipartite nodes in output by projecting the solution to primary nodes.
print_all_trials (bool, optional) – Write each trial to separate output files. Has effect only when –num-trials is greater than 1.
no_overwrite (bool, optional) – Fail with an output error if any target output file already exists. By default existing files are replaced.
print_config_fingerprint (bool, optional) – Print the canonical configuration fingerprint and exit.
timing_json (str, optional) – Write machine-readable run timing JSON to this path. Use - for stdout.
summary_json (str, optional) – Write machine-readable final run summary JSON to this path. Use - for stdout.
manifest_json (str, optional) – Write a machine-readable run manifest JSON to this path. Use - for stdout.
memory_report (bool, optional) – Include peak RSS and best-effort bytes per node/link estimates in timing JSON. Requires –timing-json.
trial_offset (int, optional) – Global index of the first trial this process runs; trial i uses seed = base_seed + (trial_offset + i). Default 0 (single-process behavior).
trial_results (str, optional) – Write this shard’s per-trial results (codelengths, seeds, best-tree reference, fingerprints) as JSON to this path, for deterministic merging of distributed shard runs into a final solution.
no_final_output (bool, optional) – Skip writing this process’s aggregate best result. Per-trial outputs and –trial-results are still written.
verbosity_level (int, optional) – Verbosity level on the console. 1 keeps the default output level, 2 renders -vv and so on.
silent (bool, optional) – Suppress console output.
pretty (bool, optional) – Deprecated. Accepted for backward compatibility; has no effect.
two_level (bool, optional) – Optimize a two-level partition instead of the default multi-level hierarchy.
flow_model (str, optional) – Choose how Infomap derives flow from the input links. Options: undirected, directed, undirdir, outdirdir, rawdir, precomputed.
directed (bool, optional) – Treat input links as directed. Shorthand for –flow-model directed.
recorded_teleportation (bool, optional) – When teleportation is used to calculate flow, also record teleportation steps in the codelength.
use_node_weights_as_flow (bool, optional) – Use node weights from the API or Pajek node records as normalized node flow.
to_nodes (bool, optional) – Teleport to nodes instead of links. Uses uniform node weights unless node weights are provided.
teleportation_probability (float, optional) – Set the probability of teleporting to a random node or link when calculating flow.
regularized (bool, optional) – Add a fully connected Bayesian prior network to reduce overfitting to missing links. Activates –recorded-teleportation.
regularization_strength (float, optional) – Scale the relative strength of the Bayesian prior network used by –regularized.
entropy_corrected (bool, optional) – Correct for negative entropy bias in small samples, especially solutions with many modules.
entropy_correction_strength (float, optional) – Scale the default correction used by –entropy-corrected.
markov_time (float, optional) – Scale link flow to change the cost of moving between modules. Higher values result in fewer modules.
variable_markov_time (bool, optional) – Vary Markov time locally to reduce overpartitioning in sparse areas while keeping higher resolution in dense areas.
variable_markov_damping (float, optional) – With –variable-markov-time, set damping between local effective degree (0) and local entropy (1).
variable_markov_min_scale (float, optional) – With –variable-markov-time, set the minimum local scale for zero-entropy nodes. Local Markov time is max scale divided by local scale.
preferred_number_of_modules (int, optional) – Penalize solutions by how far their number of modules differs from this value.
preferred_number_of_levels (int, optional) – Soft preference for the depth of the hierarchy. Steering to a shallower depth is reliable at a small codelength cost; deeper is best-effort, bounded by what the optimizer proposes. No-op with –two-level or strength 0.
preferred_number_of_levels_strength (float, optional) – Scale the strength of –preferred-number-of-levels. 0 disables the preference; larger values increase the cost of deviating from the preferred depth.
multilayer_relax_rate (float, optional) – Set the probability of relaxing from a state node to neighboring layers instead of staying in the current layer.
multilayer_relax_limit (int, optional) – Limit relaxation to this many neighboring layer ids in each direction. Use a negative value to allow relaxation to any layer.
multilayer_relax_limit_up (int, optional) – Limit relaxation upward to this many higher neighboring layer ids. Use a negative value to allow relaxation to any higher layer.
multilayer_relax_limit_down (int, optional) – Limit relaxation downward to this many lower neighboring layer ids. Use a negative value to allow relaxation to any lower layer.
multilayer_relax_by_jsd (bool, optional) – Weight multilayer relaxation by out-link similarity measured with Jensen-Shannon divergence.
multilayer_relax_to_self (bool, optional) – On relaxation, link a state node to its own physical node in the target layer instead of spreading to its out-neighbors. Builds a smaller state network with the same flow as the default.
seed (int, optional) – Set the random number generator seed for reproducible results.
num_trials (int, optional) – Run this many independent trials and keep the best solution.
core_loop_limit (int, optional) – Limit how many core loops try to move each node to the best module.
core_level_limit (int, optional) – Limit how many times core loops are reapplied to the aggregated modular network to find larger structures. 0 means no limit.
tune_iteration_limit (int, optional) – Limit the main iterations in the two-level partition algorithm. 0 means no limit.
core_loop_codelength_threshold (float, optional) – Require at least this codelength improvement to accept a new solution in a core loop.
tune_iteration_relative_threshold (float, optional) – Require each tune iteration to improve codelength by this fraction of the initial two-level codelength.
fast_hierarchical_solution (int, optional) – Find top modules fast. Use 2 to keep all fast levels and 3 to skip the recursive part.
inner_parallelization (bool, optional) – Experimental: use batched parallel node moves for coarse optimization. Performance gains are workload-dependent, often require a relaxed core-loop-codelength-threshold and low tune-iteration-limit, and may produce a different partition than serial optimization.
parallel_trials (bool, optional) – Run independent trials in parallel with OpenMP. –num-trials remains the total number of trials; the number of parallel workers follows the OpenMP thread count (e.g. OMP_NUM_THREADS), clamped to –num-trials. Peak memory scales with the worker count. Nested OpenMP and –inner-parallelization are disabled inside workers.
converge (bool, optional) – Treat the trial count as a cap and stop early once the best codelength has plateaued (no meaningful improvement over several consecutive trials). Runs trials serially; cannot be combined with parallel trials or distributed sharding. With no explicit trial count, a default cap is used.
num_threads (str, optional) – Effective thread budget: ‘auto’ (resolve from –num-threads > INFOMAP_NUM_THREADS > SLURM_CPUS_PER_TASK > OMP_NUM_THREADS > cpuset > hardware), or a positive integer. 1 forces fully serial. Governs the recursive partition, parallel trials, and inner parallelization.
threads (str, optional) – Alias for –num-threads.
prefer_modular_solution (bool, optional) – Prefer a modular solution even when one module gives a lower codelength.
num_random_moves (int, optional) – Try this many random moves in each core loop to merge weakly connected nodes.
max_degree_for_random_moves (int, optional) – Try random moves only for nodes with degree at most this value.
- 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:
Notes
Unlike the networkx/igraph adapters (which auto-detect directedness via
is_directed()), this adapter defaultsdirected=Trueand names its weight parameteredge_weight.add_scipy_sparse_matrix()instead defaultsdirected=False.Deprecated since version Use:
Network.from_edge_index()orinfomap.run(edge_index).
- add_igraph_graph(g, edge_weights=None, vertex_weights=None, node_id='node_id', layer_id='layer_id', meta_attribute=None, 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.meta_attribute (str, optional) – Vertex attribute to read categorical meta data from, for use with the meta-data map equation. Values are encoded to integers in first-seen order and set as Infomap meta data; vertices with missing values are skipped. Raises
ValueErrorif the attribute does not exist.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:
Notes
Directedness is auto-detected via
g.is_directed()(as for networkx). The graph-library adapters diverge on this: networkx and igraph auto-detect,add_scipy_sparse_matrix()defaultsdirected=False, andadd_edge_index()defaultsdirected=True. They also name their weight parameter differently: igraphedge_weights, networkxweight, scipyweighted(bool), edge_indexedge_weight.Deprecated since version Use:
Network.from_igraph()orinfomap.run(graph).
- 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, meta_attribute=None)¶
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'} >>> result = im.run() >>> for node in result.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'} >>> result = im.run() >>> for node in result.nodes(states=True): ... 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) >>> result = im.run() >>> for node in sorted(result.nodes(states=True), 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.meta_attribute (str, optional) – Node attribute to read categorical meta data from, for use with the meta-data map equation. Values are encoded to integers in first-seen order and set as Infomap meta data; nodes with missing values are skipped. Raises
ValueErrorif the attribute is not set on any node.
- Returns:
Dict with the internal node ids as keys and original labels as values.
- Return type:
Notes
Directedness is auto-detected via
g.is_directed()(see above). The graph-library adapters diverge on this: networkx and igraph auto-detect,add_scipy_sparse_matrix()defaultsdirected=False, andadd_edge_index()defaultsdirected=True. They also name their weight parameter differently: networkxweight, igraphedge_weights, scipyweighted(bool), edge_indexedge_weight.Parallel edges in an
nx.MultiGraph/nx.MultiDiGraphare each forwarded toadd_linkand self-loops are passed through.Deprecated since version Use:
Network.from_networkx()orinfomap.run(graph).
- 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:
Notes
Unlike the networkx/igraph adapters (which auto-detect directedness via
is_directed()), this adapter defaultsdirected=Falseand names its weight controlweighted(a bool).add_edge_index()instead defaultsdirected=True.Deprecated since version Use:
Network.from_scipy_sparse_matrix()orinfomap.run(matrix).
- 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}.
- get_dataframe(columns: Sequence[str] | None = None, *, states: bool = True, depth_level: int = 1) Any¶
Get a Pandas DataFrame with the selected columns.
Deprecated since version Use:
result = im.run(); result.to_dataframe(...).Examples
>>> from infomap import Infomap >>> im = Infomap(silent=True) >>> im.read_file("twotriangles.net") >>> _ = im.run() >>> im.get_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.get_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:
float – The effective number of modules
.. deprecated:: – Use
result = im.run(); result.effective_num_modules(depth).
- 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
- Parameters:
data (str) – The kind of data to return, one of
"weight"or"flow". Default"weight".- Returns:
tuple of int, int, float – An iterator of source, target, weight/flow tuples.
.. deprecated:: – Use
result = im.run(); result.links(data=data).
- 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 of int – Dict with node ids as keys and module ids as values.
.. deprecated:: – Use
result = im.run(); result.modules(depth, states=states).
- 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) (3, 8) (3, 8) (3, 8) (3, 9) (3, 9) (3, 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 of list of int – Dict with node ids as keys and tuple of module ids as values.
.. deprecated:: – Use
result = im.run(); result.multilevel_modules(states=states).
- 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:
dict of string – A dict with node ids as keys and node names as values.
.. deprecated:: – Use
result = im.run(); result.names.
- 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:
InfomapLeafIterator or InfomapIteratorPhysical – An iterator over each leaf node, depth first from the root
.. deprecated:: – Use
result = im.run(); result.nodes(depth, states=states).
- get_state_names()¶
Get all state-node names.
Populated for higher-order (state/memory) networks whose
*Statessection names the state nodes; empty otherwise. Physical node names are available separately viaget_names().See also
- Returns:
dict of string – A dict with state ids as keys and state-node names as values.
.. deprecated:: – Use
result = im.run(); result.state_names.
- 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:
InfomapIterator or InfomapIteratorPhysical – An iterator over each node in the tree, depth first from the root
.. deprecated:: – Use
result = im.run(); result.tree(depth, states=states).
- read_file(filename, accumulate=True)¶
Read network data from file.
- 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, include_self_links=None, skip_adjust_bipartite_flow=False, bipartite_teleportation=False, weight_threshold=None, no_self_links=False, node_limit=None, matchable_multilayer_ids=None, cluster_data=None, assign_to_neighbouring_module=False, meta_data=None, meta_data_rate=1.0, meta_data_unweighted=False, no_infomap=False, out_name=None, no_file_output=False, tree=False, ftree=False, clu=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, trial_offset=None, trial_results=None, no_final_output=False, verbosity_level=1, silent=False, pretty=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, preferred_number_of_levels=None, preferred_number_of_levels_strength=1.0, multilayer_relax_rate=0.15, multilayer_relax_limit=-1, multilayer_relax_limit_up=-1, multilayer_relax_limit_down=-1, multilayer_relax_by_jsd=False, multilayer_relax_to_self=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, inner_parallelization=False, parallel_trials=False, converge=False, num_threads=None, threads=None, prefer_modular_solution=False, num_random_moves=None, max_degree_for_random_moves=None)¶
Run Infomap.
Keyword arguments mirror the Infomap CLI flags. Use
Optionsfor the full parameter reference andinfomap.run()withoptions=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.
include_self_links (bool, optional) – Deprecated. Self-links are included by default; use no_self_links=True to exclude them.
skip_adjust_bipartite_flow (bool, optional) – Keep flow on bipartite nodes instead of distributing it to primary nodes.
bipartite_teleportation (bool, optional) – Use bipartite teleportation instead of the default two-step unipartite teleportation.
weight_threshold (float, optional) – Ignore input links with weight below this threshold.
no_self_links (bool, optional) – Exclude self-links from the input network.
node_limit (int, optional) – Read only nodes up to this node id and ignore links connected to higher node ids.
matchable_multilayer_ids (int, optional) – Construct state ids from node ids and layer ids that stay comparable across networks. Set at least to the largest layer id among networks to match.
cluster_data (str, optional) – Read an initial partition from a clu file or a hierarchy from a tree/ftree file. Tree input may use physical or state nodes for higher-order networks.
assign_to_neighbouring_module (bool, optional) – With –cluster-data, assign nodes missing module ids to a neighboring node’s module when possible.
meta_data (str, optional) – Read metadata to encode from a clu-format file.
meta_data_rate (float, optional) – With –meta-data, set the metadata encoding rate. The default encodes metadata at each step.
meta_data_unweighted (bool, optional) – With –meta-data, encode metadata without weighting by node flow.
no_infomap (bool, optional) – Skip optimization. Use this to calculate codelength for –cluster-data or to print non-modular statistics.
out_name (str, optional) – Base name for output files, for example [out_directory]/[out-name].tree.
no_file_output (bool, optional) – Do not write output files.
tree (bool, optional) – Write the modular hierarchy to a tree file. Enabled by default when no other output format is selected.
ftree (bool, optional) – Write the modular hierarchy and aggregated links between nested modules to an ftree file. Used by Network Navigator.
clu (bool, optional) – Write top-level module ids for each node to a clu file.
clu_level (int, optional) – With –clu or –output clu, write module ids at this depth from the root. Use -1 for bottom-level modules.
output (sequence of str, optional) – Write selected output formats as a comma-separated list without spaces, e.g. -o clu,tree,ftree. Options: clu, tree, ftree, newick, json, csv, network, states, flow.
hide_bipartite_nodes (bool, optional) – Hide bipartite nodes in output by projecting the solution to primary nodes.
print_all_trials (bool, optional) – Write each trial to separate output files. Has effect only when –num-trials is greater than 1.
no_overwrite (bool, optional) – Fail with an output error if any target output file already exists. By default existing files are replaced.
print_config_fingerprint (bool, optional) – Print the canonical configuration fingerprint and exit.
timing_json (str, optional) – Write machine-readable run timing JSON to this path. Use - for stdout.
summary_json (str, optional) – Write machine-readable final run summary JSON to this path. Use - for stdout.
manifest_json (str, optional) – Write a machine-readable run manifest JSON to this path. Use - for stdout.
memory_report (bool, optional) – Include peak RSS and best-effort bytes per node/link estimates in timing JSON. Requires –timing-json.
trial_offset (int, optional) – Global index of the first trial this process runs; trial i uses seed = base_seed + (trial_offset + i). Default 0 (single-process behavior).
trial_results (str, optional) – Write this shard’s per-trial results (codelengths, seeds, best-tree reference, fingerprints) as JSON to this path, for deterministic merging of distributed shard runs into a final solution.
no_final_output (bool, optional) – Skip writing this process’s aggregate best result. Per-trial outputs and –trial-results are still written.
verbosity_level (int, optional) – Verbosity level on the console. 1 keeps the default output level, 2 renders -vv and so on.
silent (bool, optional) – Suppress console output.
pretty (bool, optional) – Deprecated. Accepted for backward compatibility; has no effect.
two_level (bool, optional) – Optimize a two-level partition instead of the default multi-level hierarchy.
flow_model (str, optional) – Choose how Infomap derives flow from the input links. Options: undirected, directed, undirdir, outdirdir, rawdir, precomputed.
directed (bool, optional) – Treat input links as directed. Shorthand for –flow-model directed.
recorded_teleportation (bool, optional) – When teleportation is used to calculate flow, also record teleportation steps in the codelength.
use_node_weights_as_flow (bool, optional) – Use node weights from the API or Pajek node records as normalized node flow.
to_nodes (bool, optional) – Teleport to nodes instead of links. Uses uniform node weights unless node weights are provided.
teleportation_probability (float, optional) – Set the probability of teleporting to a random node or link when calculating flow.
regularized (bool, optional) – Add a fully connected Bayesian prior network to reduce overfitting to missing links. Activates –recorded-teleportation.
regularization_strength (float, optional) – Scale the relative strength of the Bayesian prior network used by –regularized.
entropy_corrected (bool, optional) – Correct for negative entropy bias in small samples, especially solutions with many modules.
entropy_correction_strength (float, optional) – Scale the default correction used by –entropy-corrected.
markov_time (float, optional) – Scale link flow to change the cost of moving between modules. Higher values result in fewer modules.
variable_markov_time (bool, optional) – Vary Markov time locally to reduce overpartitioning in sparse areas while keeping higher resolution in dense areas.
variable_markov_damping (float, optional) – With –variable-markov-time, set damping between local effective degree (0) and local entropy (1).
variable_markov_min_scale (float, optional) – With –variable-markov-time, set the minimum local scale for zero-entropy nodes. Local Markov time is max scale divided by local scale.
preferred_number_of_modules (int, optional) – Penalize solutions by how far their number of modules differs from this value.
preferred_number_of_levels (int, optional) – Soft preference for the depth of the hierarchy. Steering to a shallower depth is reliable at a small codelength cost; deeper is best-effort, bounded by what the optimizer proposes. No-op with –two-level or strength 0.
preferred_number_of_levels_strength (float, optional) – Scale the strength of –preferred-number-of-levels. 0 disables the preference; larger values increase the cost of deviating from the preferred depth.
multilayer_relax_rate (float, optional) – Set the probability of relaxing from a state node to neighboring layers instead of staying in the current layer.
multilayer_relax_limit (int, optional) – Limit relaxation to this many neighboring layer ids in each direction. Use a negative value to allow relaxation to any layer.
multilayer_relax_limit_up (int, optional) – Limit relaxation upward to this many higher neighboring layer ids. Use a negative value to allow relaxation to any higher layer.
multilayer_relax_limit_down (int, optional) – Limit relaxation downward to this many lower neighboring layer ids. Use a negative value to allow relaxation to any lower layer.
multilayer_relax_by_jsd (bool, optional) – Weight multilayer relaxation by out-link similarity measured with Jensen-Shannon divergence.
multilayer_relax_to_self (bool, optional) – On relaxation, link a state node to its own physical node in the target layer instead of spreading to its out-neighbors. Builds a smaller state network with the same flow as the default.
seed (int, optional) – Set the random number generator seed for reproducible results.
num_trials (int, optional) – Run this many independent trials and keep the best solution.
core_loop_limit (int, optional) – Limit how many core loops try to move each node to the best module.
core_level_limit (int, optional) – Limit how many times core loops are reapplied to the aggregated modular network to find larger structures. 0 means no limit.
tune_iteration_limit (int, optional) – Limit the main iterations in the two-level partition algorithm. 0 means no limit.
core_loop_codelength_threshold (float, optional) – Require at least this codelength improvement to accept a new solution in a core loop.
tune_iteration_relative_threshold (float, optional) – Require each tune iteration to improve codelength by this fraction of the initial two-level codelength.
fast_hierarchical_solution (int, optional) – Find top modules fast. Use 2 to keep all fast levels and 3 to skip the recursive part.
inner_parallelization (bool, optional) – Experimental: use batched parallel node moves for coarse optimization. Performance gains are workload-dependent, often require a relaxed core-loop-codelength-threshold and low tune-iteration-limit, and may produce a different partition than serial optimization.
parallel_trials (bool, optional) – Run independent trials in parallel with OpenMP. –num-trials remains the total number of trials; the number of parallel workers follows the OpenMP thread count (e.g. OMP_NUM_THREADS), clamped to –num-trials. Peak memory scales with the worker count. Nested OpenMP and –inner-parallelization are disabled inside workers.
converge (bool, optional) – Treat the trial count as a cap and stop early once the best codelength has plateaued (no meaningful improvement over several consecutive trials). Runs trials serially; cannot be combined with parallel trials or distributed sharding. With no explicit trial count, a default cap is used.
num_threads (str, optional) – Effective thread budget: ‘auto’ (resolve from –num-threads > INFOMAP_NUM_THREADS > SLURM_CPUS_PER_TASK > OMP_NUM_THREADS > cpuset > hardware), or a positive integer. 1 forces fully serial. Governs the recursive partition, parallel trials, and inner parallelization.
threads (str, optional) – Alias for –num-threads.
prefer_modular_solution (bool, optional) – Prefer a modular solution even when one module gives a lower codelength.
num_random_moves (int, optional) – Try this many random moves in each core loop to merge weakly connected nodes.
max_degree_for_random_moves (int, optional) – Try random moves only for nodes with degree at most this value.
- Returns:
The result of this run. See
Result.- Return type:
See also
- run_with_options(options, *, args=None, initial_partition=None)¶
Run Infomap using a reusable
Optionsinstance.Deprecated since version Use:
infomap.run(input, options=options)instead.
- 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) >>> result = im.run(meta_data_rate=0) >>> result.num_top_modules 2 >>> result = im.run(meta_data_rate=2) >>> result.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"."name"resolves the physical node name; the opt-in"state_name"resolves the per-state-node name for a higher-order network (falling back to the physical name, thennode_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.deprecated:: (..) – Use
result = im.run(); result.to_dataframe(...).
- 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
- 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) >>> result = im.run() >>> result.codelength 0.9183
- property codelength¶
Get the total (hierarchical) codelength.
See also
- Returns:
float – The codelength
.. deprecated:: – Use
result = im.run(); result.codelength.
- property codelengths¶
Get the total (hierarchical) codelength for each trial.
See also
- Returns:
tuple of float – The codelengths for each trial
.. deprecated:: – Use
result = im.run(); result.codelengths.
- property effective_num_leaf_modules¶
The flow weighted effective number of leaf modules.
Measured as the perplexity of the module flow distribution.
- Returns:
float – The effective number of top modules
.. deprecated:: – Use
result = im.run(); result.effective_num_leaf_modules.
- property effective_num_top_modules¶
The flow weighted effective number of top modules.
Measured as the perplexity of the module flow distribution.
- Returns:
float – The effective number of top modules
.. deprecated:: – Use
result = im.run(); result.effective_num_top_modules.
- property elapsed_time¶
Get the elapsed run time in seconds.
- Returns:
float – The elapsed run time in seconds.
.. deprecated:: – Use
result = im.run(); result.elapsed_time.
- 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:
float – The entropy rate
.. deprecated:: – Use
result = im.run(); result.entropy_rate.
- 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
- Returns:
tuple of int, int, float – An iterator of source, target, flow tuples.
.. deprecated:: – Use
result = im.run(); result.links(data="flow").
- property have_memory¶
Returns true for multilayer and memory networks.
- Returns:
bool – True if the network is a multilayer or memory network.
.. deprecated:: – Use
result = im.run(); result.have_memory.
- property index_codelength¶
Get the two-level index codelength.
See also
- Returns:
float – The two-level index codelength
.. deprecated:: – Use
result = im.run(); result.index_codelength.
- 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 ... } >>> result = im.run(no_infomap=True) >>> result.codelength 3.4056
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).For a multilayer network you can key the partition by physical identity instead of state ids, using
(layer_id, node_id)tuples (orMultilayerNode) as keys. The resolution to internally generated state ids is deferred until the network is built when you callrun().>>> from infomap import Infomap, MultilayerNode >>> im = Infomap(silent=True) >>> im.add_multilayer_intra_link(1, 1, 2) >>> im.add_multilayer_intra_link(2, 1, 3) >>> im.initial_partition = {(1, 1): 0, MultilayerNode(2, 1): 1}
- property leaf_modules¶
A view of the leaf modules, i.e. the bottom modules containing leaf nodes.
See also
- Returns:
InfomapLeafModuleIterator – An iterator over each leaf module in the tree, depth first from the root
.. deprecated:: – Use
result = im.run(); result.leaf_modules().
- 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
- Returns:
tuple of int, int, float – An iterator of source, target, weight tuples.
.. deprecated:: – Use
result = im.run(); result.links().
- property max_depth¶
Get the max depth of the hierarchical tree.
- Returns:
int – The max depth
.. deprecated:: – Use
result = im.run(); result.max_depth.
- property meta_codelength¶
Get the meta codelength.
This is the meta entropy times the meta data rate.
See also
- Returns:
float – The meta codelength
.. deprecated:: – Use
result = im.run(); result.meta_codelength.
- property meta_entropy¶
Get the meta entropy (unweighted by meta data rate).
See also
- Returns:
float – The meta entropy
.. deprecated:: – Use
result = im.run(); result.meta_entropy.
- 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:
float – The module codelength
.. deprecated:: – Use
result = im.run(); result.module_codelength.
- 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... deprecated:: – Use
result = im.run(); result.modules().
- 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... deprecated:: – Use
result = im.run(); result.multilevel_modules().
- property names¶
Get all node names.
Short-hand for
get_names.- Returns:
dict of string – A dict with node ids as keys and node names as values.
.. deprecated:: – Use
result = im.run(); result.names.
- 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:
InfomapLeafIterator – An iterator over each leaf node in the tree, depth first from the root
.. deprecated:: – Use
result = im.run(); result.nodes(states=True).
- property num_leaf_modules¶
Get the number of leaf modules in the tree
- Returns:
int – The number of leaf modules
.. deprecated:: – Use
result = im.run(); result.num_leaf_modules.
- property num_levels¶
Get the max depth of the hierarchical tree. Alias of
max_depth.See also
- Returns:
int – The max depth
.. deprecated:: – Use
result = im.run(); result.num_levels.
- 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:
int – The number of non-trivial top modules
.. deprecated:: – Use
result = im.run(); result.num_non_trivial_top_modules.
- 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:
int – The number of top modules
.. deprecated:: – Use
result = im.run(); result.num_top_modules.
- property one_level_codelength¶
Get the one-level codelength.
See also
- Returns:
float – The one-level codelength
.. deprecated:: – Use
result = im.run(); result.one_level_codelength.
- 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:
iterator – An iterator over each physical leaf node in the tree, depth first from the root (the concrete iterator type depends on whether the network has memory)
.. deprecated:: – Use
result = im.run(); result.nodes(states=False).
- 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:
iterator – An iterator over each physical node in the tree, depth first from the root (
InfomapIteratorPhysicalfor memory networks,InfomapIteratorfor first-order networks).. deprecated:: – Use
result = im.run(); result.tree(states=False).
- 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:
float – The relative codelength savings
.. deprecated:: – Use
result = im.run(); result.relative_codelength_savings.
- property state_names¶
Get all state-node names.
Short-hand for
get_state_names.See also
- Returns:
dict of string – A dict with state ids as keys and state-node names as values.
.. deprecated:: – Use
result = im.run(); result.state_names.
- 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:
InfomapIterator – An iterator over each node in the tree, depth first from the root
.. deprecated:: – Use
result = im.run(); result.tree(states=True).