Result

Result is the immutable snapshot returned by infomap.run() and Infomap.run(). Scalar metrics are properties; node and tree collections are methods with defaults (modules(depth=1), nodes(), to_dataframe()).

class infomap.Result(engine: Infomap, *, generation: int)

Immutable snapshot of an Infomap run.

Returned by Infomap.run() (and the functional infomap.run()) and used to back the legacy on-instance accessors. Holds eager O(1) scalars; tree-derived metrics (the effective_num_* modules) and node/tree/dataframe data are materialized lazily and guarded against the engine being re-run.

Carries the result-artifact file writers (write_tree, write_clu, write_flow_tree, …): write the mapequation.org tool files straight off the result, whatever built it. Like all node-level access, writing is generation-guarded — a stale Result raises instead of writing the rebuilt tree.

Read scalars as properties and collections as methods (with defaults):

Examples

Run Infomap and read the partition off the Result:

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

Per-node views via nodes() (a physical-node default; pass states=True for state nodes):

>>> for node in sorted(result.nodes(), key=lambda n: n.node_id):
...     print(node.node_id, node.module_id, f"{node.flow:.4f}")
1 1 0.1429
2 1 0.1429
3 1 0.2143
4 2 0.2143
5 2 0.1429
6 2 0.1429

A Result is a snapshot, not a live handle: re-running the same Infomap rebuilds the C++ result tree, so node-level access on the old Result raises. Eager scalars (codelength, num_top_modules, …) stay valid.

For a sweep, summary() returns the scalar metrics as a dict (one row per run, so pandas.DataFrame(r.summary() for r in results) builds a table) and to_series() gives the pandas-native row; both read only the eager scalars and stay valid after a re-run.

effective_num_modules(depth: int = 1) float

Return the flow-weighted effective number of modules at depth.

Measured as the perplexity of the module flow distribution. Equivalent to the legacy Infomap.get_effective_num_modules(depth).

Parameters:

depth (int, optional) – The module level. 1 (default) is the top (coarsest) level; -1 the bottom (leaf-module) level.

leaf_modules() Iterator[InfomapLeafModuleIterator]

Iterate the leaf modules (bottom modules containing leaf nodes), depth first from the root.

Equivalent to the legacy Infomap.leaf_modules iterator.

Returns:

Yields each leaf module (the live InfomapLeafModuleIterator positions). The iterator is generation-guarded: consuming it after the bound engine re-runs raises instead of walking a rebuilt tree.

Return type:

generator

Iterate the partitioned links with their weight or flow.

Equivalent to the legacy Infomap.get_links(data). The sources and targets are state ids for a state or multilayer network.

Parameters:

data (str, optional) – The kind of value to return, one of "weight" or "flow". Default "weight".

Returns:

(source, target, weight_or_flow) tuples. The generator is generation-guarded like tree(): consuming it after the bound engine re-runs raises instead of reading the rebuilt engine.

Return type:

generator of (int, int, float)

modules(depth: int = 1, *, states: bool = False) dict[int, int]

Map node_id (or state_id when states) to module_id.

Equivalent to the legacy Infomap.get_modules(depth, states): for a higher-order (multilayer/memory) network, requesting physical-node modules without states is ambiguous and raises, mirroring the C++ getModules guard.

Parameters:
  • depth (int, optional) – The depth in the hierarchical tree of the reported module ids. 1 (default) is the top (coarsest) level; -1 the bottom (finest) level.

  • states (bool, optional) – Key the mapping by state_id when True, by node_id when False (the default).

Returns:

{node_or_state_id: module_id} for every leaf node.

Return type:

dict of int to int

Raises:

InfomapError – For a higher-order network when states is False.

See also

multilevel_modules

Module ids for every level at once.

tree

Walk the full hierarchical tree.

multilevel_modules(*, states: bool = False) dict[int, tuple[int, ...]]

Map node_id (or state_id when states) to a tuple of module_id, one per level from the top down.

Equivalent to the legacy Infomap.get_multilevel_modules(states).

Parameters:

states (bool, optional) – Key the mapping by state_id when True, by node_id when False (the default).

Returns:

{node_or_state_id: (top_module_id, ..., leaf_module_id)}.

Return type:

dict of int to tuple of int

See also

modules

Module ids for a single level.

nodes(depth: int = 1, *, states: bool = False) Iterator[TreeNode]

Iterate leaf TreeNode views, depth first from the root.

Parameters:
  • depth (int, optional) – The module level reported by node.module_id. 1 (default) is the top (coarsest) level; -1 the bottom (finest).

  • states (bool, optional) – Iterate state nodes when True. When False (the default), iterate physical nodes, merging state nodes with the same node_id if they are in the same module; the same physical node may then appear on different paths in the tree.

Yields:

