Network

Network is the first-class input builder. Construct it from a graph library with a from_* constructor, or build it incrementally with the add_* verbs. Then partition it with infomap.run() or Network.run().

class infomap.Network(core: Core | None = None)

Bases: _NetworkWritersMixin

A first-class Infomap network input builder.

Build a network with the fluent add_*/set_* verbs (each returns self), then run it via run() or the functional infomap.run(). Both return an immutable Result.

Network is an in-memory builder: it runs silently and does not write output files (its engine is created with --silent --no-file-output, and that cannot be turned off per run). Read results off the returned Result. If you need Infomap to write .tree/.clu output files, use Infomap instead.

Examples

Build a small network and run it directly:

>>> from infomap import Network
>>> net = (
...     Network()
...     .add_link(1, 2)
...     .add_link(1, 3)
...     .add_link(2, 3)
...     .add_link(3, 4)
...     .add_link(4, 5)
...     .add_link(4, 6)
...     .add_link(5, 6)
... )
>>> result = net.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

A Network can also be handed to infomap.run():

>>> from infomap import run
>>> result = run(net)
>>> result.num_top_modules
2
Parameters:

core (optional) – Internal engine handle to build onto. If None, a default silent, no-file-output Core is created and owned by this Network. When composed by infomap.Infomap, the shared, options-configured Core is passed in.

classmethod from_edge_index(edge_index: Any, *, edge_weight: Any = None, num_nodes: int | None = None, directed: bool = True, node_labels: Any = None, node_ids: Any = <unset>) → Network

Build a Network from a PyG-style edge index.

Loads edge_index via the same adapter Infomap.add_edge_index() uses. The {internal_id: label} mapping is stored on node_id_to_label.

node_labels gives the nodes external labels, one per node index; without it the indices are the node ids.

Deprecated since version 2.16: node_ids is the pre-2.16 spelling of node_labels; it emits a DeprecationWarning and leaves in 3.0.

directed defaults to True: a PyG edge_index is directed by convention – each column is a source -> target edge, and undirected graphs store both directions explicitly. This per-format default differs across the constructors – from_networkx() and from_igraph() infer directedness from the graph, while from_scipy_sparse_matrix() defaults to directed=False.

The edge_weight parameter – a 1-D array with one value per edge, or None for unit weights – matches PyTorch Geometric’s edge_weight name. Each sibling constructor names its weight parameter after its own source library, so the spelling differs by design: from_networkx() weight, from_igraph() edge_weights / vertex_weights, from_scipy_sparse_matrix() weighted.

classmethod from_file(path: str | PathLike[str], *, accumulate: bool = True) → Network

Build a Network by reading a network file.

Parameters:
  • path (str or os.PathLike) – Path to an Infomap-readable network file.

  • accumulate (bool, optional) – Accumulate onto already added nodes and links. Default True.

classmethod from_igraph(g: igraph.Graph, *, edge_weights: Any = None, vertex_weights: Any = None, node_id_attribute: str = 'node_id', layer_id_attribute: str = 'layer_id', multilayer_inter_intra_format: bool = True, meta_attribute: str | None = None, node_id: str | None = <unset>, layer_id: str | None = <unset>) → Network

Build a Network from a python-igraph graph.

Loads g via the same adapter Infomap.add_igraph_graph() uses. The {internal_id: label} mapping is stored on node_id_to_label. Pass meta_attribute to use a vertex attribute as Infomap metadata (values are encoded to integers, so string categories work).

node_id_attribute names the vertex attribute holding the physical node id (implying a state network) and layer_id_attribute the one holding the layer id (implying a multilayer network).

Deprecated since version 2.16: node_id and layer_id are the pre-2.16 spellings of node_id_attribute and layer_id_attribute; they emit a DeprecationWarning and leave in 3.0.

The edge_weights / vertex_weights parameters match python-igraph’s own Graph.community_infomap(edge_weights, vertex_weights) names. Each sibling constructor names its weight parameter after its own source library, so the spelling differs by design: from_networkx() weight, from_scipy_sparse_matrix() weighted, from_edge_index() edge_weight.

classmethod from_networkx(g: networkx.Graph, *, weight: str | None = 'weight', node_id_attribute: str = 'node_id', layer_id_attribute: str = 'layer_id', multilayer_inter_intra_format: bool = True, meta_attribute: str | None = None, node_id: str | None = <unset>, layer_id: str | None = <unset>) → Network

Build a Network from a NetworkX graph.

Loads g via the same adapter Infomap.add_networkx_graph() uses. The {internal_id: label} mapping is stored on node_id_to_label. Pass meta_attribute to use a node attribute as Infomap metadata (values are encoded to integers, so string categories work).

node_id_attribute names the node attribute holding the physical node id (implying a state network) and layer_id_attribute the one holding the layer id (implying a multilayer network) – the *_attribute spelling meta_attribute already uses.

Deprecated since version 2.16: node_id and layer_id are the pre-2.16 spellings of node_id_attribute and layer_id_attribute; they emit a DeprecationWarning and leave in 3.0. (node_id read as the singular of node_ids, a different parameter.)

The weight parameter – the edge-data key to read, or None to treat every edge as unit weight – matches networkx’s own weight argument. Each sibling constructor names its weight parameter after its own source library, so the spelling differs by design: from_igraph() edge_weights / vertex_weights, from_scipy_sparse_matrix() weighted, from_edge_index() edge_weight.

classmethod from_scipy_sparse_matrix(A: Any, *, directed: bool = False, weighted: bool = True, node_labels: Any = None, node_ids: Any = <unset>) → Network

Build a Network from a SciPy sparse adjacency matrix.

Loads A via the same adapter Infomap.add_scipy_sparse_matrix() uses. The {internal_id: label} mapping is stored on node_id_to_label.

