__init__.py 42.2 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
Tiago Peixoto's avatar
Tiago Peixoto committed
3
#
4 5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2019 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

21
"""
22 23
``graph_tool.centrality`` - Centrality measures
-----------------------------------------------
24 25

This module includes centrality-related algorithms.
26 27 28 29 30 31 32 33 34 35

Summary
+++++++

.. autosummary::
   :nosignatures:

   pagerank
   betweenness
   central_point_dominance
Tiago Peixoto's avatar
Tiago Peixoto committed
36
   closeness
37
   eigenvector
Tiago Peixoto's avatar
Tiago Peixoto committed
38
   katz
39
   hits
40
   eigentrust
41
   trust_transitivity
42 43 44

Contents
++++++++
45 46
"""

47 48
from __future__ import division, absolute_import, print_function

Tiago Peixoto's avatar
Tiago Peixoto committed
49
from .. dl_import import dl_import
50
dl_import("from . import libgraph_tool_centrality")
Tiago Peixoto's avatar
Tiago Peixoto committed
51

52
from .. import _prop, ungroup_vector_property, Vector_size_t
53
from .. topology import shortest_distance
Tiago Peixoto's avatar
Tiago Peixoto committed
54 55
import sys
import numpy
56
import numpy.linalg
Tiago Peixoto's avatar
Tiago Peixoto committed
57

Tiago Peixoto's avatar
Tiago Peixoto committed
58 59
__all__ = ["pagerank", "betweenness", "central_point_dominance", "closeness",
           "eigentrust", "eigenvector", "katz", "hits", "trust_transitivity"]
Tiago Peixoto's avatar
Tiago Peixoto committed
60

Tiago Peixoto's avatar
Tiago Peixoto committed
61

62 63
def pagerank(g, damping=0.85, pers=None, weight=None, prop=None, epsilon=1e-6,
             max_iter=None, ret_iter=False):
64
    r"""Calculate the PageRank of each vertex.
65 66 67

    Parameters
    ----------
68
    g : :class:`~graph_tool.Graph`
69
        Graph to be used.
70
    damping : float, optional (default: 0.85)
71
        Damping factor.
72
    pers : :class:`~graph_tool.VertexPropertyMap`, optional (default: None)
73 74
        Personalization vector. If omitted, a constant value of :math:`1/N`
        will be used.
75
    weight : :class:`~graph_tool.EdgePropertyMap`, optional (default: None)
76
        Edge weights. If omitted, a constant value of 1 will be used.
77
    prop : :class:`~graph_tool.VertexPropertyMap`, optional (default: None)
78 79
        Vertex property map to store the PageRank values. If supplied, it will
        be used uninitialized.
Tiago Peixoto's avatar
Tiago Peixoto committed
80
    epsilon : float, optional (default: 1e-6)
81 82 83 84 85 86 87 88 89
        Convergence condition. The iteration will stop if the total delta of all
        vertices are below this value.
    max_iter : int, optional (default: None)
        If supplied, this will limit the total number of iterations.
    ret_iter : bool, optional (default: False)
        If true, the total number of iterations is also returned.

    Returns
    -------
90
    pagerank : :class:`~graph_tool.VertexPropertyMap`
91
        A vertex property map containing the PageRank values.
92 93 94 95 96

    See Also
    --------
    betweenness: betweenness centrality
    eigentrust: eigentrust centrality
97
    eigenvector: eigenvector centrality
98
    hits: authority and hub centralities
99
    trust_transitivity: pervasive trust transitivity
100 101 102

    Notes
    -----
Tiago Peixoto's avatar
Tiago Peixoto committed
103 104
    The value of PageRank [pagerank-wikipedia]_ of vertex v, :math:`PR(v)`, is
    given iteratively by the relation:
105 106

    .. math::
107

108 109
        PR(v) = \frac{1-d}{N} + d \sum_{u \in \Gamma^{-}(v)}
                \frac{PR (u)}{d^{+}(u)}
110

111 112
    where :math:`\Gamma^{-}(v)` are the in-neighbors of v, :math:`d^{+}(u)` is
    the out-degree of u, and d is a damping factor.
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    If a personalization property :math:`p(v)` is given, the definition becomes:

    .. math::

        PR(v) = (1-d)p(v) + d \sum_{u \in \Gamma^{-}(v)}
                \frac{PR (u)}{d^{+}(u)}

    If edge weights are also given, the equation is then generalized to:

    .. math::

        PR(v) = (1-d)p(v) + d \sum_{u \in \Gamma^{-}(v)}
                \frac{PR (u) w_{u\to v}}{d^{+}(u)}

    where :math:`d^{+}(u)=\sum_{y}A_{u,y}w_{u\to y}` is redefined to be the sum
    of the weights of the out-going edges from u.

131 132 133 134
    If a node has out-degree zero, it is assumed to connect to every other node
    with a weight proportional to :math:`p(v)` or a constant if no
    personalization is given.

135
    The implemented algorithm progressively iterates the above equations, until
Tiago Peixoto's avatar
Tiago Peixoto committed
136
    it no longer changes, according to the parameter epsilon. It has a
137 138 139 140 141 142
    topology-dependent running time.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
143

Tiago Peixoto's avatar
Tiago Peixoto committed
144 145 146 147
    .. testsetup:: pagerank

       import matplotlib

148 149 150 151 152 153 154
    .. doctest:: pagerank

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> pr = gt.pagerank(g)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=pr,
       ...               vertex_size=gt.prop_to_size(pr, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
155 156
       ...               vorder=pr, vcmap=matplotlib.cm.gist_heat,
       ...               output="polblogs_pr.pdf")
157 158 159 160 161 162 163
       <...>

    .. testcode:: pagerank
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=pr,
                     vertex_size=gt.prop_to_size(pr, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
164 165
                     vorder=pr, vcmap=matplotlib.cm.gist_heat,
                     output="polblogs_pr.png")
166 167 168 169 170 171


    .. figure:: polblogs_pr.*
       :align: center

       PageRank values of the a political blogs network of [adamic-polblogs]_.
172 173 174

    Now with a personalization vector, and edge weights:

175 176 177 178 179 180 181 182 183
    .. doctest:: pagerank

       >>> d = g.degree_property_map("total")
       >>> periphery = d.a <= 2
       >>> p = g.new_vertex_property("double")
       >>> p.a[periphery] = 100
       >>> pr = gt.pagerank(g, pers=p)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=pr,
       ...               vertex_size=gt.prop_to_size(pr, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
184 185
       ...               vorder=pr, vcmap=matplotlib.cm.gist_heat,
       ...               output="polblogs_pr_pers.pdf")
186 187 188 189 190 191 192
       <...>

    .. testcode:: pagerank
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=pr,
                     vertex_size=gt.prop_to_size(pr, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
193
                     vcmap=matplotlib.cm.gist_heat,
194 195 196 197 198 199 200 201 202
                     vorder=pr, output="polblogs_pr_pers.png")


    .. figure:: polblogs_pr_pers.*
       :align: center

       Personalized PageRank values of the a political blogs network of
       [adamic-polblogs]_, where vertices with very low degree are given
       artificially high scores.
203 204 205

    References
    ----------
206 207
    .. [pagerank-wikipedia] http://en.wikipedia.org/wiki/Pagerank
    .. [lawrence-pagerank-1998] P. Lawrence, B. Sergey, M. Rajeev, W. Terry,
208
       "The pagerank citation ranking: Bringing order to the web", Technical
209
       report, Stanford University, 1998
210 211 212
    .. [Langville-survey-2005] A. N. Langville, C. D. Meyer, "A Survey of
       Eigenvector Methods for Web Information Retrieval", SIAM Review, vol. 47,
       no. 1, pp. 135-161, 2005, :DOI:`10.1137/S0036144503424786`
213 214 215
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
216 217
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
218
    if max_iter is None:
219
        max_iter = 0
Tiago Peixoto's avatar
Tiago Peixoto committed
220
    if prop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
221
        prop = g.new_vertex_property("double")
222 223
        N = len(prop.fa)
        prop.fa = pers.fa[:N] if pers is not None else 1. / g.num_vertices()
Tiago Peixoto's avatar
Tiago Peixoto committed
224
    ic = libgraph_tool_centrality.\
225 226 227
            get_pagerank(g._Graph__graph, _prop("v", g, prop),
                         _prop("v", g, pers), _prop("e", g, weight),
                         damping, epsilon, max_iter)
Tiago Peixoto's avatar
Tiago Peixoto committed
228 229 230 231 232
    if ret_iter:
        return prop, ic
    else:
        return prop

Tiago Peixoto's avatar
Tiago Peixoto committed
233

234 235
def betweenness(g, pivots=None, vprop=None, eprop=None, weight=None, norm=True):
    r"""Calculate the betweenness centrality for each vertex and edge.