TreeNode – An immutable snapshot view per leaf node.

summary() dict[str, Any]

Return the result’s scalar metrics as a plain dict.

A one-row-per-run record for collecting a sweep into a table: write the loop as you normally would and drop each summary into pandas, adding your own swept-parameter columns alongside:

records = []
for markov_time in (0.5, 1.0, 2.0):
    result = infomap.run(graph, markov_time=markov_time, seed=123)
    records.append({"markov_time": markov_time, **result.summary()})
df = pandas.DataFrame(records)

The keys match the scalar Result property names, so each column reads the same as the attribute you would read off a single result (df["codelength"] mirrors result.codelength).

This is distinct from Infomap.summary(). That method describes the stateful instance – network counts and run status, available even before a run – and keys its module counts with the shorter card names (top_modules, levels). Result.summary reports only a finished run’s result metrics, keyed by the Result property names (num_top_modules, num_levels); it is the shape to collect into a sweep table.

A curated set of the eagerly captured O(1) scalars is included, so summary is cheap and stays valid for the life of the Result: it never walks the tree and never raises StaleResultError, even after the bound engine has re-run. The tree-derived effective_num_* metrics and the per-trial codelengths are intentionally left out (read them off their properties when needed). A few eager scalars are also omitted to keep the row focused on the common case – add them yourself when a sweep needs them: meta_codelength / meta_entropy (metadata runs), num_physical_nodes and have_memory (higher-order networks), and max_depth.

Returns:

{metric_name: value} for the scalar result metrics.

Return type:

dict

See also

to_series

the same record as a pandas.Series.

to_dataframe

the per-node table for a single result.

Infomap.summary

the stateful instance’s state card (different keys).

Examples

>>> import infomap
>>> result = infomap.run(infomap.datasets.two_triangles(), seed=123)
>>> summary = result.summary()
>>> summary["num_top_modules"]
2
>>> summary["codelength"] == result.codelength
True
>>> "num_levels" in summary
True
to_dataframe(columns: Sequence[str] | None = None, *, states: bool = False, depth: int | None = None, index: str | bool | None = None, sort: bool | str | Sequence[str] = False, level: int | None = None, depth_level: int | None = None) pandas.DataFrame

Return a pandas DataFrame of the leaf nodes.

Byte-identical to the legacy Infomap.to_dataframe.

Parameters:
  • columns (sequence of str, optional) – Columns to include. "community" is accepted as an alias for "module_id". "name" resolves the physical node name (falling back to the integer node_id); 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); see state_names. Default ["node_id", "module_id", "flow", "path", "name"].

  • states (bool, optional) – Use state nodes when True and physical nodes when False (the default).

  • depth (int, optional) – The module level reported by module_id, as in modules(). 1 (default) is the top (coarsest) level; -1 the bottom (finest).

  • index (str, bool, or None, optional) – Column to set as the DataFrame index. Use False or None (the default) 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.

  • level (int, optional) –

    Deprecated since version 2.15: Alias for depth.

  • depth_level (int, optional) –

    Deprecated since version 2.15: Alias for depth.

Returns:

One row per leaf node, with the requested columns.

Return type:

pandas.DataFrame

Raises:
  • ImportError – If pandas is not installed.

  • ValueError – If an unknown column is requested, or if depth and one of its aliases are given conflicting values.

to_igraph(*, module_attribute: str | None = 'infomap_module', path_attribute: str | None = 'infomap_path', include_hierarchy: bool = True, flow_attribute: str | None = 'flow') igraph.Graph

Build a python-igraph graph of the partitioned network.

Equivalent to infomap.to_igraph(); see it for the parameters and the attribute scheme.

Returns:

Directed when the partitioned network is directed, else undirected.

Return type:

igraph.Graph

to_networkx(*, module_attribute: str | None = 'infomap_module', path_attribute: str | None = 'infomap_path', include_hierarchy: bool = True, flow_attribute: str | None = 'flow') networkx.Graph

Build a NetworkX graph of the partitioned network.

Equivalent to infomap.to_networkx(); see it for the parameters and the attribute scheme.

Returns:

DiGraph when the partitioned network is directed, else Graph.

Return type:

networkx.Graph or networkx.DiGraph

to_series() pandas.Series

Return the result’s scalar metrics as a pandas.Series.

The pandas-native form of summary(): a one-row record indexed by metric name, so a sweep collects into one row per run with

pandas.DataFrame([result.to_series() for result in results])

Like summary(), this reads only the eager scalars, so it stays valid after the bound engine re-runs.

Returns:

The summary() mapping as a Series indexed by metric name.

Return type:

pandas.Series

Raises:

ImportError – If pandas is not installed. Install it with python -m pip install "infomap[pandas]".

See also

summary

the same record as a plain dict.

to_dataframe

the per-node table for a single result.

