Infomap class

Infomap is the stateful entry point for the whole workflow: build a network, run the search, then read the partition back. Its remaining strength is building a network incrementally, one link at a time:

im = infomap.Infomap(num_trials=10, seed=42)  # 1. configure
im.add_link(0, 1)                             # 2. build incrementally
im.add_link(1, 2)
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 result accessors below (get_modules, modules, codelength, …) are deprecated and leave in 3.0 – read the equivalently named members off the returned Result instead. Mind the shape shift: im.modules is a property, while result.modules() is a method. These accessors emit a silent-by-default PendingDeprecationWarning (surface it with -W); see The stateful Infomap class for the full migration table. For one-shot use, prefer infomap.run(); the stateful class remains the way to build incrementally and to write the native output files.

Building a network

The graph-library and matrix adapters below are deprecated; load graphs with infomap.run() or the Network from_* classmethods instead (see the note above). Only read_file(), which reads a native network file, is current.

read_file(filename[, accumulate])

Read network data from file.

add_networkx_graph(g[, weight, node_id, ...])

Add a NetworkX graph.

add_igraph_graph(g[, edge_weights, ...])

Add a python-igraph graph.

add_scipy_sparse_matrix(A[, directed, ...])

Add links and nodes from a SciPy sparse adjacency matrix.

from_scipy_sparse_matrix(A, *[, directed, ...])

Create an Infomap instance from a SciPy sparse adjacency matrix.

add_edge_index(edge_index[, edge_weight, ...])

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

from_edge_index(edge_index, *[, ...])

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

Links and nodes directly:

add_link(source_id, target_id[, weight])

Add a link.

add_links(links)

Add several links.

add_node(node_id[, name, teleportation_weight])

Add a node.

add_nodes(nodes)

Add nodes.

remove_link(source_id, target_id)

Remove a link.

remove_links(links)

Remove several links.

Multilayer and state-node inputs:

add_state_node(state_id, node_id[, name])

Add a state node.

add_state_nodes(state_nodes)

Add state nodes.

add_multilayer_intra_link(layer_id, ...[, ...])

Add an intra-layer link.

add_multilayer_intra_links(links)

Add several intra-layer links.

add_multilayer_inter_link(source_layer_id, ...)

Add an inter-layer link.

add_multilayer_inter_links(links)

Add several inter-layer links.

add_multilayer_link(source_multilayer_node, ...)

Add a multilayer link.

add_multilayer_links(links)

Add several multilayer links.

Names, metadata, and setup:

set_name(node_id, name)

Set the name of a node.

set_names(names)

Set names to several nodes at once.

set_meta_data(node_id[, meta_category])

Set integer metadata for one node, or for many at once.

bipartite_start_id

Get or set the bipartite start id.

initial_partition

Get or set the initial partition.

Running Infomap

run([args, initial_partition, ...])

Run Infomap.

run_with_options(options, *[, args, ...])

Run Infomap using a reusable Options instance.

from_options(options[, args])

Create an Infomap instance from Options.

Reading the partition

Except for network, these accessors mirror the Result API and are deprecated (they leave in 3.0). Read them off the Result that run() returns – e.g. result.modules() rather than im.get_modules().

get_modules([depth_level, states])

Get a dict with node ids as keys and module ids as values for a given depth in the hierarchical tree.

modules

A view of the top-level modules, mapping node_id to module_id.

get_multilevel_modules([states])

Get a dict with node ids as keys and a tuple of module ids as values.

multilevel_modules

A view of the multilevel modules, mapping node_id to a tuple of module_id.

get_nodes([depth_level, states])

A view of the nodes in the hierarchical tree, iterating depth first from the root.

nodes

A view of the nodes in the hierarchical tree, iterating depth first from the root.

physical_nodes

A view of the nodes in the hierarchical tree, iterating depth first from the root.

leaf_modules

A view of the leaf modules, i.e. the bottom modules containing leaf nodes.

get_tree([depth_level, states])

A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes.

tree

A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes.

physical_tree

A view of the hierarchical tree, iterating over the modules as well as the leaf-nodes.

get_links([data])

A view of the currently assigned links and their weights or flow.

links

A view of the currently assigned links and their weights.

flow_links

A view of the currently assigned links and their flow.

network

Get the internal network.

to_dataframe([columns, states, level, ...])

Get a pandas-friendly DataFrame with Infomap results.

get_dataframe([columns, states, depth_level])

Get a Pandas DataFrame with the selected columns.

get_name(node_id[, default])

Get the name of a node.

get_names()

Get all node names.

names

Get all node names.

state_names

Get all state-node names.

get_state_names()

Get all state-node names.

Solution metrics

Most of these metrics are also available (and preferred) on the Result that run() returns; those on-instance copies are deprecated and leave in 3.0.

codelength

Get the total (hierarchical) codelength.

codelengths

Get the total (hierarchical) codelength for each trial.

index_codelength

Get the two-level index codelength.

module_codelength

Get the total codelength of the modules.

meta_codelength

Get the meta codelength.

one_level_codelength

Get the one-level codelength.

relative_codelength_savings

Get the relative codelength savings.

num_top_modules

Get the number of top modules in the tree

num_leaf_modules

Get the number of leaf modules in the tree

num_non_trivial_top_modules

Get the number of non-trivial top modules in the tree

num_levels

Get the max depth of the hierarchical tree.

max_depth

Get the max depth of the hierarchical tree.

num_nodes

The number of state nodes if we have a higher order network, or the number of physical nodes.

num_links

The number of links.

num_physical_nodes

The number of physical nodes.

effective_num_top_modules

The flow weighted effective number of top modules.