236 237 238

    Parameters
    ----------
239
    g : :class:`~graph_tool.Graph`
240
        Graph to be used.
241 242 243 244 245
    pivots : list or :class:`~numpy.ndarray`, optional (default: None)
        If provided, the betweenness will be estimated using the vertices in
        this list as pivots. If the list contains all nodes (the default) the
        algorithm will be exact, and if the vertices are randomly chosen the
        result will be an unbiased estimator.
246
    vprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: None)
247
        Vertex property map to store the vertex betweenness values.
248
    eprop : :class:`~graph_tool.EdgePropertyMap`, optional (default: None)
249
        Edge property map to store the edge betweenness values.
250
    weight : :class:`~graph_tool.EdgePropertyMap`, optional (default: None)
251 252 253 254 255 256
        Edge property map corresponding to the weight value of each edge.
    norm : bool, optional (default: True)
        Whether or not the betweenness values should be normalized.

    Returns
    -------
Tiago Peixoto's avatar
Tiago Peixoto committed
257 258
    vertex_betweenness : A vertex property map with the vertex betweenness values.
    edge_betweenness : An edge property map with the edge betweenness values.
259 260 261 262 263 264

    See Also
    --------
    central_point_dominance: central point dominance of the graph
    pagerank: PageRank centrality
    eigentrust: eigentrust centrality
265
    eigenvector: eigenvector centrality
266
    hits: authority and hub centralities
267
    trust_transitivity: pervasive trust transitivity
268 269 270 271 272

    Notes
    -----
    Betweenness centrality of a vertex :math:`C_B(v)` is defined as,

273 274
    .. math::

275 276 277
        C_B(v)= \sum_{s \neq v \neq t \in V \atop s \neq t}
                \frac{\sigma_{st}(v)}{\sigma_{st}}

278 279 280 281 282
    where :math:`\sigma_{st}` is the number of shortest paths from s to t, and
    :math:`\sigma_{st}(v)` is the number of shortest paths from s to t that pass
    through a vertex :math:`v`. This may be normalised by dividing through the
    number of pairs of vertices not including v, which is :math:`(n-1)(n-2)/2`,
    for undirected graphs, or :math:`(n-1)(n-2)` for directed ones.
283

284
    The algorithm used here is defined in [brandes-faster-2001]_, and has a
285 286 287 288 289 290
    complexity of :math:`O(VE)` for unweighted graphs and :math:`O(VE +
    V(V+E)\log V)` for weighted graphs. The space complexity is :math:`O(VE)`.

    If the ``pivots`` parameter is given, the complexity will be instead
    :math:`O(PE)` for unweighted graphs and :math:`O(PE + P(V+E)\log V)` for
    weighted graphs, where :math:`P` is the number of pivot vertices.
291 292 293 294 295

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
296

Tiago Peixoto's avatar
Tiago Peixoto committed
297 298 299 300
    .. testsetup:: betweenness

       import matplotlib

