External algorithm adapters

pySpainMobility prepares and validates mobility flows obtained through Mobility and geographic correspondences from Zones. These adapters pass its network results to external projects:

  • SciPy provides the sparse matrix representation used by the base package.

  • NetworkX provides graph algorithms and graph objects through an optional adapter.

  • Infomap provides the community detection algorithm through an optional adapter.

NetworkX and Infomap are installed separately when their algorithms are needed. The small network used below is the one built in Network examples.

NetworkX

pip install 'pyspainmobility[network]'
from pyspainmobility.network.integrations import to_networkx

graph = to_networkx(network)
print(graph.number_of_nodes(), graph.number_of_edges())  # 2 2
print(graph["A"]["B"]["weight"])  # 5.0

The graph preserves direction, weights and isolated nodes. Zone geometries are not attached automatically; obtain them through Zones.get_zone_geodataframe(). Weights such as trip counts represent flow strength. Check the chosen NetworkX algorithm’s weight interpretation, especially when it expects path distances.

pyspainmobility.network.integrations.networkx.to_networkx(network: SparseMobilityNetwork, *, edge_attribute: str = 'weight') → Any[source]

Convert a network to a weighted NetworkX graph preserving direction.

NetworkX is imported only here, so installing pySpainMobility for sparse network work does not pull in a graph-object dependency. Install the optional adapter with pip install pyspainmobility[network].

Parameters:
  • network (SparseMobilityNetwork) – Network to convert, preserving zone IDs, edge weights and isolates.

  • edge_attribute (str) – Attribute storing each edge’s weight. Default is 'weight'.

Returns:

Graph matching the source direction, with the flow audit in graph.graph['pyspainmobility_audit']. Geographic node attributes must be attached separately using data from Zones.

Return type:

networkx.Graph or networkx.DiGraph

Infomap

pip install 'pyspainmobility[infomap]'
from pyspainmobility.network.integrations import run_infomap

partition = run_infomap(network, seed=123, num_trials=10)
print(partition.communities())

Infomap assigns nodes to flow-based communities, which can cross administrative boundaries. The adapter records the seed, algorithm version, options and input network fingerprint. Community labels identify modules in that run; matching numeric labels across runs does not establish that the communities are the same.

pyspainmobility.network.integrations.infomap.run_infomap(network: SparseMobilityNetwork, *, seed: int = 123, num_trials: int = 1, two_level: bool = False, markov_time: float | None = None, **options: object) → CommunityPartition[source]

Run Infomap and return a backend-neutral, auditable partition.

OD weights are interpreted by Infomap as edge weights for its random-walk flow model; they are not themselves the resulting flow values. seed and num_trials are retained in the returned provenance to make stochastic optimisation repeatable. The network direction is fixed by the canonical mobility contract and cannot be overridden here.

Parameters:
  • network (SparseMobilityNetwork) – Mobility network supplied to Infomap.

  • seed (int) – Infomap’s random seed. Default is 123.

  • num_trials (int) – Number of optimization trials. Must be positive; default is 1.

  • two_level (bool) – Restrict the partition to two levels when True. Default is False.

  • markov_time (float, optional) – Positive Infomap Markov time controlling the flow model’s scale.

  • **options – Additional Infomap keyword options. Direction and flow-model overrides are rejected to preserve the source network’s interpretation.

Returns:

Zone-to-module assignments, module hierarchy, algorithm metrics and recorded run parameters. communities() groups zone IDs by module.

Return type:

CommunityPartition

For direct use of Infomap’s Python network object:

pyspainmobility.network.integrations.infomap.to_infomap(network: SparseMobilityNetwork) → Any[source]

Create a weighted Infomap network directly from its CSR matrix.

The adapter passes the canonical zone IDs as Infomap node names, including explicit isolates. No edge-table or NetworkX materialisation is involved.

Parameters:

network (SparseMobilityNetwork) – Network to convert, preserving its direction, weights and zone IDs.

Returns:

Infomap’s native network object, ready for use with its Python API.

Return type:

infomap.Network

class pyspainmobility.network.model.CommunityPartition(node_index: ~pyspainmobility.network.model.NodeIndex, assignments: ~typing.Mapping[str, int], hierarchy: ~typing.Mapping[str, ~typing.Tuple[int, ...]], algorithm: str, algorithm_version: str | None, parameters: ~typing.Mapping[str, object], network_fingerprint: str, algorithm_metrics: ~typing.Mapping[str, object] = <factory>)[source]

A reproducible community assignment over one NodeIndex.

Community labels are algorithm-specific identifiers: callers should use membership relations rather than compare their numeric values across runs. hierarchy stores the complete module path supplied by a multilevel algorithm; its first item is the corresponding top-level assignment.

property codelength: float | None

Infomap code length, when supplied by that adapter.

property num_top_modules: int | None

Infomap top-level module count, when supplied by that adapter.

module_of(node_id: object) → int[source]

Return the algorithm’s top-level module for node_id.

communities() → Dict[int, frozenset[str]][source]

Group node IDs by top-level module without assuming label order.