Top-level functions

The functional API and its building blocks. Most work goes through run(); the rest are graph-package convenience wrappers and standalone primitives.

Running Infomap

infomap.run(input: Any, *, options: Options | Mapping[str, Any] | None=None, seed: int = <unset>, num_trials: int = <unset>, two_level: bool = <unset>, directed: bool | None = <unset>, markov_time: float = <unset>, args: str | None = None, initial_partition: dict[Any, Any] | None=None, **overrides: Any) Result

Run Infomap on input and return a Result.

This is the canonical entry point. It accepts any supported network representation – including a prebuilt Network or Infomap instance – so net.run(**kw) and im.run(**kw) are thin conveniences equivalent to infomap.run(net, **kw) / infomap.run(im, **kw).

Parameters:
  • input (Network, Infomap, networkx.Graph, igraph.Graph, scipy sparse matrix, (2, E) array/tensor, str or Path, or iterable of links) – The network to partition. See the module docstring for the dispatch table.

  • options (Options, mapping, or None, optional) – Base configuration. Any keyword argument below takes precedence.

  • seed (int, optional) – Random-number-generator seed for reproducible results (default 123).

  • num_trials (int, optional) – Number of independent trials to run; the best solution is kept (default 1).

  • two_level (bool, optional) – Optimize a two-level partition instead of the default multilevel hierarchy.

  • directed (bool, optional) – Treat links as directed (shorthand for flow_model="directed"). For a graph, file, or link-iterable input this is an engine flag; for a SciPy sparse matrix or a (2, E) edge index it names the input adapter’s orientation instead and is rejected here – build the network with Network.from_scipy_sparse_matrix(..., directed=True) / Network.from_edge_index(..., directed=True), or pass options=Options(flow_model="directed").

  • markov_time (float, optional) – Scale link flow to change the cost of moving between modules; higher values yield fewer modules.

  • args (str, optional) – Raw Infomap arguments prepended before the rendered options – the escape hatch for full CLI parity.

  • initial_partition (mapping, optional) – Initial module assignment for this run only.

  • **overrides – Any other Infomap engine option, as a keyword argument, forwarded to Options. Convenient for a one-off; for a reusable or validated configuration prefer options=Options(...) (the canonical carrier and the full parameter reference). They configure the engine, not how the input is read.

Returns:

An immutable snapshot of the run.

Return type:

Result

Notes

The Python API is quiet by default. To see the engine log, attach a handler to the infomap logger with infomap.enable_log() (infomap.enable_log(logging.DEBUG) for more detail). The infomap command-line interface keeps its verbose default.

Keyword arguments go to the engine; the input adapters always build with their defaults (e.g. networkx reads the "weight" edge attribute, a SciPy matrix is treated as undirected). For non-default input building – a different weight attribute, explicit directedness, a state/multilayer layout – build the network first and run it:

infomap.run(Network.from_networkx(g, weight="capacity"), num_trials=10)
infomap.run(Network.from_scipy_sparse_matrix(A, directed=True))

Passing an adapter argument to run() directly (run(g, weight=...), run(A, directed=True)) raises with a pointer to the matching Network.from_* constructor, rather than silently ignoring it or building a different graph.

A 2-row integer array/tensor is read as a (2, E) edge index. A weighted link matrix (rows of (source, target, weight)) has a float column and is read as link rows; to pass integer link rows explicitly, use a list of tuples or Network().add_links(...).

Examples

One call from an iterable of (u, v[, w]) links to a Result:

>>> from infomap import run
>>> result = run([(1, 2), (1, 3), (2, 3), (4, 5), (4, 6), (5, 6), (3, 4)])
>>> result.num_top_modules
2
>>> 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

Graph-package entry points

infomap.find_communities(g: networkx.Graph, *, weight: str | None = 'weight', node_id: str = 'node_id', layer_id: str = 'layer_id', multilayer_inter_intra_format: bool = True, options: Options | Mapping[str, Any] | None = None, trials: int | None = None, initial_partition: Mapping[Any, Any] | None = None, module_attribute: str | None = None, flow_attribute: str | None = None, meta_attribute: str | None = None, **infomap_options: Any) list[set[Any]]

Find communities in a NetworkX-style graph.

This is the NetworkX variant; its igraph counterpart is find_igraph_communities(). The unqualified name is kept for backward compatibility.

This helper is duck-typed and does not import NetworkX. It accepts the same graph objects as Infomap.add_networkx_graph(), runs Infomap, and returns communities using the original graph node labels.

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

  • weight (str or None, optional) – Key to look up link weight in edge data if present. Default "weight". Use None to treat every edge as weight 1. The name matches networkx; the igraph counterpart find_igraph_communities() uses edge_weights / vertex_weights (python-igraph’s own community_infomap names).

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

  • options (Options, mapping, or None, optional) – Base engine configuration carried the 3.0-safe way – an Options instance or a mapping. Any bare keyword below (and an explicit trials / num_trials) takes precedence.

  • trials (int, optional) – Number of independent trials; the best solution is kept. Convenience alias for the num_trials Infomap option (matching find_igraph_communities()). Pass trials or num_trials, not both; if neither is given the engine default num_trials=1 applies – raise it for research runs.

  • module_attribute (str, optional) – If set, write each node’s module id back to this node attribute on g.

  • flow_attribute (str, optional) – If set, write each node’s flow back to this node attribute on g.

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

  • initial_partition (mapping, optional) – Initial module assignment passed to infomap.Infomap.run(). Keys may use the original NetworkX node labels.

  • **infomap_options – Engine options passed to infomap.Infomap. The engine is quiet by default; call infomap.enable_log() for the log. Prefer carrying non-common options via the options= argument above (the 3.0-safe path).