301 302 303 304 305 306 307 308
    .. doctest:: betweenness

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> vp, ep = gt.betweenness(g)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=vp,
       ...               vertex_size=gt.prop_to_size(vp, mi=5, ma=15),
       ...               edge_pen_width=gt.prop_to_size(ep, mi=0.5, ma=5),
Tiago Peixoto's avatar
Tiago Peixoto committed
309
       ...               vcmap=matplotlib.cm.gist_heat,
310 311 312 313 314 315 316 317 318
       ...               vorder=vp, output="polblogs_betweenness.pdf")
       <...>

    .. testcode:: betweenness
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=vp,
                     vertex_size=gt.prop_to_size(vp, mi=5, ma=15),
                     edge_pen_width=gt.prop_to_size(ep, mi=0.5, ma=5),
Tiago Peixoto's avatar
Tiago Peixoto committed
319
                     vcmap=matplotlib.cm.gist_heat,
320 321 322 323 324 325 326
                     vorder=vp, output="polblogs_betweenness.png")


    .. figure:: polblogs_betweenness.*
       :align: center

       Betweenness values of the a political blogs network of [adamic-polblogs]_.
327 328 329

    References
    ----------
330 331
    .. [betweenness-wikipedia] http://en.wikipedia.org/wiki/Centrality#Betweenness_centrality
    .. [brandes-faster-2001] U. Brandes, "A faster algorithm for betweenness
Tiago Peixoto's avatar
Tiago Peixoto committed
332
       centrality", Journal of Mathematical Sociology, 2001, :doi:`10.1080/0022250X.2001.9990249`
333 334 335
    .. [brandes-centrality-2007] U. Brandes, C. Pich, "Centrality estimation in
       large networks", Int. J. Bifurcation Chaos 17, 2303 (2007).
       :DOI:`10.1142/S0218127407018403`
336 337 338
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
339

340
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
341
    if vprop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
342
        vprop = g.new_vertex_property("double")
Tiago Peixoto's avatar
Tiago Peixoto committed
343
    if eprop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
344
        eprop = g.new_edge_property("double")
Tiago Peixoto's avatar
Tiago Peixoto committed
345
    if weight is not None and weight.value_type() != eprop.value_type():
Tiago Peixoto's avatar
Tiago Peixoto committed
346 347 348
        nw = g.new_edge_property(eprop.value_type())
        g.copy_property(weight, nw)
        weight = nw
349 350 351 352 353 354
    if pivots is not None:
        pivots = numpy.asarray(pivots, dtype="uint64")
    else:
        pivots = g.get_vertices()
    vpivots = Vector_size_t(len(pivots))
    vpivots.a = pivots
Tiago Peixoto's avatar
Tiago Peixoto committed
355
    libgraph_tool_centrality.\
356
            get_betweenness(g._Graph__graph, vpivots, _prop("e", g, weight),
Tiago Peixoto's avatar
Tiago Peixoto committed
357 358 359
                            _prop("e", g, eprop), _prop("v", g, vprop), norm)
    return vprop, eprop

Tiago Peixoto's avatar
Tiago Peixoto committed
360 361 362 363 364 365 366 367
def closeness(g, weight=None, source=None, vprop=None, norm=True, harmonic=False):
    r"""
    Calculate the closeness centrality for each vertex.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
368
    weight : :class:`~graph_tool.EdgePropertyMap`, optional (default: None)
Tiago Peixoto's avatar
Tiago Peixoto committed
369 370 371
        Edge property map corresponding to the weight value of each edge.
    source : :class:`~graph_tool.Vertex`, optional (default: ``None``)
        If specified, the centrality is computed for this vertex alone.
372
    vprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
373 374 375 376 377 378 379 380 381
        Vertex property map to store the vertex centrality values.
    norm : bool, optional (default: ``True``)
        Whether or not the centrality values should be normalized.
    harmonic : bool, optional (default: ``False``)
        If true, the sum of the inverse of the distances will be computed,
        instead of the inverse of the sum.

    Returns
    -------
382
    vertex_closeness : :class:`~graph_tool.VertexPropertyMap`
Tiago Peixoto's avatar
Tiago Peixoto committed
383 384 385 386 387 388 389 390
        A vertex property map with the vertex closeness values.

    See Also
    --------
    central_point_dominance: central point dominance of the graph
    pagerank: PageRank centrality
    eigentrust: eigentrust centrality
    eigenvector: eigenvector centrality
391
    hits: authority and hub centralities
Tiago Peixoto's avatar
Tiago Peixoto committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    trust_transitivity: pervasive trust transitivity

    Notes
    -----
    The closeness centrality of a vertex :math:`i` is defined as,

    .. math::

        c_i = \frac{1}{\sum_j d_{ij}}

    where :math:`d_{ij}` is the (possibly directed and/or weighted) distance
    from :math:`i` to :math:`j`. In case there is no path between the two
    vertices, here the distance is taken to be zero.

    If ``harmonic == True``, the definition becomes

    .. math::

        c_i = \sum_j\frac{1}{d_{ij}},

    but now, in case there is no path between the two vertices, we take
    :math:`d_{ij} \to\infty` such that :math:`1/d_{ij}=0`.

    If ``norm == True``, the values of :math:`c_i` are normalized by
    :math:`n_i-1` where :math:`n_i` is the size of the (out-) component of
    :math:`i`. If ``harmonic == True``, they are instead simply normalized by
418
    :math:`V-1`.
Tiago Peixoto's avatar
Tiago Peixoto committed
419

420
    The algorithm complexity of :math:`O(V(V + E))` for unweighted graphs and
Tiago Peixoto's avatar
Tiago Peixoto committed
421
    :math:`O(V(V+E) \log V)` for weighted graphs. If the option ``source`` is
422
    specified, this drops to :math:`O(V + E)` and :math:`O((V+E)\log V)`
Tiago Peixoto's avatar
Tiago Peixoto committed
423 424 425 426 427 428 429
    respectively.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------

Tiago Peixoto's avatar
Tiago Peixoto committed
430 431 432 433
    .. testsetup:: closeness

       import matplotlib

Tiago Peixoto's avatar
Tiago Peixoto committed
434 435 436 437 438 439 440
    .. doctest:: closeness

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> c = gt.closeness(g)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=c,
       ...               vertex_size=gt.prop_to_size(c, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
441
       ...               vcmap=matplotlib.cm.gist_heat,
Tiago Peixoto's avatar
Tiago Peixoto committed
442 443 444 445 446 447 448 449
       ...               vorder=c, output="polblogs_closeness.pdf")
       <...>

    .. testcode:: closeness
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=c,
                     vertex_size=gt.prop_to_size(c, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
450
                     vcmap=matplotlib.cm.gist_heat,
Tiago Peixoto's avatar
Tiago Peixoto committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
                     vorder=c, output="polblogs_closeness.png")


    .. figure:: polblogs_closeness.*
       :align: center

       Closeness values of the a political blogs network of [adamic-polblogs]_.

    References
    ----------
    .. [closeness-wikipedia] https://en.wikipedia.org/wiki/Closeness_centrality
    .. [opsahl-node-2010] Opsahl, T., Agneessens, F., Skvoretz, J., "Node
       centrality in weighted networks: Generalizing degree and shortest
       paths". Social Networks 32, 245-251, 2010 :DOI:`10.1016/j.socnet.2010.03.006`
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`

    """
    if source is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