effective_num_leaf_modules

The flow weighted effective number of leaf modules.

get_effective_num_modules([depth_level])

The flow weighted effective number of modules.

entropy_rate

Get the entropy rate of the network.

meta_entropy

Get the meta entropy (unweighted by metadata rate).

have_memory

Returns true for multilayer and memory networks.

elapsed_time

Get the elapsed run time in seconds.

summary()

Return a compact dictionary describing this instance's state.

Writing output

write(filename, *args, **kwargs)

Write results to file, inferring the format from the extension.

write_clu(filename[, states, depth, depth_level])

Write result to a clu file.

write_tree(filename[, states])

Write result to a tree file.

write_flow_tree(filename[, states])

Write result to a ftree file.

write_state_network(filename)

Write internal state network to file.

write_json(filename[, states])

Write result to a JSON file.

write_newick(filename[, states])

Write result to a Newick file.

write_pajek(filename[, flow])

Write network to a Pajek file.

write_csv(filename[, states])

Write result to a CSV file.

Full reference

Attention

Many members below are the deprecated on-instance result accessors (get_modules, modules, codelength, to_dataframe, …), and their example bodies show the legacy im.<accessor> form for reference only. In new code, read these off the Result that run() returns instead (see the note at the top of this page for the shape shift and the migration table).

class infomap.Infomap(args: str | None = None, include_self_links: bool | None = None, skip_adjust_bipartite_flow: bool = False, bipartite_teleportation: bool = False, weight_threshold: float | None = None, no_self_links: bool = False, node_limit: int | None = None, matchable_multilayer_ids: int | None = None, cluster_data: str | None = None, assign_to_neighbouring_module: bool = False, meta_data: str | None = None, meta_data_rate: float = 1.0, meta_data_unweighted: bool = False, no_infomap: bool = False, out_name: str | None = None, no_file_output: bool = False, tree: bool = False, ftree: bool = False, clu: bool = False, clu_level: int | None = None, output: list[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow']] | tuple[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow'], ...] | None = None, hide_bipartite_nodes: bool = False, print_all_trials: bool = False, no_overwrite: bool = False, print_config_fingerprint: bool = False, timing_json: str | None = None, summary_json: str | None = None, manifest_json: str | None = None, memory_report: bool = False, trial_offset: int | None = None, trial_results: str | None = None, no_final_output: bool = False, verbosity_level: int = 1, silent: bool = True, pretty: bool | None = None, two_level: bool = False, flow_model: Literal['undirected', 'directed', 'undirdir', 'outdirdir', 'rawdir', 'precomputed'] | None = None, directed: bool | None = None, recorded_teleportation: bool = False, use_node_weights_as_flow: bool = False, to_nodes: bool = False, teleportation_probability: float = 0.15, max_flow_iterations: int = 400, min_flow_iterations: int = 50, flow_tolerance: float = 1e-15, regularized: bool = False, regularization_strength: float = 1.0, entropy_corrected: bool = False, entropy_correction_strength: float = 1.0, markov_time: float = 1.0, variable_markov_time: bool = False, variable_markov_damping: float = 1.0, variable_markov_min_scale: float = 1.0, preferred_number_of_modules: int | None = None, preferred_number_of_levels: int | None = None, preferred_number_of_levels_strength: float = 1.0, multilayer_relax_rate: float = 0.15, multilayer_relax_limit: int = -1, multilayer_relax_limit_up: int = -1, multilayer_relax_limit_down: int = -1, multilayer_relax_by_jsd: bool = False, multilayer_relax_to_self: bool = False, seed: int = 123, num_trials: int = 1, core_loop_limit: int = 10, core_level_limit: int | None = None, tune_iteration_limit: int | None = None, core_loop_codelength_threshold: float = 1e-10, tune_iteration_relative_threshold: float = 1e-05, fast_hierarchical_solution: int | None = None, inner_parallelization: bool = False, parallel_trials: bool = False, converge: bool = False, num_threads: str | int | None = None, threads: str | int | None = None, prefer_modular_solution: bool = False, num_random_moves: int = 5, max_degree_for_random_moves: int = 2, options: Options | Mapping | None = None)

The stateful entry point to the algorithm: build a network with the add_* verbs, then call run() to get an immutable Result. Internally it composes a Network (input) and an Options config over a single Core boundary to the SWIG-compiled engine, rather than exposing that engine directly. For one-shot use prefer the functional infomap.run(); for incremental construction prefer Network.

Note

Only seed, num_trials, two_level, directed and markov_time are first-class keyword options here. The 70+ other keyword parameters in the __init__/run() signature are per-option deprecation shims that move off these signatures in 3.0 – carry every other engine option via Options (im.run(options=Options(regularized=True))) rather than as a bare keyword. The output-file flags (tree, clu, output, out_name, no_file_output …) are inert here; write from the Result / Network instead. For a clean, one-entry-per-option parameter reference read inspect.getdoc(infomap.Options), not the raw signature.

Examples

Build a network, run Infomap, and read the results off the returned Result:

>>> from infomap import Infomap
>>> im = Infomap()
>>> 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. Point read_file at your own network file (Pajek, link list, *States …); the bundled infomap.datasets need no file at all:

im = Infomap(num_trials=10)
im.read_file("your-network.net")
result = im.run()
result.codelength        # e.g. 3.3858
result.num_top_modules   # e.g. 3

Iterate the partition via Result.modules() (node_id -> module_id) or Result.nodes() (per-node views):

>>> from infomap import Infomap
>>> im = Infomap()
>>> 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 immutable Result; 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 Quick start and Reference notebooks.

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

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