tree(depth: int = 1, *, states: bool = False) Iterator[InfomapIterator | InfomapIteratorPhysical]

Iterate the hierarchical tree, modules and leaf nodes alike, depth first from the root.

Equivalent to the legacy Infomap.get_tree(depth, states). For a higher-order (multilayer/memory) network the physical tree is used unless states is requested, mirroring the legacy semantics.

Parameters:
  • depth (int, optional) – The module level reported by iterator.module_id. 1 (default) is the top (coarsest) level; -1 the bottom (finest).

  • states (bool, optional) – Iterate over state nodes when True, physical nodes when False (the default).

Returns:

Yields each node in the tree (the live InfomapIterator / InfomapIteratorPhysical positions), depth first from the root. The iterator is generation-guarded: consuming it after the bound engine re-runs raises instead of walking a rebuilt C++ tree.

Return type:

generator

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_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 codelength: float

The total (hierarchical) codelength.

property codelengths: tuple

The total (hierarchical) codelength for each trial.

property effective_num_leaf_modules: float

The flow-weighted effective number of leaf modules.

Measured as the perplexity of the leaf-module flow distribution. Unlike the eager scalar properties, this is computed lazily on first access (see effective_num_modules()), so it can raise StaleResultError if the Infomap has re-run since.

property effective_num_top_modules: float

The flow-weighted effective number of top modules.

Measured as the perplexity of the top-module flow distribution. Unlike the eager scalar properties, this is computed lazily on first access (see effective_num_modules()), so it can raise StaleResultError if the Infomap has re-run since.

property elapsed_time: float

The elapsed run time in seconds.

property entropy_rate: float

The entropy rate of the network.

property have_memory: bool

True for multilayer and memory networks.

property index_codelength: float

The two-level index codelength.

property max_depth: int

Alias of num_levels.

property meta_codelength: float

The meta codelength (meta entropy times metadata rate).

property meta_entropy: float

The meta entropy (unweighted by the metadata rate).

property module_codelength: float

The total codelength of the modules.

property names: dict[int, str]

All node names, as {node_id: name}.

Maps each internal node_id to the label of the input node. It is populated only when the input labels are not already the integer ids – for a graph whose nodes are integers (contiguous or not) the ids are the labels, so this is empty and modules() is keyed by those integers directly. The result.names.get(nid, nid) idiom therefore recovers labels for both cases. Returns a copy; mutating it does not affect the Result.

property num_leaf_modules: int

The number of leaf modules (bottom modules containing leaf nodes).

property num_levels: int

The max depth of the hierarchical tree.

The number of links.

property num_nodes: int

The number of (state) nodes.

property num_non_trivial_top_modules: int

The number of non-trivial top modules (size not 1 or all).

property num_physical_nodes: int

The number of physical nodes.

Equals num_nodes for a first-order network; for a higher-order (multilayer/memory) network it counts the distinct physical nodes behind the state nodes. Captured eagerly, so it stays valid after a re-run.

property num_top_modules: int

The number of top modules in the tree.

property one_level_codelength: float

The one-level codelength.

property relative_codelength_savings: float

The relative codelength savings 1 - L / L_1.

property state_names: dict[int, str]

All state-node names, as {state_id: name}.

Returns a copy; mutating it does not affect the Result.

Populated for higher-order (state/memory) networks whose *States section names the state nodes; empty otherwise. Physical node names are available separately via names.

TreeNode is the lightweight, immutable per-node view yielded by Result.nodes().

class infomap.TreeNode(*, node_id: int, state_id: int, module_id: int, flow: float, depth: int, layer_id: int, child_index: int, modular_centrality: float, path: tuple[int, ...], name: str | int, state_name: str | int)

A lightweight, immutable view over a single leaf node of a Result.

Yielded by Result.nodes(). A plain Python object: attribute access reads from the snapshot data the Result already materialized, without touching the underlying C++ engine, so it stays valid after a re-run.

node_id

The physical node id.

Type:

int

state_id

The state node id. Equals node_id for first-order networks.

Type:

int

module_id

The module id at the depth level the nodes were requested for.

Type:

int

flow

The node flow (the fraction of flow the node receives).

Type:

float

depth

The depth of the node in the tree (number of levels below the root; equals len(path)).

Type:

int

layer_id

The layer id for multilayer networks, otherwise 0.

Type:

int

child_index

The zero-based index of the node among its parent module’s children.

Type:

int

modular_centrality

A flow-based centrality score of the node within its parent module.

Type:

float

path

The tree path from the root as a tuple of one-based child indices (the colon-separated path in tree output files).

Type:

tuple of int

name

The physical node name, or node_id if the node is unnamed.

Type:

str or int

state_name

The state-node name for higher-order networks, falling back to name when no state name is set.

Type:

str or int