471
        if vprop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
472 473 474 475 476 477 478
            vprop = g.new_vertex_property("double")
        libgraph_tool_centrality.\
            closeness(g._Graph__graph, _prop("e", g, weight),
                      _prop("v", g, vprop), harmonic, norm)
        return vprop
    else:
        max_dist = g.num_vertices() + 1
479
        dist = shortest_distance(g, source=source, weights=weight,
Tiago Peixoto's avatar
Tiago Peixoto committed
480
                                 max_dist=max_dist)
481
        dists = dist.fa[(dist.fa < max_dist) * (dist.fa > 0)]
Tiago Peixoto's avatar
Tiago Peixoto committed
482 483 484 485 486 487 488
        if harmonic:
            c = (1. / dists).sum()
            if norm:
                c /= g.num_vertices() - 1
        else:
            c = 1. / dists.sum()
            if norm:
489 490
                c *= len(dists)
        return c
Tiago Peixoto's avatar
Tiago Peixoto committed
491

Tiago Peixoto's avatar
Tiago Peixoto committed
492

Tiago Peixoto's avatar
Tiago Peixoto committed
493
def central_point_dominance(g, betweenness):
494
    r"""Calculate the central point dominance of the graph, given the betweenness
495 496 497 498
    centrality of each vertex.

    Parameters
    ----------
499
    g : :class:`~graph_tool.Graph`
500
        Graph to be used.
501
    betweenness : :class:`~graph_tool.VertexPropertyMap`
502 503 504 505 506
        Vertex property map with the betweenness centrality values. The values
        must be normalized.

    Returns
    -------
507 508
    cp : float
        The central point dominance.
509 510 511 512 513 514 515 516

    See Also
    --------
    betweenness: betweenness centrality

    Notes
    -----
    Let :math:`v^*` be the vertex with the largest relative betweenness
517
    centrality; then, the central point dominance [freeman-set-1977]_ is defined
518 519
    as:

520 521
    .. math::

522 523 524 525 526 527 528 529 530
        C'_B = \frac{1}{|V|-1} \sum_{v} C_B(v^*) - C_B(v)

    where :math:`C_B(v)` is the normalized betweenness centrality of vertex
    v. The value of :math:`C_B` lies in the range [0,1].

    The algorithm has a complexity of :math:`O(V)`.

    Examples
    --------
531 532 533 534 535

    >>> g = gt.collection.data["polblogs"]
    >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
    >>> vp, ep = gt.betweenness(g)
    >>> print(gt.central_point_dominance(g, vp))
Tiago Peixoto's avatar
Tiago Peixoto committed
536
    0.105683...
537 538 539

    References
    ----------
540
    .. [freeman-set-1977] Linton C. Freeman, "A Set of Measures of Centrality
541 542
       Based on Betweenness", Sociometry, Vol. 40, No. 1, pp. 35-41, 1977,
       :doi:`10.2307/3033543`
543 544
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
545
    return libgraph_tool_centrality.\
546
           get_central_point_dominance(g._Graph__graph,
Tiago Peixoto's avatar
Tiago Peixoto committed
547 548
                                       _prop("v", g, betweenness))

549

550 551 552 553 554 555 556 557 558
def eigenvector(g, weight=None, vprop=None, epsilon=1e-6, max_iter=None):
    r"""
    Calculate the eigenvector centrality of each vertex in the graph, as well as
    the largest eigenvalue.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
559
    weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
560
        Edge property map with the edge weights.
561
    vprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
562 563
        Vertex property map where the values of eigenvector must be stored. If
        provided, it will be used uninitialized.
564 565 566 567 568 569 570 571 572 573
    epsilon : float, optional (default: ``1e-6``)
        Convergence condition. The iteration will stop if the total delta of all
        vertices are below this value.
    max_iter : int, optional (default: ``None``)
        If supplied, this will limit the total number of iterations.

    Returns
    -------
    eigenvalue : float
        The largest eigenvalue of the (weighted) adjacency matrix.
574
    eigenvector : :class:`~graph_tool.VertexPropertyMap`
575 576 577 578 579 580
        A vertex property map containing the eigenvector values.

    See Also
    --------
    betweenness: betweenness centrality
    pagerank: PageRank centrality
