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:
_NetworkWritersMixinA first-class Infomap network input builder.
Build a network with the fluent
add_*/set_*verbs (each returnsself), then run it viarun()or the functionalinfomap.run(). Both return an immutableResult.Networkis 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 returnedResult. If you need Infomap to write.tree/.cluoutput files, useInfomapinstead.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
Networkcan also be handed toinfomap.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-outputCoreis created and owned by thisNetwork. When composed byinfomap.Infomap, the shared, options-configuredCoreis 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
Networkfrom a PyG-style edge index.Loads
edge_indexvia the same adapterInfomap.add_edge_index()uses. The{internal_id: label}mapping is stored onnode_id_to_label.node_labelsgives the nodes external labels, one per node index; without it the indices are the node ids.Deprecated since version 2.16:
node_idsis the pre-2.16 spelling ofnode_labels; it emits aDeprecationWarningand leaves in 3.0.directeddefaults toTrue: a PyGedge_indexis directed by convention – each column is asource -> targetedge, and undirected graphs store both directions explicitly. This per-format default differs across the constructors –from_networkx()andfrom_igraph()infer directedness from the graph, whilefrom_scipy_sparse_matrix()defaults todirected=False.The
edge_weightparameter – a 1-D array with one value per edge, orNonefor unit weights – matches PyTorch Geometric’sedge_weightname. 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
Networkby 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
Networkfrom a python-igraph graph.Loads
gvia the same adapterInfomap.add_igraph_graph()uses. The{internal_id: label}mapping is stored onnode_id_to_label. Passmeta_attributeto use a vertex attribute as Infomap metadata (values are encoded to integers, so string categories work).node_id_attributenames the vertex attribute holding the physical node id (implying a state network) andlayer_id_attributethe one holding the layer id (implying a multilayer network).Deprecated since version 2.16:
node_idandlayer_idare the pre-2.16 spellings ofnode_id_attributeandlayer_id_attribute; they emit aDeprecationWarningand leave in 3.0.The
edge_weights/vertex_weightsparameters match python-igraph’s ownGraph.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
Networkfrom a NetworkX graph.Loads
gvia the same adapterInfomap.add_networkx_graph()uses. The{internal_id: label}mapping is stored onnode_id_to_label. Passmeta_attributeto use a node attribute as Infomap metadata (values are encoded to integers, so string categories work).node_id_attributenames the node attribute holding the physical node id (implying a state network) andlayer_id_attributethe one holding the layer id (implying a multilayer network) – the*_attributespellingmeta_attributealready uses.Deprecated since version 2.16:
node_idandlayer_idare the pre-2.16 spellings ofnode_id_attributeandlayer_id_attribute; they emit aDeprecationWarningand leave in 3.0. (node_idread as the singular ofnode_ids, a different parameter.)The
weightparameter – the edge-data key to read, orNoneto treat every edge as unit weight – matches networkx’s ownweightargument. 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
Networkfrom a SciPy sparse adjacency matrix.Loads
Avia the same adapterInfomap.add_scipy_sparse_matrix()uses. The{internal_id: label}mapping is stored onnode_id_to_label.node_labelsgives the matrix rows external labels, one per row; without it the row indices are the node ids.Deprecated since version 2.16:
node_idsis the pre-2.16 spelling ofnode_labels; it emits aDeprecationWarningand leaves in 3.0. (It read as the plural ofnode_idon the graph constructors, which names an attribute rather than a sequence.)directeddefaults toFalse: a symmetric adjacency is the common undirected case, soA[i, j]andA[j, i]are folded together. This per-format default differs across the constructors –from_networkx()andfrom_igraph()infer directedness from the graph, whilefrom_edge_index()defaults todirected=True.weighted– use the matrix values as weights, else treat every stored entry as weight 1 – is a local name:scipy.sparse.csgraphhas 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_links(links: Any) Network¶
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_multilayer_inter_link(source_layer_id: int, node_id: int, target_layer_id: int, weight: float = 1.0) Network¶
Add an inter-layer link.
- add_multilayer_inter_links(links: Any) Network¶
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_multilayer_intra_link(layer_id: int, source_node_id: int, target_node_id: int, weight: float = 1.0) Network¶
Add an intra-layer link.
- add_multilayer_intra_links(links: Any) Network¶
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_multilayer_link(source_multilayer_node: Any, target_multilayer_node: Any, weight: float = 1.0) Network¶
Add a multilayer link.
- Parameters:
source_multilayer_node (tuple of int, or MultilayerNode) –
(layer_id, node_id).target_multilayer_node (tuple of int, or MultilayerNode) –
(layer_id, node_id).weight (float, optional)
- add_multilayer_links(links: Any) Network¶
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.
- 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_links(links: Any) Network¶
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 toinfomap.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()andinfomap.Infomap.run(). A supplied value overrides theoptionscarrier.num_trials (optional) – The five common-tier engine options, accepted directly here to match
infomap.run()andinfomap.Infomap.run(). A supplied value overrides theoptionscarrier.two_level (optional) – The five common-tier engine options, accepted directly here to match
infomap.run()andinfomap.Infomap.run(). A supplied value overrides theoptionscarrier.directed (optional) – The five common-tier engine options, accepted directly here to match
infomap.run()andinfomap.Infomap.run(). A supplied value overrides theoptionscarrier.markov_time (optional) – The five common-tier engine options, accepted directly here to match
infomap.run()andinfomap.Infomap.run(). A supplied value overrides theoptionscarrier.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 ofnode_id_to_label).**overrides – Any other Infomap engine option, as a keyword argument, forwarded to
Optionsand matchinginfomap.run(). Convenient for a one-off; for a reusable or validated configuration preferoptions=Options(...), the canonical carrier and full reference.
- Returns:
An immutable snapshot of the run, bound to this
Network.- Return type:
Notes
A
Networkengine is silent for its whole lifetime;silent=Falsecannot re-enable the engine log here and warns instead. For the log, run through the statefulInfomap(constructed withsilent=False) or pass the input directly toinfomap.run().
- set_bipartite_start_id(start_id: int) Network¶
Set the bipartite start id, returning
selffor fluent chaining.The chainable form of the
bipartite_start_idsetter, so a bipartite network can be built in a single expression alongside theadd_*verbs.
- set_meta_data(node_id: Any, meta_category: int | None = None) Network¶
Set integer metadata for one node, or for many at once.
- 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
filenameis overwritten.See also
- 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
filenameis overwritten.See also
- 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:
- 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 aNetworkor anInfomap.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_*andremove_*methods instead. The multilayer adapter path noted above is the one place the package itself still goes through the handle; #1026 records it.