#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .. import GraphView, _check_props
from .. centrality import pagerank
from . util import *
import numpy as np
from types import SimpleNamespace
from . base_states import *
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_inference as libinference")
[docs]
@entropy_state_signature
class MapEquationState(CLabelState, MCMCState, MultiflipMCMCState,
MultilevelMCMCState, GibbsMCMCState, DrawBlockState):
r"""Obtain the partition of a network according to the map equation.
.. warning::
Do not use this approach in the analysis of networks without
understanding the consequences. This algorithm is included only for
comparison purposes. In general, the inference-based approaches based on
:class:`~graph_tool.inference.BlockState`,
:class:`~graph_tool.inference.NestedBlockState`, and
:class:`~graph_tool.inference.PPBlockState` should be
universally preferred [peixoto-descriptive-2023]_.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be partitioned.
b : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Initial partition. If not supplied, a partition into a single group will
be used.
eweight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights, used to compute the flows if ``vflow`` and ``eflow`` are
not given.
alpha : ``float`` (optional, default: ``0.15``)
Teleportation probability of the random walk on directed graphs.
vflow : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Fraction of time the random walk spends on each vertex. If given,
``eflow`` must be given as well, and ``eweight`` and ``alpha`` are
ignored.
eflow : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Fraction of the steps of the random walk along each edge, in the
direction of the edge if the graph is directed, or in each of the two
directions if it is undirected.
clabel : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Constraint labels on the vertices. If supplied, vertices with different
label values will not be clustered in the same group.
entropy_args : ``dict`` (optional, default: ``{}``)
Override default arguments for :meth:`~MapEquationState.entropy()`
method and related operations.
See Also
--------
ModularityState: Modularity maximization
NormCutState: Normalized cut minimization
BlockState: Stochastic block model
Notes
-----
The map equation [rosvall-maps-2008]_ is the description length, in bits,
of a `random walk <https://en.wikipedia.org/wiki/Random_walk>`_ on the
network, when the vertices are encoded with a two-level code that uses a
separate codebook for each group, together with an index codebook for the
transitions between groups. For a partition :math:`\boldsymbol b`, it reads
.. math::
L(\boldsymbol b) = q\log_2 q - \sum_r q^{\curvearrowleft}_r\log_2 q^{\curvearrowleft}_r
- \sum_r q^{\curvearrowright}_r\log_2 q^{\curvearrowright}_r
- \sum_v p_v\log_2 p_v
+ \sum_r (q^{\curvearrowright}_r + p_r)\log_2 (q^{\curvearrowright}_r + p_r),
where :math:`p_v` is the fraction of time the walk spends on vertex
:math:`v`, :math:`p_r=\sum_{v}p_v\delta_{b_v,r}`, :math:`q^{\curvearrowright}_r`
and :math:`q^{\curvearrowleft}_r` are the flows exiting and entering group
:math:`r` along the edges, and :math:`q=\sum_r q^{\curvearrowleft}_r`.
For undirected graphs, the walk is the stationary unbiased random walk,
with :math:`p_v = k_v/2W` and flow :math:`w_{e}/2W` along each direction
of edge :math:`e`, where :math:`w_e` is the edge weight, :math:`k_v` the
weighted degree, and :math:`W` the total edge weight. For directed
graphs, the walk teleports with probability ``alpha`` to a random vertex
(or with probability one, from vertices without out-edges), and
:math:`p_v` is its stationary distribution, given by
:func:`~graph_tool.centrality.pagerank`. The teleportation steps are not
encoded [lambiotte-ranking-2012]_: the edge flows are those of one
further step without teleportation,
:math:`f_{uv} \propto p_u w_{uv}/k^{\text{out}}_u`, normalized to sum to
one, and the vertex flows are replaced by the flows entering each vertex
along the edges, :math:`p_v = \sum_u f_{uv}`. Other flows can be given
with ``vflow`` and ``eflow``.
Only the two-level map equation is implemented. Its minimization is done
with the generic Markov chain Monte Carlo algorithms (see
:meth:`~MapEquationState.multiflip_mcmc_sweep` and
:meth:`~MapEquationState.multilevel_mcmc_sweep`), with ``beta=np.inf``
for a greedy optimization, rather than with the Infomap algorithm of
[rosvall-maps-2008]_.
Examples
--------
.. testcode::
:hide:
gt.seed_rng(42)
np.random.seed(42)
>>> g = gt.collection.data["football"]
>>> state = gt.MapEquationState(g)
>>> for i in range(10):
... ret = state.multiflip_mcmc_sweep(beta=np.inf, niter=10)
>>> print(state.get_B(), state.entropy())
12 5.44665...
>>> state.draw(pos=g.vp.pos, output="football-map-equation.svg")
<...>
.. figure:: football-map-equation.svg
:align: center
:width: 60%
Partition of the network of American college football games obtained
by minimizing the map equation. The vertex colors indicate the
groups.
References
----------
.. [rosvall-maps-2008] Martin Rosvall and Carl T. Bergstrom, "Maps of
random walks on complex networks reveal community structure",
Proc. Natl. Acad. Sci. USA 105, 1118-1123 (2008),
:doi:`10.1073/pnas.0706851105`, :arxiv:`0707.0609`
.. [lambiotte-ranking-2012] Renaud Lambiotte and Martin Rosvall, "Ranking
and clustering of nodes in networks with smart teleportation",
Phys. Rev. E 85, 056107 (2012), :doi:`10.1103/PhysRevE.85.056107`,
:arxiv:`1112.5252`
.. [peixoto-descriptive-2023] Tiago P. Peixoto, "Descriptive vs.
inferential community detection in networks: pitfalls, myths and
half-truths", Elements in the Structure and Dynamics of Complex Networks,
Cambridge University Press (2023), :doi:`10.1017/9781009118897`
:arxiv:`2112.00183`
"""
@kwargs_wrap
def __init__(self, g, b=None, eweight=None, alpha=0.15, vflow=None,
eflow=None, clabel=None, entropy_args={}, **kwargs):
EntropyState.__init__(self, entropy_args=entropy_args)
CLabelState.__init__(self, g=g, b=b, clabel=clabel,
pclabel=kw_pop(kwargs, "pclabel", None))
self.g = g
self.alpha = alpha
if eweight is not None:
eweight = g.own_property(eweight)
self.eweight = eweight
if (vflow is None) != (eflow is None):
raise ValueError("Either both or none of vflow and eflow must be given")
if vflow is None:
vflow, eflow = self._get_flows(g, eweight, alpha)
else:
vflow = g.own_property(vflow).copy("double")
eflow = g.own_property(eflow).copy("double")
self.vflow = vflow
self.eflow = eflow
# The C++ state sees the graph as directed, with the flow along
# (eflow) and against (rflow) the direction of each edge.
if g.is_directed():
rflow = g.new_ep("double")
else:
rflow = eflow
u = GraphView(g, directed=True)
self._cstate = SimpleNamespace(g=u, b=self.b, clabel=self.clabel,
pclabel=self.pclabel,
vflow=u.own_property(vflow),
eflow=u.own_property(eflow),
rflow=u.own_property(rflow))
self._state = libinference.make_map_equation_state(self._cstate)
@staticmethod
def _get_flows(g, eweight, alpha):
if eweight is None:
w = g.new_ep("double", 1)
else:
w = eweight.copy("double")
if not g.is_directed():
u = GraphView(g, directed=False)
k = u.degree_property_map("total", weight=w)
W = w.fa.sum()
vflow = k.copy("double")
if W > 0:
vflow.fa /= 2 * W
eflow = w.copy()
if W > 0:
eflow.fa /= 2 * W
return vflow, eflow
p = pagerank(g, damping=1 - alpha, weight=w)
kout = g.degree_property_map("out", weight=w)
edges = g.get_edges([g.edge_index])
s = edges[:,0]
eflow = g.new_ep("double")
eflow.a[edges[:,2]] = p.a[s] * w.a[edges[:,2]] / kout.a[s]
Z = eflow.fa.sum()
vflow = g.new_vp("double")
if Z > 0:
eflow.fa /= Z
vflow.a = np.bincount(edges[:,1], weights=eflow.a[edges[:,2]],
minlength=len(vflow.a))
return vflow, eflow
def __repr__(self):
return "<MapEquationState object with %d blocks, for graph %s, at 0x%x>" % \
(self.get_B(), str(self.g), id(self))
[docs]
def get_B(self):
r"Returns the total number of blocks."
return len(np.unique(self.b.fa))
[docs]
def get_Be(self):
r"""Returns the effective number of blocks, defined as :math:`e^{H}`, with
:math:`H=-\sum_r\frac{n_r}{N}\ln \frac{n_r}{N}`, where :math:`n_r` is
the number of nodes in group :math:`r`.
"""
w = np.array(np.bincount(self.b.fa), dtype="double")
w = w[w>0]
w /= w.sum()
return np.exp(-(w*np.log(w)).sum())
@copy_state_wrap
def _entropy(self, **kwargs):
r"""Return the map equation, i.e. the description length of the random
walk in bits (see the class documentation)."""
return EntropyState._entropy_dispatch(**dict(locals(), **kwargs))