581
    hits: authority and hub centralities
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    trust_transitivity: pervasive trust transitivity

    Notes
    -----

    The eigenvector centrality :math:`\mathbf{x}` is the eigenvector of the
    (weighted) adjacency matrix with the largest eigenvalue :math:`\lambda`,
    i.e. it is the solution of

    .. math::

        \mathbf{A}\mathbf{x} = \lambda\mathbf{x},


    where :math:`\mathbf{A}` is the (weighted) adjacency matrix and
    :math:`\lambda` is the largest eigenvalue.

    The algorithm uses the power method which has a topology-dependent complexity of
    :math:`O\left(N\times\frac{-\log\epsilon}{\log|\lambda_1/\lambda_2|}\right)`,
    where :math:`N` is the number of vertices, :math:`\epsilon` is the ``epsilon``
    parameter, and :math:`\lambda_1` and :math:`\lambda_2` are the largest and
    second largest eigenvalues of the (weighted) adjacency matrix, respectively.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
Tiago Peixoto's avatar
Tiago Peixoto committed
609

610 611 612
    .. testsetup:: eigenvector

       np.random.seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
613
       import matplotlib
614 615 616 617 618 619 620 621 622 623

    .. doctest:: eigenvector

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> w = g.new_edge_property("double")
       >>> w.a = np.random.random(len(w.a)) * 42
       >>> ee, x = gt.eigenvector(g, w)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
       ...               vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
624
       ...               vcmap=matplotlib.cm.gist_heat,
625 626 627 628 629 630 631 632
       ...               vorder=x, output="polblogs_eigenvector.pdf")
       <...>

    .. testcode:: eigenvector
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
                     vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
633
                     vcmap=matplotlib.cm.gist_heat,
634 635 636 637 638 639 640 641
                     vorder=x, output="polblogs_eigenvector.png")


    .. figure:: polblogs_eigenvector.*
       :align: center

       Eigenvector values of the a political blogs network of
       [adamic-polblogs]_, with random weights attributed to the edges.
642 643 644 645 646 647 648 649 650

    References
    ----------

    .. [eigenvector-centrality] http://en.wikipedia.org/wiki/Centrality#Eigenvector_centrality
    .. [power-method] http://en.wikipedia.org/wiki/Power_iteration
    .. [langville-survey-2005] A. N. Langville, C. D. Meyer, "A Survey of
       Eigenvector Methods for Web Information Retrieval", SIAM Review, vol. 47,
       no. 1, pp. 135-161, 2005, :DOI:`10.1137/S0036144503424786`
651 652 653
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
654 655 656

    """

657
    if vprop is None:
658
        vprop = g.new_vertex_property("double")
659
        vprop.fa = 1. / g.num_vertices()
660 661 662 663 664 665 666 667
    if max_iter is None:
        max_iter = 0
    ee = libgraph_tool_centrality.\
         get_eigenvector(g._Graph__graph, _prop("e", g, weight),
                         _prop("v", g, vprop), epsilon, max_iter)
    return ee, vprop


668 669
def katz(g, alpha=0.01, beta=None, weight=None, vprop=None, epsilon=1e-6,
         max_iter=None, norm=True):
Tiago Peixoto's avatar
Tiago Peixoto committed
670
    r"""
Tiago Peixoto's avatar
Tiago Peixoto committed
671
    Calculate the Katz centrality of each vertex in the graph.
Tiago Peixoto's avatar
Tiago Peixoto committed
672 673 674 675 676

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
677
    weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
678 679
        Edge property map with the edge weights.
    alpha : float, optional (default: ``0.01``)
680 681
        Free parameter :math:`\alpha`. This must be smaller than the inverse of
        the largest eigenvalue of the adjacency matrix.
682
    beta : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
683 684
        Vertex property map where the local personalization values. If not
        provided, the global value of 1 will be used.
685
    vprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
686 687 688 689 690 691 692
        Vertex property map where the values of eigenvector must be stored. If
        provided, it will be used uninitialized.
    epsilon : float, optional (default: ``1e-6``)
        Convergence condition. The iteration will stop if the total delta of all
        vertices are below this value.
    max_iter : int, optional (default: ``None``)
        If supplied, this will limit the total number of iterations.
693 694
    norm : bool, optional (default: ``True``)
        Whether or not the centrality values should be normalized.
Tiago Peixoto's avatar
Tiago Peixoto committed
695 696 697

    Returns
    -------
698
    centrality : :class:`~graph_tool.VertexPropertyMap`
Tiago Peixoto's avatar
Tiago Peixoto committed
699 700 701 702 703 704 705
        A vertex property map containing the Katz centrality values.

    See Also
    --------
    betweenness: betweenness centrality
    pagerank: PageRank centrality
    eigenvector: eigenvector centrality
706
    hits: authority and hub centralities
Tiago Peixoto's avatar
Tiago Peixoto committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    trust_transitivity: pervasive trust transitivity

    Notes
    -----

    The Katz centrality :math:`\mathbf{x}` is the solution of the nonhomogeneous
    linear system

    .. math::

        \mathbf{x} = \alpha\mathbf{A}\mathbf{x} + \mathbf{\beta},


    where :math:`\mathbf{A}` is the (weighted) adjacency matrix and
    :math:`\mathbf{\beta}` is the personalization vector (if not supplied,
    :math:`\mathbf{\beta} = \mathbf{1}` is assumed).

    The algorithm uses successive iterations of the equation above, which has a
    topology-dependent convergence complexity.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
731 732 733
    .. testsetup:: katz

       np.random.seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
734
       import matplotlib
735 736 737 738 739 740

    .. doctest:: katz

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> w = g.new_edge_property("double")
Tiago Peixoto's avatar
Tiago Peixoto committed
741
       >>> w.a = np.random.random(len(w.a))
742 743 744
       >>> x = gt.katz(g, weight=w)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
       ...               vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
745
       ...               vcmap=matplotlib.cm.gist_heat,