node_labels gives the matrix rows external labels, one per row; without it the row indices are the node ids.

Deprecated since version 2.16: node_ids is the pre-2.16 spelling of node_labels; it emits a DeprecationWarning and leaves in 3.0. (It read as the plural of node_id on the graph constructors, which names an attribute rather than a sequence.)

directed defaults to False: a symmetric adjacency is the common undirected case, so A[i, j] and A[j, i] are folded together. This per-format default differs across the constructors – from_networkx() and from_igraph() infer directedness from the graph, while from_edge_index() defaults to directed=True.

weighted – use the matrix values as weights, else treat every stored entry as weight 1 – is a local name: scipy.sparse.csgraph has no such flag. Each sibling constructor names its weight parameter after its own source library, so the spelling differs by design: from_networkx() weight, from_igraph() edge_weights / vertex_weights, from_edge_index() edge_weight.

Add a link.

Parameters:
  • source_id (int)

  • target_id (int)

  • weight (float, optional)

Add several links.

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.

Add an inter-layer link.

Parameters:
  • source_layer_id (int)

  • node_id (int)

  • target_layer_id (int)

  • weight (float, optional)

Add several inter-layer 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.

Parameters:
  • layer_id (int)

  • source_node_id (int)

  • target_node_id (int)

  • weight (float, optional)

Add several intra-layer 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.

Parameters:

Add several multilayer 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_node(node_id: int, name: str | None = None, teleportation_weight: float | None = None) → Network

Add a node.

Parameters:
  • node_id (int)

  • name (str, optional)

  • teleportation_weight (float, optional) – Node weight, used by to_nodes teleportation and by use_node_weights_as_flow. A weight read later from a file for the same node replaces it.

add_nodes(nodes: Any) → Network

Add nodes.

Parameters:

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

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

Add a state node.

Parameters:
  • state_id (int)

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

  • name (str, optional)

add_state_nodes(state_nodes: Any) → Network

Add state nodes.

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

read_file(filename: str | PathLike[str], accumulate: bool = True) → Network

Read network data from file.

Parameters:
  • filename (str or os.PathLike)

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

Parameters:
  • source_id (int)

  • target_id (int)

Remove several links.

Parameters:

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

run(*, 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: Mapping[Any, Any] | None=None, **overrides: Any) → Result

Run Infomap on this network and return a Result.

This is a thin convenience wrapper: net.run(**kw) is equivalent to infomap.run(net, **kw), the canonical entry point. It accepts the same keywords.

Parameters:
  • options (Options, mapping, or None, optional) – Configuration rendered to Infomap CLI flags for this run.

  • seed (optional) – The five common-tier engine options, accepted directly here to match infomap.run() and infomap.Infomap.run(). A supplied value overrides the options carrier.

  • num_trials (optional) – The five common-tier engine options, accepted directly here to match infomap.run() and infomap.Infomap.run(). A supplied value overrides the options carrier.

  • two_level (optional) – The five common-tier engine options, accepted directly here to match infomap.run() and infomap.Infomap.run(). A supplied value overrides the options carrier.

  • directed (optional) – The five common-tier engine options, accepted directly here to match infomap.run() and infomap.Infomap.run(). A supplied value overrides the options carrier.

  • markov_time (optional) – The five common-tier engine options, accepted directly here to match infomap.run() and infomap.Infomap.run(). A supplied value overrides the options carrier.

  • args (str, optional) – Raw Infomap arguments prepended before the rendered options.

  • initial_partition (mapping, optional) – Initial module assignment for this run only, keyed by internal node id ({node_or_state_id: module_id}) or, for a multilayer network, {(layer_id, node_id): module_id}. The internal ids are the ones you built the network with (the values of node_id_to_label).

  • **overrides – Any other Infomap engine option, as a keyword argument, forwarded to Options and matching infomap.run(). Convenient for a one-off; for a reusable or validated configuration prefer options=Options(...), the canonical carrier and full reference.

Returns:

An immutable snapshot of the run, bound to this Network.

Return type:

Result

Notes

A Network engine is silent for its whole lifetime; silent=False cannot re-enable the engine log here and warns instead. For the log, run through the stateful Infomap (constructed with silent=False) or pass the input directly to infomap.run().

set_bipartite_start_id(start_id: int) → Network

Set the bipartite start id, returning self for fluent chaining.

The chainable form of the bipartite_start_id setter, so a bipartite network can be built in a single expression alongside the add_* verbs.

set_meta_data(node_id: Any, meta_category: int | None = None) → Network

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

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.

  • 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) → Network

Set the name of a node.

Parameters:
set_names(names: Any) → Network

Set names to several nodes at once.

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

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)

property bipartite_start_id: int

Get or set the bipartite start id.

Returns:

The node id where the second node type starts.

Return type:

int

property network: Any

The underlying SWIG state network.

Exposed so the graph adapters (which reach for infomap.network.add_multilayer_node / add_multilayer_state_link) work identically when building onto a Network or an Infomap.

An escape hatch, not the supported build surface. Mutating through it bypasses this class, so the run’s input file identity is not dropped and the published artifacts keep naming a file that no longer describes the network (#1026). Build with the add_* and remove_* methods instead. The multilayer adapter path noted above is the one place the package itself still goes through the handle; #1026 records it.

node_id_to_label: dict[int, Any]

{internal_id: label} mapping populated by the graph-library constructors (from_networkx/from_igraph/from_scipy_sparse_matrix/ from_edge_index). Empty on a manually built or file-loaded Network, mirroring Infomap, so the attribute is always present.

The number of links.

Returns:

The number of links.

Return type:

int

property num_nodes: int

The number of state nodes if a higher-order network, else physical.

Returns:

The number of nodes.

Return type:

int