Deprecated since version 2.15: Use Network.from_edge_index() or infomap.run(edge_index).

classmethod from_options(options, args=None)

Create an Infomap instance from Options.

Deprecated since version 2.15: Pass options to infomap.run() or Infomap.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 Infomap instance from a SciPy sparse adjacency matrix.

Deprecated since version 2.15: Use Network.from_scipy_sparse_matrix() or infomap.run(matrix).

__init__(args: str | None = None, include_self_links: bool | None = None, skip_adjust_bipartite_flow: bool = False, bipartite_teleportation: bool = False, weight_threshold: float | None = None, no_self_links: bool = False, node_limit: int | None = None, matchable_multilayer_ids: int | None = None, cluster_data: str | None = None, assign_to_neighbouring_module: bool = False, meta_data: str | None = None, meta_data_rate: float = 1.0, meta_data_unweighted: bool = False, no_infomap: bool = False, out_name: str | None = None, no_file_output: bool = False, tree: bool = False, ftree: bool = False, clu: bool = False, clu_level: int | None = None, output: list[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow']] | tuple[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow'], ...] | None = None, hide_bipartite_nodes: bool = False, print_all_trials: bool = False, no_overwrite: bool = False, print_config_fingerprint: bool = False, timing_json: str | None = None, summary_json: str | None = None, manifest_json: str | None = None, memory_report: bool = False, trial_offset: int | None = None, trial_results: str | None = None, no_final_output: bool = False, verbosity_level: int = 1, silent: bool = True, pretty: bool | None = None, two_level: bool = False, flow_model: Literal['undirected', 'directed', 'undirdir', 'outdirdir', 'rawdir', 'precomputed'] | None = None, directed: bool | None = None, recorded_teleportation: bool = False, use_node_weights_as_flow: bool = False, to_nodes: bool = False, teleportation_probability: float = 0.15, max_flow_iterations: int = 400, min_flow_iterations: int = 50, flow_tolerance: float = 1e-15, regularized: bool = False, regularization_strength: float = 1.0, entropy_corrected: bool = False, entropy_correction_strength: float = 1.0, markov_time: float = 1.0, variable_markov_time: bool = False, variable_markov_damping: float = 1.0, variable_markov_min_scale: float = 1.0, preferred_number_of_modules: int | None = None, preferred_number_of_levels: int | None = None, preferred_number_of_levels_strength: float = 1.0, multilayer_relax_rate: float = 0.15, multilayer_relax_limit: int = -1, multilayer_relax_limit_up: int = -1, multilayer_relax_limit_down: int = -1, multilayer_relax_by_jsd: bool = False, multilayer_relax_to_self: bool = False, seed: int = 123, num_trials: int = 1, core_loop_limit: int = 10, core_level_limit: int | None = None, tune_iteration_limit: int | None = None, core_loop_codelength_threshold: float = 1e-10, tune_iteration_relative_threshold: float = 1e-05, fast_hierarchical_solution: int | None = None, inner_parallelization: bool = False, parallel_trials: bool = False, converge: bool = False, num_threads: str | int | None = None, threads: str | int | None = None, prefer_modular_solution: bool = False, num_random_moves: int = 5, max_degree_for_random_moves: int = 2, options: Options | Mapping | None = None) None