746 747 748 749 750 751 752 753
       ...               vorder=x, output="polblogs_katz.pdf")
       <...>

    .. testcode:: katz
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
                     vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
754
                     vcmap=matplotlib.cm.gist_heat,
755 756 757 758 759 760 761 762
                     vorder=x, output="polblogs_katz.png")


    .. figure:: polblogs_katz.*
       :align: center

       Katz centrality values of the a political blogs network of
       [adamic-polblogs]_, with random weights attributed to the edges.
Tiago Peixoto's avatar
Tiago Peixoto committed
763 764 765 766 767 768 769

    References
    ----------

    .. [katz-centrality] http://en.wikipedia.org/wiki/Katz_centrality
    .. [katz-new] L. Katz, "A new status index derived from sociometric analysis",
       Psychometrika 18, Number 1, 39-43, 1953, :DOI:`10.1007/BF02289026`
770 771 772
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
Tiago Peixoto's avatar
Tiago Peixoto committed
773 774
    """

775
    if vprop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
776 777 778
        vprop = g.new_vertex_property("double")
    if max_iter is None:
        max_iter = 0
779
    libgraph_tool_centrality.\
Tiago Peixoto's avatar
Tiago Peixoto committed
780
         get_katz(g._Graph__graph, _prop("e", g, weight), _prop("v", g, vprop),
781 782 783
                  _prop("v", g, beta), float(alpha), epsilon, max_iter)
    if norm:
        vprop.fa = vprop.fa / numpy.linalg.norm(vprop.fa)
Tiago Peixoto's avatar
Tiago Peixoto committed
784 785 786
    return vprop


787 788 789 790 791 792 793 794
def hits(g, weight=None, xprop=None, yprop=None, epsilon=1e-6, max_iter=None):
    r"""
    Calculate the authority and hub centralities of each vertex in the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
795
    weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
796
        Edge property map with the edge weights.
797
    xprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
798
        Vertex property map where the authority centrality must be stored.
799
    yprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
800 801 802 803 804 805 806 807 808 809 810
        Vertex property map where the hub centrality must be stored.
    epsilon : float, optional (default: ``1e-6``)
        Convergence condition. The iteration will stop if the total delta of all
        vertices are below this value.
    max_iter : int, optional (default: ``None``)
        If supplied, this will limit the total number of iterations.

    Returns
    -------
    eig : `float`
        The largest eigenvalue of the cocitation matrix.
811
    x : :class:`~graph_tool.VertexPropertyMap`
812
        A vertex property map containing the authority centrality values.
813
    y : :class:`~graph_tool.VertexPropertyMap`
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        A vertex property map containing the hub centrality values.

    See Also
    --------
    betweenness: betweenness centrality
    eigenvector: eigenvector centrality
    pagerank: PageRank centrality
    trust_transitivity: pervasive trust transitivity

    Notes
    -----

    The Hyperlink-Induced Topic Search (HITS) centrality assigns hub
    (:math:`\mathbf{y}`) and authority (:math:`\mathbf{x}`) centralities to the
    vertices, following:

    .. math::

        \begin{align}
            \mathbf{x} &= \alpha\mathbf{A}\mathbf{y} \\
            \mathbf{y} &= \beta\mathbf{A}^T\mathbf{x}
        \end{align}


    where :math:`\mathbf{A}` is the (weighted) adjacency matrix and
    :math:`\lambda = 1/(\alpha\beta)` is the largest eigenvalue of the
    cocitation matrix, :math:`\mathbf{A}\mathbf{A}^T`. (Without loss of
    generality, we set :math:`\beta=1` in the algorithm.)

    The algorithm uses the power method which has a topology-dependent complexity of
    :math:`O\left(N\times\frac{-\log\epsilon}{\log|\lambda_1/\lambda_2|}\right)`,
    where :math:`N` is the number of vertices, :math:`\epsilon` is the ``epsilon``
    parameter, and :math:`\lambda_1` and :math:`\lambda_2` are the largest and
    second largest eigenvalues of the (weighted) cocitation matrix, respectively.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
853

Tiago Peixoto's avatar
Tiago Peixoto committed
854 855 856 857
    .. testsetup:: hits

       import matplotlib

858 859 860 861 862 863 864
    .. doctest:: hits

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> ee, x, y = gt.hits(g)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
       ...               vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
865
       ...               vcmap=matplotlib.cm.gist_heat,
866 867 868 869
       ...               vorder=x, output="polblogs_hits_auths.pdf")
       <...>
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=y,
       ...               vertex_size=gt.prop_to_size(y, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
870
       ...               vcmap=matplotlib.cm.gist_heat,
871 872 873 874 875 876 877 878
       ...               vorder=y, output="polblogs_hits_hubs.pdf")
       <...>

    .. testcode:: hits
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=x,
                     vertex_size=gt.prop_to_size(x, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
879
                     vcmap=matplotlib.cm.gist_heat,
880 881 882
                     vorder=x, output="polblogs_hits_auths.png")
       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=y,
                     vertex_size=gt.prop_to_size(y, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
883
                     vcmap=matplotlib.cm.gist_heat,
884 885 886 887
                     vorder=y, output="polblogs_hits_hubs.png")


    .. figure:: polblogs_hits_auths.*
Tiago Peixoto's avatar
Tiago Peixoto committed
888
       :align: center
889 890 891 892 893

       HITS authority values of the a political blogs network of
       [adamic-polblogs]_.

    .. figure:: polblogs_hits_hubs.*
Tiago Peixoto's avatar
Tiago Peixoto committed
894
       :align: center
895 896

       HITS hub values of the a political blogs network of [adamic-polblogs]_.
897 898 899 900 901 902

    References
    ----------

    .. [hits-algorithm] http://en.wikipedia.org/wiki/HITS_algorithm
    .. [kleinberg-authoritative] J. Kleinberg, "Authoritative sources in a
903
       hyperlinked environment", Journal of the ACM 46 (5): 604-632, 1999,
