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
inputand return aResult.This is the canonical entry point. It accepts any supported network representation – including a prebuilt
NetworkorInfomapinstance – sonet.run(**kw)andim.run(**kw)are thin conveniences equivalent toinfomap.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 withNetwork.from_scipy_sparse_matrix(..., directed=True)/Network.from_edge_index(..., directed=True), or passoptions=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 preferoptions=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:
Notes
The Python API is quiet by default. To see the engine log, attach a handler to the
infomaplogger withinfomap.enable_log()(infomap.enable_log(logging.DEBUG)for more detail). Theinfomapcommand-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 matchingNetwork.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 orNetwork().add_links(...).Examples
One call from an iterable of
(u, v[, w])links to aResult:>>> 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". UseNoneto treat every edge as weight 1. The name matches networkx; the igraph counterpartfind_igraph_communities()usesedge_weights/vertex_weights(python-igraph’s owncommunity_infomapnames).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
Optionsinstance or a mapping. Any bare keyword below (and an explicittrials/num_trials) takes precedence.trials (int, optional) – Number of independent trials; the best solution is kept. Convenience alias for the
num_trialsInfomap option (matchingfind_igraph_communities()). Passtrialsornum_trials, not both; if neither is given the engine defaultnum_trials=1applies – 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
ValueErrorif 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; callinfomap.enable_log()for the log. Prefer carrying non-common options via theoptions=argument above (the 3.0-safe path).
- Returns:
A partition of
g.nodesgrouped 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 NetworkXcommunitybackend. The igraph counterpartfind_igraph_communities()instead returns anigraph.VertexClustering– each finder returns its ecosystem’s idiomatic partition type, so the shape differs by design.- Return type:
- Raises:
ValueError – If both
trialsandnum_trialsare 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
Infomapinstance fromg(viaInfomap.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
Noneauto-detects a"weight"edge attribute (mirroring the networkx adapter) and uses it when present, treating the graph as unweighted otherwise. Theedge_weights/vertex_weightsnames match python-igraph’s owncommunity_infomapsignature; the networkx counterpartfind_communities()usesweight.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
Optionsinstance or a mapping. Any bare keyword below (and an explicittrials/num_trials) takes precedence.trials (int, optional) – Number of independent trials; the best solution is kept. Convenience alias for the
num_trialsInfomap option. Passtrialsornum_trials, not both; if neither is given the engine defaultnum_trials=1applies – 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_idis 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
ValueErrorif the attribute does not exist.**infomap_options – Engine options passed to
infomap.Infomap. The engine is quiet by default; callinfomap.enable_log()for the log. Prefer carrying non-common options via theoptions=argument above (the 3.0-safe path).
- Returns:
The top-level partition, with the codelength of the solution attached as a
codelengthattribute. For an empty graph, an empty clustering withcodelength0.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 counterpartfind_communities()instead returns alistofset– each finder returns its ecosystem’s idiomatic partition type, so the shape differs by design.- Return type:
igraph.VertexClustering
- Raises:
ValueError – If both
trialsandnum_trialsare 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)sstream handler (stdout) to the"infomap"logger and sets the logger level, which engages the log routing: every engine run emits records — nosilent=Falseneeded — and stdout output is replaced by the records. Passlevel=logging.DEBUGfor the engine’s-vvdetail 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 configurelogging.getLogger("infomap")with standardlogginginstead.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. Uselogging.DEBUGto include the engine’s detail lines.- Returns:
The installed handler (useful for reformatting or removal).
- Return type:
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.
- 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.
Build and CLI entry points¶
- infomap.build_info()¶
Report how the compiled Infomap extension was built.
- Returns:
A dict with an
enabled_featurestuple naming the optional features the native engine was compiled with (empty for a standard build).- Return type:
Examples
>>> import infomap >>> sorted(infomap.build_info()) ['enabled_features']
- infomap.main()¶
Run the
infomapcommand-line interface.This is the console-script entry point behind the
infomapcommand (andpython -m infomap): it joinssys.argv[1:]into a native CLI invocation and returns the process exit code, suitable forsys.exit. A keyboard interrupt exits cleanly with code 130.