Returns:

A partition of g.nodes grouped by top-level Infomap module. This is the list-of-sets shape NetworkX’s own community functions return (e.g. networkx.community.louvain_communities), which also keeps it drop-in for a NetworkX community backend. The igraph counterpart find_igraph_communities() instead returns an igraph.VertexClustering – each finder returns its ecosystem’s idiomatic partition type, so the shape differs by design.

Return type:

list of set

Raises:

ValueError – If both trials and num_trials are passed.

infomap.find_igraph_communities(g: igraph.Graph, *, edge_weights: str | Iterable[Any] | None = None, vertex_weights: Any = None, options: Options | Mapping[str, Any] | None = None, trials: int | None = None, node_id: str = 'node_id', layer_id: str = 'layer_id', multilayer_inter_intra_format: bool = True, module_attribute: str | None = None, flow_attribute: str | None = None, meta_attribute: str | None = None, **infomap_options: Any) igraph.VertexClustering

Find communities in a python-igraph graph.

This helper builds an Infomap instance from g (via Infomap.add_igraph_graph()), runs Infomap, and returns the top-level partition as an igraph clustering.

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. The edge_weights / vertex_weights names match python-igraph’s own community_infomap signature; the networkx counterpart find_communities() uses weight.

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

  • options (Options, mapping, or None, optional) – Base engine configuration carried the 3.0-safe way – an Options instance or a mapping. Any bare keyword below (and an explicit trials / num_trials) takes precedence.

  • trials (int, optional) – Number of independent trials; the best solution is kept. Convenience alias for the num_trials Infomap option. Pass trials or num_trials, not both; if neither is given the engine default num_trials=1 applies – raise it for research runs.

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

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

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

  • module_attribute (str, optional) – If set, write each vertex’s module id back to this vertex attribute on g.

  • flow_attribute (str, optional) – If set, write each vertex’s flow back to this vertex attribute on g.

  • meta_attribute (str, optional) – Vertex attribute to read categorical metadata from. 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.

  • **infomap_options – Engine options passed to infomap.Infomap. The engine is quiet by default; call infomap.enable_log() for the log. Prefer carrying non-common options via the options= argument above (the 3.0-safe path).

Returns:

The top-level partition, with the codelength of the solution attached as a codelength attribute. For an empty graph, an empty clustering with codelength 0.0 is returned without running Infomap. This is the same type python-igraph’s own community methods return (e.g. Graph.community_infomap); the networkx counterpart find_communities() instead returns a list of set – each finder returns its ecosystem’s idiomatic partition type, so the shape differs by design.

Return type:

igraph.VertexClustering

Raises:

ValueError – If both trials and num_trials are passed.

Engine log

The engine log becomes Python log records on the "infomap" logger when that logger has handlers; see the routing rules in Running Infomap.

infomap.enable_log(level: int = 20) Handler

Show the engine log as Python log records, in one line.

Attaches a plain %(message)s stream handler (stdout) to the "infomap" logger and sets the logger level, which engages the log routing: every engine run emits records — no silent=False needed — and stdout output is replaced by the records. Pass level=logging.DEBUG for the engine’s -vv detail lines.

Idempotent: repeated calls reuse the same handler and only adjust the level. Undo with disable_log(). For full control (formatting, files, propagation), skip this helper and configure logging.getLogger("infomap") with standard logging instead.

Turns off propagation while active so records are not also emitted by a root handler installed via logging.basicConfig (which would print each line twice); disable_log() restores propagation.

Parameters:

level (int, optional) – The logger level, by default logging.INFO. Use logging.DEBUG to include the engine’s detail lines.

Returns:

The installed handler (useful for reformatting or removal).

Return type:

logging.Handler

Examples

>>> import infomap
>>> handler = infomap.enable_log()
>>> infomap.disable_log()
infomap.disable_log() None

Remove the handler installed by enable_log().

Handlers the user attached themselves are left untouched; with no handlers remaining, the engine goes back to classic stdout output (gated by silent=).

Information-theoretic primitives

The building blocks behind the map equation, exposed for standalone use.

infomap.entropy(p)

Compute the Shannon entropy of a probability distribution in bits.

Parameters:

p (iterable of float) – Probabilities.

Returns:

The entropy -sum(x * log2(x) for x in p).

Return type:

float

infomap.perplexity(p)

Compute the perplexity of a probability distribution.

The perplexity is 2 ** entropy(p), interpretable as the effective number of outcomes in the distribution.

Parameters:

p (iterable of float) – Probabilities.

Returns:

The perplexity.

Return type:

float

infomap.plogp(p)

Compute x * log2(x) for each value in p.

Parameters:

p (iterable of float) – Probabilities.

Returns:

x * log2(x) for each x in p, or 0 where x <= 0.

Return type:

generator of float

Build and CLI entry points

infomap.build_info()

Report how the compiled Infomap extension was built.

Returns:

A dict with an enabled_features tuple naming the optional features the native engine was compiled with (empty for a standard build).

Return type:

dict

Examples

>>> import infomap
>>> sorted(infomap.build_info())
['enabled_features']
infomap.main()

Run the infomap command-line interface.

This is the console-script entry point behind the infomap command (and python -m infomap): it joins sys.argv[1:] into a native CLI invocation and returns the process exit code, suitable for sys.exit. A keyboard interrupt exits cleanly with code 130.