904 905
       :DOI:`10.1145/324133.324140`.
    .. [power-method] http://en.wikipedia.org/wiki/Power_iteration
906 907 908
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
909 910 911 912 913 914 915 916 917 918 919 920 921 922
    """

    if xprop is None:
        xprop = g.new_vertex_property("double")
    if yprop is None:
        yprop = g.new_vertex_property("double")
    if max_iter is None:
        max_iter = 0
    l = libgraph_tool_centrality.\
         get_hits(g._Graph__graph, _prop("e", g, weight), _prop("v", g, xprop),
                  _prop("v", g, yprop), epsilon, max_iter)
    return 1. / l, xprop, yprop


Tiago Peixoto's avatar
Tiago Peixoto committed
923
def eigentrust(g, trust_map, vprop=None, norm=False, epsilon=1e-6, max_iter=0,
Tiago Peixoto's avatar
Tiago Peixoto committed
924
               ret_iter=False):
925 926 927 928 929
    r"""
    Calculate the eigentrust centrality of each vertex in the graph.

    Parameters
    ----------
930
    g : :class:`~graph_tool.Graph`
931
        Graph to be used.
932
    trust_map : :class:`~graph_tool.EdgePropertyMap`
933
        Edge property map with the values of trust associated with each
934
        edge. The values must lie in the range [0,1].
935
    vprop : :class:`~graph_tool.VertexPropertyMap`, optional (default: ``None``)
936
        Vertex property map where the values of eigentrust must be stored.
937
    norm : bool, optional (default:  ``False``)
938
        Norm eigentrust values so that the total sum equals 1.
939
    epsilon : float, optional (default: ``1e-6``)
940 941
        Convergence condition. The iteration will stop if the total delta of all
        vertices are below this value.
942
    max_iter : int, optional (default: ``None``)
943
        If supplied, this will limit the total number of iterations.
944
    ret_iter : bool, optional (default: ``False``)
945 946 947 948
        If true, the total number of iterations is also returned.

    Returns
    -------
949
    eigentrust : :class:`~graph_tool.VertexPropertyMap`
950
        A vertex property map containing the eigentrust values.
951 952 953 954 955

    See Also
    --------
    betweenness: betweenness centrality
    pagerank: PageRank centrality
956
    trust_transitivity: pervasive trust transitivity
957 958 959

    Notes
    -----
960
    The eigentrust [kamvar-eigentrust-2003]_ values :math:`t_i` correspond the
961 962
    following limit

963 964
    .. math::

965 966 967 968 969
        \mathbf{t} = \lim_{n\to\infty} \left(C^T\right)^n \mathbf{c}

    where :math:`c_i = 1/|V|` and the elements of the matrix :math:`C` are the
    normalized trust values:

970 971
    .. math::

972 973 974 975 976 977 978 979
        c_{ij} = \frac{\max(s_{ij},0)}{\sum_{j} \max(s_{ij}, 0)}

    The algorithm has a topology-dependent complexity.

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
980 981 982 983

    .. testsetup:: eigentrust

       np.random.seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
984
       import matplotlib
985 986 987 988 989 990 991 992 993 994

    .. doctest:: eigentrust

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> w = g.new_edge_property("double")
       >>> w.a = np.random.random(len(w.a)) * 42
       >>> t = gt.eigentrust(g, w)
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=t,
       ...               vertex_size=gt.prop_to_size(t, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
995
       ...               vcmap=matplotlib.cm.gist_heat,
996 997 998 999 1000 1001 1002 1003
       ...               vorder=t, output="polblogs_eigentrust.pdf")
       <...>

    .. testcode:: eigentrust
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=t,
                     vertex_size=gt.prop_to_size(t, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
1004
                     vcmap=matplotlib.cm.gist_heat,
1005 1006 1007 1008 1009 1010 1011 1012 1013
                     vorder=t, output="polblogs_eigentrust.png")


    .. figure:: polblogs_eigentrust.*
       :align: center

       Eigentrust values of the a political blogs network of
       [adamic-polblogs]_, with random weights attributed to the edges.

1014 1015 1016

    References
    ----------
1017
    .. [kamvar-eigentrust-2003] S. D. Kamvar, M. T. Schlosser, H. Garcia-Molina
1018 1019
       "The eigentrust algorithm for reputation management in p2p networks",
       Proceedings of the 12th international conference on World Wide Web,
Tiago Peixoto's avatar
Tiago Peixoto committed
1020
       Pages: 640 - 651, 2003, :doi:`10.1145/775152.775242`
1021 1022 1023
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
1024 1025
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
1026
    if vprop is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1027
        vprop = g.new_vertex_property("double")
1028 1029
    i = libgraph_tool_centrality.\
           get_eigentrust(g._Graph__graph, _prop("e", g, trust_map),
Tiago Peixoto's avatar
Tiago Peixoto committed
1030
                          _prop("v", g, vprop), epsilon, max_iter)
1031 1032 1033 1034 1035 1036 1037 1038
    if norm:
        vprop.get_array()[:] /= sum(vprop.get_array())

    if ret_iter:
        return vprop, i
    else:
        return vprop

Tiago Peixoto's avatar
Tiago Peixoto committed
1039