Create a new Infomap instance.

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

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

  • options (Options, mapping, or None, optional) – A reusable Options object (or a mapping) applied as the base configuration; any keyword argument set to a non-default value overrides it. This is the canonical, warning-free carrier for the advanced options that leave the signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • bipartite_teleportation (bool, optional) –

    Use bipartite teleportation instead of the default two-step unipartite teleportation.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • weight_threshold (float, optional) –

    Ignore input links with weight below this threshold.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • no_self_links (bool, optional) –

    Exclude self-links from the input network.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • node_limit (int, optional) –

    Read only nodes up to this node id and ignore links connected to higher node ids.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • assign_to_neighbouring_module (bool, optional) –

    With –cluster-data, assign nodes missing module ids to a neighboring node’s module when possible.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • meta_data (str, optional) –

    Read metadata to encode from a clu-format file.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • meta_data_rate (float, optional) –

    With –meta-data, set the metadata encoding rate. The default encodes metadata at each step.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • meta_data_unweighted (bool, optional) –

    With –meta-data, encode metadata without weighting by node flow.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • no_infomap (bool, optional) –

    Skip optimization. Use this to calculate codelength for –cluster-data or to print non-modular statistics.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • out_name (str, optional) –

    Base name for output files, for example [out_directory]/[out-name].tree.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • no_file_output (bool, optional) –

    Do not write output files.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • tree (bool, optional) –

    Write the modular hierarchy to a tree file. Enabled by default when no other output format is selected.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • ftree (bool, optional) –

    Write the modular hierarchy and aggregated links between nested modules to an ftree file. Used by Network Navigator.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • clu (bool, optional) –

    Write top-level module ids for each node to a clu file.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • clu_level (int, optional) –

    With –clu or –output clu, write module ids at this depth from the root. Use -1 for bottom-level modules.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • 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.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • hide_bipartite_nodes (bool, optional) –

    Hide bipartite nodes in output by projecting the solution to primary nodes.

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. It projects the secondary (type-B) bipartite nodes out of what result.write_tree/write_clu emit, leaving the in-memory result covering both node types. Set it via Options and write from the Result to use it.

  • print_all_trials (bool, optional) –

    Write each trial to separate output files. Has effect only when –num-trials is greater than 1.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • no_overwrite (bool, optional) –

    Fail with an output error if any target output file already exists. By default existing files are replaced.

    Has no effect in the Python API unless an output directory is passed via args (library mode disables file output otherwise; use the write_* methods to write results).

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use Result.write_tree/write_flow_tree/write_clu (write_clu takes depth) or Network.write_pajek/write_state_network. The flag only acts when an output directory is passed via the raw args escape hatch.

  • print_config_fingerprint (bool, optional) –

    Print the canonical configuration fingerprint and exit.

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. A print-and-exit CLI diagnostic; run the infomap binary.

  • timing_json (str, optional) –

    Write machine-readable run timing JSON to this path. Use - for stdout.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • summary_json (str, optional) –

    Write machine-readable final run summary JSON to this path. Use - for stdout.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • manifest_json (str, optional) –

    Write a machine-readable run manifest JSON to this path. Use - for stdout.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • memory_report (bool, optional) –

    Include peak RSS and best-effort bytes per node/link estimates in timing JSON. Requires –timing-json.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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).

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • no_final_output (bool, optional) –

    Skip writing this process’s aggregate best result. Per-trial outputs and –trial-results are still written.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • verbosity_level (int, optional) –

    Verbosity level on the console. 1 keeps the default output level, 2 renders -vv and so on.

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. A DEBUG-enabled ‘infomap’ logger (infomap.enable_log(logging.DEBUG)) raises engine verbosity; logger levels filter the records.

  • silent (bool, optional) –

    Suppress console output. The Python API is already quiet by default; to see the engine log, use infomap.enable_log() rather than this flag. The command-line interface is unaffected.

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. The Python API is quiet by default; logging is the control. Attach handlers to logging.getLogger(‘infomap’) (e.g. infomap.enable_log()) for the engine log.

  • pretty (bool | None, optional) – Deprecated. Accepted for backward compatibility; has no effect. Passing it explicitly emits a DeprecationWarning.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • use_node_weights_as_flow (bool, optional) –

    Use node weights from the API or Pajek node records as normalized node flow.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • to_nodes (bool, optional) –

    Teleport to nodes instead of links. Uses uniform node weights unless node weights are provided.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • teleportation_probability (float, optional) –

    Set the probability of teleporting to a random node or link when calculating flow.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • max_flow_iterations (int, optional) –

    Limit the power iteration used to calculate flow (directed and regularized flow models) to this many iterations.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • min_flow_iterations (int, optional) –

    Require at least this many power iterations before the flow calculation can converge, even if –flow-tolerance is already met.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • flow_tolerance (float, optional) –

    Convergence tolerance for the power iteration used to calculate flow. Iteration stops once the per-iteration change in flow drops to or below this value, after –min-flow-iterations have run.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • regularized (bool, optional) –

    Add a fully connected Bayesian prior network to reduce overfitting to missing links. Activates –recorded-teleportation.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • regularization_strength (float, optional) –

    Scale the relative strength of the Bayesian prior network used by –regularized.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • entropy_corrected (bool, optional) –

    Correct for negative entropy bias in small samples, especially solutions with many modules.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • entropy_correction_strength (float, optional) –

    Scale the default correction used by –entropy-corrected.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • variable_markov_damping (float, optional) –

    With –variable-markov-time, set damping between local effective degree (0) and local entropy (1).

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • preferred_number_of_modules (int, optional) –

    Penalize solutions by how far their number of modules differs from this value.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • multilayer_relax_rate (float, optional) –

    Set the probability of relaxing from a state node to neighboring layers instead of staying in the current layer.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • multilayer_relax_by_jsd (bool, optional) –

    Weight multilayer relaxation by out-link similarity measured with Jensen-Shannon divergence.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • tune_iteration_limit (int, optional) –

    Limit the main iterations in the two-level partition algorithm. 0 means no limit.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • core_loop_codelength_threshold (float, optional) –

    Require at least this codelength improvement to accept a new solution in a core loop.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • tune_iteration_relative_threshold (float, optional) –

    Require each tune iteration to improve codelength by this fraction of the initial two-level codelength.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • fast_hierarchical_solution (int, optional) –

    Find top modules fast. Use 2 to keep all fast levels and 3 to skip the recursive part.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • num_threads (str or int, 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.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • threads (str or int, optional) –

    Alias for –num-threads.

    Deprecated since version 2.15: This keyword leaves the Infomap signature in 3.0. Use num_threads; threads is a redundant alias of the same engine option.

  • prefer_modular_solution (bool, optional) –

    Prefer a modular solution even when one module gives a lower codelength.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • num_random_moves (int, optional) –

    Try this many random moves in each core loop to merge weakly connected nodes.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

  • max_degree_for_random_moves (int, optional) –

    Try random moves only for nodes with degree at most this value.

    Changed in version 2.15: Pass it via Options; moves off this signature in 3.0.

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

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

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

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

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

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

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

Returns:

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

Return type:

dict

Notes

Unlike the networkx/igraph adapters (which auto-detect directedness via is_directed()), this adapter defaults directed=True and names its weight parameter edge_weight. add_scipy_sparse_matrix() instead defaults directed=False.

Deprecated since version 2.15: Use Network.from_edge_index() or infomap.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 name vertex attribute as Infomap node names when present, and treats node_id/layer_id vertex attributes as state/multilayer metadata.

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

  • edge_weights (str, sequence, or None, optional) – Edge weight attribute name or an explicit sequence with one value per edge. Default None auto-detects a "weight" edge attribute (mirroring the networkx adapter) and uses it when present, treating the graph as unweighted otherwise. Pass an explicit sequence of unit weights to force an unweighted run of a graph that carries a "weight" attribute.

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

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

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

  • meta_attribute (str, optional) – Vertex attribute to read categorical metadata from, for use with the meta-data map equation. Values are encoded to integers in first-seen order and set as Infomap metadata; vertices with missing values are skipped. Raises ValueError if 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:

dict

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() defaults directed=False, and add_edge_index() defaults directed=True. They also name their weight parameter differently: igraph edge_weights, networkx weight, scipy weighted (bool), edge_index edge_weight.

Deprecated since version 2.15: Use Network.from_igraph() or infomap.run(graph).

Add a link.

Notes

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

See also

remove_link

Parameters:
  • source_id (int)

  • target_id (int)

  • weight (float, optional)

Add several links.

Examples

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

See also

add_link, remove_link

Parameters:

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

Add an inter-layer link.

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

Notes

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

Examples

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

  • node_id (int)

  • target_layer_id (int)

  • weight (float, optional)

Add several inter-layer links.

Examples

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

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

Add an intra-layer link.

Adds a link within a layer in a multilayer network.

Examples

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

Notes

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

Parameters:
  • layer_id (int)

  • source_node_id (int)

  • target_node_id (int)

  • weight (float, optional)

Add several intra-layer links.

Examples

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

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

Add a multilayer link.

Adds a link between layers in a multilayer network.

Examples

Usage with tuples:

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

Usage with MultilayerNode

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

Notes

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

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

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

  • weight (float, optional)

Add several multilayer links.

Examples

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

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

add_networkx_graph(g, weight='weight', node_id='node_id', layer_id='layer_id', multilayer_inter_intra_format=True, 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()
>>> 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()
>>> 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()
>>> 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 the directed flag to True.

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

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

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

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

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

  • meta_attribute (str, optional) – Node attribute to read categorical metadata from, for use with the meta-data map equation. Values are encoded to integers in first-seen order and set as Infomap metadata; nodes with missing values are skipped. Raises ValueError if the attribute is not set on any node.

Returns:

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

Return type:

dict

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() defaults directed=False, and add_edge_index() defaults directed=True. They also name their weight parameter differently: networkx weight, igraph edge_weights, scipy weighted (bool), edge_index edge_weight.

Parallel edges in an nx.MultiGraph/nx.MultiDiGraph are each forwarded to add_link and self-loops are passed through.

Deprecated since version 2.15: Use Network.from_networkx() or infomap.run(graph).

add_node(node_id: int, name: str | None = None, teleportation_weight: float | None = None) None

Add a node.

See also

set_name, add_nodes

Parameters:
  • node_id (int)

  • name (str, optional)

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

add_nodes(nodes: Any) None

Add nodes.

See also

add_node

Examples

Add nodes

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

Add named nodes

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

Add named nodes with teleportation weights

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

Add named nodes using dict

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

Add named nodes with teleportation weights using dict

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

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

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

Add links and nodes from a SciPy sparse adjacency matrix.

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

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

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

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

Returns:

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

Return type:

dict

Notes

Unlike the networkx/igraph adapters (which auto-detect directedness via is_directed()), this adapter defaults directed=False and names its weight control weighted (a bool). add_edge_index() instead defaults directed=True.

Deprecated since version 2.15: Use Network.from_scipy_sparse_matrix() or infomap.run(matrix).

add_state_node(state_id: int, node_id: int, name: str | None = None) None

Add a state node.

Notes

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

Parameters:
  • state_id (int)

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

  • name (str, optional) – Name of the state node itself, as opposed to the physical node.

add_state_nodes(state_nodes: Any) None

Add state nodes.

See also

add_state_node

Examples

With tuples

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

With dict

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

state_nodes (iterable of tuples or dict of int: int) – Iterable of tuples of the form (state_id, node_id) or (state_id, node_id, name), 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 2.15: Use result = im.run(); result.to_dataframe(...).

Examples

>>> from infomap import Infomap
>>> im = Infomap()
>>> 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), or InfomapLeafIteratorPhysical. 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 True and physical-node iterators when False. Default True.

  • depth_level (int, optional) – Depth level passed to get_nodes(). Default 1.

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 InfoNode attribute.

Returns:

A DataFrame containing the selected columns.

Return type:

pandas.DataFrame

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 to 1 (default) to return the top modules (coarsest level). Set to 2 for second coarsest level etc. Set to -1 to return the bottom level modules (finest level).

Returns:

  • float – The effective number of modules

  • .. deprecated:: 2.15 – Use result = im.run(); result.effective_num_modules(depth).

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()
>>> 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

links, flow_links

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:: 2.15 – 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-nodes

Path 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()
>>> 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()
>>> 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, the node_id can 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, use get_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 to 2 for second coarsest level etc. Set to -1 to return the bottom level modules (finest level). Default 1.

  • states (bool, optional) – For higher-order networks, if states is True, it will return state node ids. Otherwise it will return physical node ids, merging state nodes with same node_id if they are in the same module. Note that the same physical node may end up on different paths in the tree. Default false.

Returns:

  • dict of int – Dict with node ids as keys and module ids as values.

  • .. deprecated:: 2.15 – 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

get_modules

Examples

>>> from infomap import Infomap
>>> im = Infomap(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()
>>> 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, the node_id can 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, use get_multilevel_modules(states=True).

Parameters:

states (bool, optional) – For higher-order networks, if states is True, it will return state node ids. Otherwise it will return physical node ids, merging state nodes with same node_id if they are in the same module. Note that the same physical node may end up on different paths in the tree. Default false.

Returns:

  • dict of list of int – Dict with node ids as keys and tuple of module ids as values.

  • .. deprecated:: 2.15 – 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 default will be returned.

See also

set_name, names

Parameters:
  • node_id (int)

  • default (str, optional) – The return value if the node name is missing, default None

Returns:

  • str – The node name if it exists, else the default.

  • .. deprecated:: 2.15 – Use result = im.run(); result.names.get(node_id).

get_names()

Get all node names.

See also

names, get_name

Returns:

  • dict of string – A dict with node ids as keys and node names as values.

  • .. deprecated:: 2.15 – 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 to 1 (default) to return the top modules (coarsest level). Set to 2 for second coarsest level etc. Set to -1 to return the bottom level modules (finest level). Default 1.

  • states (bool, optional) – For higher-order networks, if states is True, it will iterate over state nodes. Otherwise it will iterate over physical nodes, merging state nodes with same node_id if they are in the same module. Note that the same physical node may end up on different paths in the tree. See notes on physical_tree. Default false.

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 same node_id end up in different modules. However, the state nodes with the same node_id within each module are only visible as one (partial) physical node (if states = False).

Returns:

  • InfomapLeafIterator or InfomapIteratorPhysical – An iterator over each leaf node, depth first from the root

  • .. deprecated:: 2.15 – 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 *States section names the state nodes; empty otherwise. Physical node names are available separately via get_names().

Returns:

  • dict of string – A dict with state ids as keys and state-node names as values.

  • .. deprecated:: 2.15 – 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 to 1 (default) to return the top modules (coarsest level). Set to 2 for second coarsest level etc. Set to -1 to return the bottom level modules (finest level).

  • states (bool, optional) – For higher-order networks, if states is True, it will iterate over state nodes. Otherwise it will iterate over physical nodes, merging state nodes with same node_id if they are in the same module. Note that the same physical node may end up on different paths in the tree. Default false.

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 same node_id end up in different modules. However, the state nodes with the same node_id within each module are only visible as one (partial) physical node (if states = False).

Returns:

  • InfomapIterator or InfomapIteratorPhysical – An iterator over each node in the tree, depth first from the root

  • .. deprecated:: 2.15 – Use result = im.run(); result.tree(depth, states=states).

read_file(filename: str, accumulate: bool = True) None

Read network data from file.

Parameters:
  • filename (str)

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

Raises:

NetworkParseError – If the file cannot be opened or its content cannot be parsed.

Remove a link.

Notes

Removing links will not remove nodes if they become disconnected.

See also

add_link

Parameters:
  • source_id (int)

  • target_id (int)

Returns:

True if the link existed and was removed.

Return type:

bool

Remove several links.

Examples

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

See also

remove_link

Parameters:

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

run(args: str | None = None, initial_partition: dict | None = None, include_self_links: bool | None = None, skip_adjust_bipartite_flow: bool = False, bipartite_teleportation: bool = False, weight_threshold: float | None = None, no_self_links: bool = False, node_limit: int | None = None, matchable_multilayer_ids: int | None = None, cluster_data: str | None = None, assign_to_neighbouring_module: bool = False, meta_data: str | None = None, meta_data_rate: float = 1.0, meta_data_unweighted: bool = False, no_infomap: bool = False, out_name: str | None = None, no_file_output: bool = False, tree: bool = False, ftree: bool = False, clu: bool = False, clu_level: int | None = None, output: list[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow']] | tuple[Literal['clu', 'tree', 'ftree', 'newick', 'json', 'csv', 'network', 'states', 'flow'], ...] | None = None, hide_bipartite_nodes: bool = False, print_all_trials: bool = False, no_overwrite: bool = False, print_config_fingerprint: bool = False, timing_json: str | None = None, summary_json: str | None = None, manifest_json: str | None = None, memory_report: bool = False, trial_offset: int | None = None, trial_results: str | None = None, no_final_output: bool = False, verbosity_level: int = 1, silent: bool = False, pretty: bool | None = None, two_level: bool = False, flow_model: Literal['undirected', 'directed', 'undirdir', 'outdirdir', 'rawdir', 'precomputed'] | None = None, directed: bool | None = None, recorded_teleportation: bool = False, use_node_weights_as_flow: bool = False, to_nodes: bool = False, teleportation_probability: float = 0.15, max_flow_iterations: int = 400, min_flow_iterations: int = 50, flow_tolerance: float = 1e-15, regularized: bool = False, regularization_strength: float = 1.0, entropy_corrected: bool = False, entropy_correction_strength: float = 1.0, markov_time: float = 1.0, variable_markov_time: bool = False, variable_markov_damping: float = 1.0, variable_markov_min_scale: float = 1.0, preferred_number_of_modules: int | None = None, preferred_number_of_levels: int | None = None, preferred_number_of_levels_strength: float = 1.0, multilayer_relax_rate: float = 0.15, multilayer_relax_limit: int = -1, multilayer_relax_limit_up: int = -1, multilayer_relax_limit_down: int = -1, multilayer_relax_by_jsd: bool = False, multilayer_relax_to_self: bool = False, seed: int = 123, num_trials: int = 1, core_loop_limit: int = 10, core_level_limit: int | None = None, tune_iteration_limit: int | None = None, core_loop_codelength_threshold: float = 1e-10, tune_iteration_relative_threshold: float = 1e-05, fast_hierarchical_solution: int | None = None, inner_parallelization: bool = False, parallel_trials: bool = False, converge: bool = False, num_threads: str | int | None = None, threads: str | int | None = None, prefer_modular_solution: bool = False, num_random_moves: int = 5, max_degree_for_random_moves: int = 2, options: Options | Mapping | None = None) Result

Run Infomap.

The per-option keyword arguments match Infomap and are documented there; Options is the full parameter reference. Reuse a saved configuration by passing infomap.run() an options= carrier.

Boolean flags default to off here and render only when set; a flag chosen at construction stays in effect for every run.

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.

  • options (Options, mapping, or None, optional) – A reusable Options object (or a mapping) applied as the base configuration; any keyword argument set to a non-default value overrides it. This is the canonical, warning-free carrier for the advanced options that leave the signature in 3.0.

Returns:

The result of this run. See Result.

Return type:

Result

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

Run Infomap using a reusable Options instance.

Deprecated since version 2.15: Use infomap.run(input, options=options) instead.

set_meta_data(node_id, meta_category=None)

Set integer metadata for one node, or for many at once.

Examples

>>> from infomap import Infomap, Options
>>> im = Infomap(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, 2: 0, 3: 1})
>>> im.set_meta_data(4, 1)
>>> im.set_meta_data(5, 0)
>>> im.set_meta_data(6, 0)
>>> result = im.run(options=Options(meta_data_rate=0))
>>> result.num_top_modules
2
>>> result = im.run(options=Options(meta_data_rate=2))
>>> result.num_top_modules
3
Parameters:
  • node_id (int or mapping) – A node id, or a {node_id: meta_category} mapping to assign metadata to several nodes in one call, as in Network.set_meta_data().

  • meta_category (int, optional) – The meta category, when node_id is a single node id (ignored when node_id is a mapping).

set_name(node_id: int, name: str | None) None

Set the name of a node.

Parameters:
set_names(names: Any) None

Set names to several nodes at once.

Examples

With tuples

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

With dict

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

See also

set_name, names

Parameters:

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

summary()

Return a compact dictionary describing this instance’s state.

A state card for the stateful builder (it also backs the notebook HTML repr). Before run() it holds loaded network counts and higher-order state-node information, with status set to "not run"; after run() it also includes module counts, codelength components, entropy rate, and elapsed time. Module counts use the short card keys (top_modules, levels, leaf_modules).

This is not Result.summary(). For a finished run’s result metrics as a one-row-per-run record – keyed by the Result property names (num_top_modules, num_levels), the shape for collecting a sweep into a pandas.DataFrame – read summary() off the Result that run() returns instead.

See also

Result.summary

the returned run’s result metrics as a sweep row.

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 includes module_id for 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, then node_id). Default ["node_id", "module_id", "flow", "path", "name"].

  • states (bool, optional) – Use state-node iterators when True and physical-node iterators when False. Default False.

  • level (int, optional) – Depth level passed to get_nodes(). Default 1.

  • index (str, bool, or None, optional) – Column to set as the DataFrame index. Use False or None to keep the default RangeIndex.

  • sort (bool, str, or sequence of str, optional) – Sort by one or more columns. Use True to sort by ["module_id", "node_id"] when available. Default False.

  • depth_level (int, optional) – Backward-compatible alias for level.

  • deprecated: (..) – 2.15: Use result = im.run(); result.to_dataframe(...).

write(filename: str | PathLike[str], *args, **kwargs) None

Write results to file, inferring the format from the extension.

An existing file at filename is overwritten.

Raises:
  • ValueError – If filename has no extension to infer the format from.

  • NotImplementedError – If the file format is not supported on this host.

Parameters:

filename (str or os.PathLike) – The filename.

write_clu(filename: str | PathLike[str], states: bool = False, depth: int | None = None, *, depth_level: int | None = None) None

Write result to a clu file.

An existing file at filename is overwritten.

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

  • depth (int, optional) – The depth in the hierarchical tree to write. Accepted positionally, matching result.modules(depth=...) and result.to_dataframe(depth=...). 1 (default) is the top level, -1 the bottom; it overrides depth_level when given.

  • depth_level (int, optional) – Legacy keyword alias of depth (the historical write_clu keyword); still accepted.

write_csv(filename: str | PathLike[str], states: bool = False) None

Write result to a CSV file.

An existing file at filename is overwritten.

See also

write_clu, write_tree

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

write_flow_tree(filename: str | PathLike[str], states: bool = False) None

Write result to a ftree file.

An existing file at filename is overwritten.

See also

write_clu, write_tree

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

write_json(filename: str | PathLike[str], states: bool = False) None

Write result to a JSON file.

An existing file at filename is overwritten.

See also

write_clu, write_tree

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

write_newick(filename: str | PathLike[str], states: bool = False) None

Write result to a Newick file.

An existing file at filename is overwritten.

See also

write_clu, write_tree

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

write_pajek(filename: str | PathLike[str], flow: bool = False) None

Write network to a Pajek file.

An existing file at filename is overwritten.

Parameters:
  • filename (str or os.PathLike)

  • flow (bool, optional) – If the flow should be included. Default False.

write_state_network(filename: str | PathLike[str]) None

Write internal state network to file.

An existing file at filename is overwritten.

See also

write_pajek

Parameters:

filename (str or os.PathLike)

write_tree(filename: str | PathLike[str], states: bool = False) None

Write result to a tree file.

An existing file at filename is overwritten.

Parameters:
  • filename (str or os.PathLike)

  • states (bool, optional) – If the state nodes should be included. Default False.

property bipartite_start_id

Get or set the bipartite start id.

Examples

>>> from infomap import Infomap
>>> im = Infomap(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
Returns:

The node id where the second node type starts.

Return type:

int

property codelength

Get the total (hierarchical) codelength.

Returns:

  • float – The codelength

  • .. deprecated:: 2.15 – Use result = im.run(); result.codelength.

property codelengths

Get the total (hierarchical) codelength for each trial.

See also

codelength

Returns:

  • tuple of float – The codelengths for each trial

  • .. deprecated:: 2.15 – 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:: 2.15 – 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:: 2.15 – 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:: 2.15 – 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()
>>> im.read_file("twotriangles.net")
>>> _ = im.run()
>>> f"{im.entropy_rate:.5f}"
'1.25070'
Returns:

  • float – The entropy rate

  • .. deprecated:: 2.15 – Use result = im.run(); result.entropy_rate.

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()
>>> 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

links

Returns:

  • tuple of int, int, float – An iterator of source, target, flow tuples.

  • .. deprecated:: 2.15 – 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:: 2.15 – Use result = im.run(); result.have_memory.

property index_codelength

Get the two-level index codelength.

Returns:

  • float – The two-level index codelength

  • .. deprecated:: 2.15 – 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, Options
>>> im = Infomap()
>>> 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(options=Options(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 (or MultilayerNode) as keys. The resolution to internally generated state ids is deferred until the network is built when you call run().

>>> from infomap import Infomap, MultilayerNode
>>> im = Infomap()
>>> 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}
Parameters:

module_ids (dict, or None) – Either {node_or_state_id: module_id} (integers) or, for a multilayer network, {(layer_id, node_id): module_id}.

Returns:

The initial partition as last set.

Return type:

dict

property leaf_modules

A view of the leaf modules, i.e. the bottom modules containing leaf nodes.

Returns:

  • InfomapLeafModuleIterator – An iterator over each leaf module in the tree, depth first from the root

  • .. deprecated:: 2.15 – Use result = im.run(); result.leaf_modules().

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()
>>> 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

flow_links

Returns:

  • tuple of int, int, float – An iterator of source, target, weight tuples.

  • .. deprecated:: 2.15 – Use result = im.run(); result.links().

property max_depth

Get the max depth of the hierarchical tree.

Returns:

  • int – The max depth

  • .. deprecated:: 2.15 – Use result = im.run(); result.max_depth.

property meta_codelength

Get the meta codelength.

This is the meta entropy times the metadata rate.

See also

meta_entropy

Returns:

  • float – The meta codelength

  • .. deprecated:: 2.15 – Use result = im.run(); result.meta_codelength.

property meta_entropy

Get the meta entropy (unweighted by metadata rate).

See also

meta_codelength

Returns:

  • float – The meta entropy

  • .. deprecated:: 2.15 – 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_codelength

For a hierarchical solution, the module codelength is the sum of codelengths for each top module.

Returns:

  • float – The module codelength

  • .. deprecated:: 2.15 – Use result = im.run(); result.module_codelength.

property modules

A view of the top-level modules, mapping node_id to module_id.

Notes

In a higher-order network, a physical node (defined by node_id) may partially exist in multiple modules. However, the node_id can 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, use get_modules(states=True).

Examples

>>> from infomap import Infomap
>>> im = Infomap(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

get_modules

Yields:
  • tuple of int, int – An iterator of (node_id, module_id) pairs.

  • .. deprecated:: 2.15 – Use result = im.run(); result.modules().

property multilevel_modules

A view of the multilevel modules, mapping node_id to a tuple of module_id.

Notes

In a higher-order network, a physical node (defined by node_id) may partially exist in multiple modules. However, the node_id can 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, use get_multilevel_modules(states=True).

Yields:
  • tuple of (int, tuple of int) – An iterator of (node_id, (module_ids...) pairs.

  • .. deprecated:: 2.15 – Use result = im.run(); result.multilevel_modules().

property names

Get all node names.

Short-hand for get_names.

See also

get_names, get_name

Returns:

  • dict of string – A dict with node ids as keys and node names as values.

  • .. deprecated:: 2.15 – 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).

Returns:

  • InfomapLeafIterator – An iterator over each leaf node in the tree, depth first from the root

  • .. deprecated:: 2.15 – 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:: 2.15 – 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

max_depth

Returns:

  • int – The max depth

  • .. deprecated:: 2.15 – Use result = im.run(); result.num_levels.

The number of links.

Returns:

The number of links

Return type:

int

property num_nodes

The number of state nodes if we have a higher order network, or the number of physical nodes.

Returns:

The number of nodes

Return type:

int

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:: 2.15 – Use result = im.run(); result.num_non_trivial_top_modules.

property num_physical_nodes

The number of physical nodes.

See also

num_nodes

Returns:

The number of nodes

Return type:

int

property num_top_modules

Get the number of top modules in the tree

Returns:

  • int – The number of top modules

  • .. deprecated:: 2.15 – Use result = im.run(); result.num_top_modules.

property one_level_codelength

Get the one-level codelength.

See also

codelength

Returns:

  • float – The one-level codelength

  • .. deprecated:: 2.15 – 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_id are merged to one physical node.

Convenience method for get_nodes(depth_level=1, states=False).

See also

get_nodes

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:: 2.15 – 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_id are merged to one physical node.

Convenience method for get_tree(depth_level=1, states=False).

Returns:

  • iterator – An iterator over each physical node in the tree, depth first from the root (InfomapIteratorPhysical for memory networks, InfomapIterator for first-order networks)

  • .. deprecated:: 2.15 – 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 L is the codelength and L_1 the one_level_codelength.

Returns:

  • float – The relative codelength savings

  • .. deprecated:: 2.15 – Use result = im.run(); result.relative_codelength_savings.

property state_names

Get all state-node names.

Short-hand for get_state_names.

Returns:

  • dict of string – A dict with state ids as keys and state-node names as values.

  • .. deprecated:: 2.15 – 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).

Returns:

  • InfomapIterator – An iterator over each node in the tree, depth first from the root

  • .. deprecated:: 2.15 – Use result = im.run(); result.tree(states=True).