1040
def trust_transitivity(g, trust_map, source=None, target=None, vprop=None):
1041
    r"""
1042 1043
    Calculate the pervasive trust transitivity between chosen (or all) vertices
    in the graph.
1044 1045 1046

    Parameters
    ----------
1047
    g : :class:`~graph_tool.Graph`
1048
        Graph to be used.
1049
    trust_map : :class:`~graph_tool.EdgePropertyMap`
1050 1051
        Edge property map with the values of trust associated with each
        edge. The values must lie in the range [0,1].
Tiago Peixoto's avatar
Tiago Peixoto committed
1052
    source : :class:`~graph_tool.Vertex` (optional, default: None)
1053
        Source vertex. All trust values are computed relative to this vertex.
1054
        If left unspecified, the trust values for all sources are computed.
Tiago Peixoto's avatar
Tiago Peixoto committed
1055
    target : :class:`~graph_tool.Vertex` (optional, default: None)
1056 1057
        The only target for which the trust value will be calculated. If left
        unspecified, the trust values for all targets are computed.
1058
    vprop : :class:`~graph_tool.VertexPropertyMap` (optional, default: None)
1059 1060
        A vertex property map where the values of transitive trust must be
        stored.
1061 1062 1063

    Returns
    -------
1064
    trust_transitivity : :class:`~graph_tool.VertexPropertyMap` or float
1065 1066 1067 1068 1069 1070 1071
        A vertex vector property map containing, for each source vertex, a
        vector with the trust values for the other vertices. If only one of
        `source` or `target` is specified, this will be a single-valued vertex
        property map containing the trust vector from/to the source/target
        vertex to/from the rest of the network. If both `source` and `target`
        are specified, the result is a single float, with the corresponding
        trust value for the target.
1072

1073 1074 1075 1076 1077 1078 1079 1080
    See Also
    --------
    eigentrust: eigentrust centrality
    betweenness: betweenness centrality
    pagerank: PageRank centrality

    Notes
    -----
Tiago Peixoto's avatar
Tiago Peixoto committed
1081
    The pervasive trust transitivity between vertices i and j is defined as
1082

1083 1084
    .. math::

1085 1086
        t_{ij} = \frac{\sum_m A_{m,j} w^2_{G\setminus\{j\}}(i\to m)c_{m,j}}
                 {\sum_m A_{m,j} w_{G\setminus\{j\}}(i\to m)}
1087

1088 1089 1090
    where :math:`A_{ij}` is the adjacency matrix, :math:`c_{ij}` is the direct
    trust from i to j, and :math:`w_G(i\to j)` is the weight of the path with
    maximum weight from i to j, computed as
Tiago Peixoto's avatar
Tiago Peixoto committed
1091

1092 1093
    .. math::

1094
       w_G(i\to j) = \prod_{e\in i\to j} c_e.
1095

1096
    The algorithm measures the transitive trust by finding the paths with
1097
    maximum weight, using Dijkstra's algorithm, to all in-neighbors of a given
1098
    target. This search needs to be performed repeatedly for every target, since
1099
    it needs to be removed from the graph first. For each given source, the
1100 1101 1102
    resulting complexity is therefore :math:`O(V^2\log V)` for all targets, and
    :math:`O(V\log V)` for a single target. For a given target, the complexity
    for obtaining the trust from all given sources is :math:`O(kV\log V)`, where
1103
    :math:`k` is the in-degree of the target. Thus, the complexity for obtaining
1104
    the complete trust matrix is :math:`O(EV\log V)`, where :math:`E` is the
1105
    number of edges in the network.
1106 1107 1108 1109 1110

    If enabled during compilation, this algorithm runs in parallel.

    Examples
    --------
1111 1112 1113
    .. testsetup:: trust_transitivity

       np.random.seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
1114
       import matplotlib
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

    .. doctest:: trust_transitivity

       >>> g = gt.collection.data["polblogs"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> g = gt.Graph(g, prune=True)
       >>> w = g.new_edge_property("double")
       >>> w.a = np.random.random(len(w.a))
       >>> t = gt.trust_transitivity(g, w, source=g.vertex(42))
       >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=t,
       ...               vertex_size=gt.prop_to_size(t, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
1126
       ...               vcmap=matplotlib.cm.gist_heat,
1127 1128 1129 1130 1131 1132 1133 1134
       ...               vorder=t, output="polblogs_trust_transitivity.pdf")
       <...>

    .. testcode:: trust_transitivity
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=t,
                     vertex_size=gt.prop_to_size(t, mi=5, ma=15),
Tiago Peixoto's avatar
Tiago Peixoto committed
1135
                     vcmap=matplotlib.cm.gist_heat,
1136 1137 1138 1139 1140 1141 1142 1143 1144
                     vorder=t, output="polblogs_trust_transitivity.png")


    .. figure:: polblogs_trust_transitivity.*
       :align: center

       Trust transitivity values from source vertex 42 of the a political blogs
       network of [adamic-polblogs]_, with random weights attributed to the
       edges.
Tiago Peixoto's avatar
Tiago Peixoto committed
1145 1146 1147

    References
    ----------
1148 1149 1150
    .. [richters-trust-2010] Oliver Richters and Tiago P. Peixoto, "Trust
       Transitivity in Social Networks," PLoS ONE 6, no. 4:
       e1838 (2011), :doi:`10.1371/journal.pone.0018384`
1151 1152 1153
    .. [adamic-polblogs] L. A. Adamic and N. Glance, "The political blogosphere
       and the 2004 US Election", in Proceedings of the WWW-2005 Workshop on the
       Weblogging Ecosystem (2005). :DOI:`10.1145/1134271.1134277`
Tiago Peixoto's avatar
Tiago Peixoto committed
1154

1155
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
1156

Tiago Peixoto's avatar
Tiago Peixoto committed
1157
    if vprop is None:
1158
        vprop = g.new_vertex_property("vector<double>")
1159

Tiago Peixoto's avatar
Tiago Peixoto committed
1160
    if target is None:
1161 1162 1163
        target = -1
    else:
        target = g.vertex_index[target]
1164

Tiago Peixoto's avatar
Tiago Peixoto committed
1165
    if source is None:
1166 1167 1168 1169
        source = -1
    else:
        source = g.vertex_index[source]

1170
    libgraph_tool_centrality.\
1171 1172 1173 1174
            get_trust_transitivity(g._Graph__graph, source, target,
                                   _prop("e", g, trust_map),
                                   _prop("v", g, vprop))
    if target != -1 or source != -1:
1175
        vprop = ungroup_vector_property(vprop, [0])[0]