__init__.py 71.4 KB
Newer Older
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
3
#
4
5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
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.topology`` - Assessing graph topology
--------------------------------------------------
24
25
26
27
28
29
30

Summary
+++++++

.. autosummary::
   :nosignatures:

31
   shortest_distance
Tiago Peixoto's avatar
Tiago Peixoto committed
32
   shortest_path
Tiago Peixoto's avatar
Tiago Peixoto committed
33
   pseudo_diameter
34
   similarity
35
   isomorphism
36
37
   subgraph_isomorphism
   mark_subgraph
38
39
   max_cardinality_matching
   max_independent_vertex_set
40
   min_spanning_tree
41
   random_spanning_tree
42
43
44
   dominator_tree
   topological_sort
   transitive_closure
Tiago Peixoto's avatar
Tiago Peixoto committed
45
   tsp_tour
46
   sequential_vertex_coloring
47
48
   label_components
   label_biconnected_components
49
   label_largest_component
50
   label_out_component
Tiago Peixoto's avatar
Tiago Peixoto committed
51
   kcore_decomposition
52
   is_bipartite
Tiago Peixoto's avatar
Tiago Peixoto committed
53
   is_DAG
54
   is_planar
55
   make_maximal_planar
Tiago Peixoto's avatar
Tiago Peixoto committed
56
   edge_reciprocity
57
58
59

Contents
++++++++
60

61
62
"""

63
64
from __future__ import division, absolute_import, print_function

Tiago Peixoto's avatar
Tiago Peixoto committed
65
from .. dl_import import dl_import
66
dl_import("from . import libgraph_tool_topology")
67

68
from .. import _prop, Vector_int32_t, _check_prop_writable, \
69
     _check_prop_scalar, _check_prop_vector, Graph, PropertyMap, GraphView,\
70
     libcore, _get_rng, _degree, perfect_prop_hash
71
from .. stats import label_self_loops
72
import random, sys, numpy, collections
73

74
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
75
           "max_cardinality_matching", "max_independent_vertex_set",
76
           "min_spanning_tree", "random_spanning_tree", "dominator_tree",
Tiago Peixoto's avatar
Tiago Peixoto committed
77
           "topological_sort", "transitive_closure", "tsp_tour",
78
79
           "sequential_vertex_coloring", "label_components",
           "label_largest_component", "label_biconnected_components",
Tiago Peixoto's avatar
Tiago Peixoto committed
80
81
82
           "label_out_component", "kcore_decomposition", "shortest_distance",
           "shortest_path", "pseudo_diameter", "is_bipartite", "is_DAG",
           "is_planar", "make_maximal_planar", "similarity", "edge_reciprocity"]
83
84
85
86
87
88
89
90
91
92


def similarity(g1, g2, label1=None, label2=None, norm=True):
    r"""Return the adjacency similarity between the two graphs.

    Parameters
    ----------
    g1 : :class:`~graph_tool.Graph`
        First graph to be compared.
    g2 : :class:`~graph_tool.Graph`
Tiago Peixoto's avatar
Tiago Peixoto committed
93
        Second graph to be compared.
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    label1 : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex labels for the first graph to be used in comparison. If not
        supplied, the vertex indexes are used.
    label2 : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex labels for the second graph to be used in comparison. If not
        supplied, the vertex indexes are used.
    norm : bool (optional, default: ``True``)
        If ``True``, the returned value is normalized by the total number of
        edges.

    Returns
    -------
    similarity : float
        Adjacency similarity value.

    Notes
    -----
    The adjacency similarity is the sum of equal entries in the adjacency
    matrix, given a vertex ordering determined by the vertex labels. In other
    words it counts the number of edges which have the same source and target
    labels in both graphs.

    The algorithm runs with complexity :math:`O(E_1 + V_1 + E_2 + V_2)`.

    Examples
    --------
120
121
122
123
124
125
126
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

127
128
129
130
    >>> g = gt.random_graph(100, lambda: (3,3))
    >>> u = g.copy()
    >>> gt.similarity(u, g)
    1.0
Tiago Peixoto's avatar
Tiago Peixoto committed
131
    >>> gt.random_rewire(u)
132
    24
133
    >>> gt.similarity(u, g)
134
    0.04666666666666667
135
136
137
138
139
140
141
    """

    if label1 is None:
        label1 = g1.vertex_index
    if label2 is None:
        label2 = g2.vertex_index
    if label1.value_type() != label2.value_type():
142
143
144
145
        try:
            label2 = label2.copy(label1.value_type())
        except ValueError:
            label1 = label1.copy(label2.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
146
    if label1.is_writable() or label2.is_writable():
147
148
149
        s = libgraph_tool_topology.\
               similarity(g1._Graph__graph, g2._Graph__graph,
                          _prop("v", g1, label1), _prop("v", g2, label2))
Tiago Peixoto's avatar
Tiago Peixoto committed
150
151
152
153
    else:
        s = libgraph_tool_topology.\
               similarity_fast(g1._Graph__graph, g2._Graph__graph,
                               _prop("v", g1, label1), _prop("v", g2, label2))
154
155
156
157
158
    if not g1.is_directed() or not g2.is_directed():
        s /= 2
    if norm:
        s /= float(max(g1.num_edges(), g2.num_edges()))
    return s
159

Tiago Peixoto's avatar
Tiago Peixoto committed
160

161
def isomorphism(g1, g2, vertex_inv1=None, vertex_inv2=None, isomap=False):
162
163
    r"""Check whether two graphs are isomorphic.

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    Parameters
    ----------
    g1 : :class:`~graph_tool.Graph`
        First graph.
    g2 : :class:`~graph_tool.Graph`
        Second graph.
    vertex_inv1 : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        Vertex invariant of the first graph. Only vertices with with the same
        invariants are considered in the isomorphism.
    vertex_inv2 : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        Vertex invariant of the second graph. Only vertices with with the same
        invariants are considered in the isomorphism.
    isomap : ``bool`` (optional, default: ``False``)
        If ``True``, a vertex :class:`~graph_tool.PropertyMap` with the
        isomorphism mapping is returned as well.

    Returns
    -------
    is_isomorphism : ``bool``
        ``True`` if both graphs are isomorphic, otherwise ``False``.
    isomap : :class:`~graph_tool.PropertyMap`
         Isomorphism mapping corresponding to a property map belonging to the
         first graph which maps its vertices to their corresponding vertices of
         the second graph.
188
189
190

    Examples
    --------
191
192
193
194
195
196
197
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

198
199
200
201
202
203
204
205
206
    >>> g = gt.random_graph(100, lambda: (3,3))
    >>> g2 = gt.Graph(g)
    >>> gt.isomorphism(g, g2)
    True
    >>> g.add_edge(g.vertex(0), g.vertex(1))
    <...>
    >>> gt.isomorphism(g, g2)
    False

207
    """
208
    imap = g1.new_vertex_property("int32_t")
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    if vertex_inv1 is None:
        vertex_inv1 = g1.degree_property_map("total").copy("int64_t")
    else:
        vertex_inv1 = vertex_inv1.copy("int64_t")
        d = g1.degree_property_map("total")
        vertex_inv1.fa += (vertex_inv1.fa.max() + 1) * d.a
    if vertex_inv2 is None:
        vertex_inv2 = g2.degree_property_map("total").copy("int64_t")
    else:
        vertex_inv2 = vertex_inv2.copy("int64_t")
        d = g2.degree_property_map("total")
        vertex_inv2.fa += (vertex_inv2.fa.max() + 1) * d.a

    inv_max = max(vertex_inv1.fa.max(),vertex_inv2.fa.max()) + 1

    l1 = label_self_loops(g1, mark_only=True)
    if l1.fa.max() > 0:
        g1 = GraphView(g1, efilt=1 - l1.fa)

    l2 = label_self_loops(g2, mark_only=True)
    if l2.fa.max() > 0:
        g2 = GraphView(g2, efilt=1 - l2.fa)

232
    iso = libgraph_tool_topology.\
233
           check_isomorphism(g1._Graph__graph, g2._Graph__graph,
234
235
236
                             _prop("v", g1, vertex_inv1),
                             _prop("v", g2, vertex_inv2),
                             inv_max,
Tiago Peixoto's avatar
Tiago Peixoto committed
237
                             _prop("v", g1, imap))
238
239
240
241
242
    if isomap:
        return iso, imap
    else:
        return iso

Tiago Peixoto's avatar
Tiago Peixoto committed
243

244
def subgraph_isomorphism(sub, g, max_n=0, vertex_label=None, edge_label=None,
245
                         induced=False, subgraph=True, generator=False):
246
    r"""Obtain all subgraph isomorphisms of `sub` in `g` (or at most `max_n` subgraphs, if `max_n > 0`).
247

248

Tiago Peixoto's avatar
Tiago Peixoto committed
249
250
251
252
253
254
    Parameters
    ----------
    sub : :class:`~graph_tool.Graph`
        Subgraph for which to be searched.
    g : :class:`~graph_tool.Graph`
        Graph in which the search is performed.
255
    max_n : int (optional, default: ``0``)
Tiago Peixoto's avatar
Tiago Peixoto committed
256
257
        Maximum number of matches to find. If `max_n == 0`, all matches are
        found.
258
    vertex_label : pair of :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
259
        If provided, this should be a pair of :class:`~graph_tool.PropertyMap`
260
261
262
263
        objects, belonging to ``sub`` and ``g`` (in this order), which specify
        vertex labels which should match, in addition to the topological
        isomorphism.
    edge_label : pair of :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
264
        If provided, this should be a pair of :class:`~graph_tool.PropertyMap`
265
266
267
268
269
270
271
        objects, belonging to ``sub`` and ``g`` (in this order), which specify
        edge labels which should match, in addition to the topological
        isomorphism.
    induced : bool (optional, default: ``False``)
        If ``True``, only node-induced subgraphs are found.
    subgraph : bool (optional, default: ``True``)
        If ``False``, all non-subgraph isomorphisms between `sub` and `g` are
272
        found.
273
274
275
276
    generator : bool (optional, default: ``False``)
        If ``True``, a generator will be returned, instead of a list. This is
        useful if the number of isomorphisms is too large to store in memory. If
        ``generator == True``, the option ``max_n`` is ignored.
Tiago Peixoto's avatar
Tiago Peixoto committed
277
278
279

    Returns
    -------
280
281
282
283
    vertex_maps : list (or generator) of :class:`~graph_tool.PropertyMap` objects
        List (or generator) containing vertex property map objects which
        indicate different isomorphism mappings. The property maps vertices in
        `sub` to the corresponding vertex index in `g`.
Tiago Peixoto's avatar
Tiago Peixoto committed
284
285
286

    Notes
    -----
287
288
289
290
291
    The implementation is based on the VF2 algorithm, introduced by Cordella et al.
    [cordella-improved-2001]_ [cordella-subgraph-2004]_. The spatial complexity
    is of order :math:`O(V)`, where :math:`V` is the (maximum) number of vertices
    of the two graphs. Time complexity is :math:`O(V^2)` in the best case and
    :math:`O(V!\times V)` in the worst case.
292
293
294

    Examples
    --------
295
    >>> from numpy.random import poisson
296
297
298
    >>> g = gt.complete_graph(30)
    >>> sub = gt.complete_graph(10)
    >>> vm = gt.subgraph_isomorphism(sub, g, max_n=100)
299
    >>> print(len(vm))
300
    100
301
    >>> for i in range(len(vm)):
302
303
    ...   g.set_vertex_filter(None)
    ...   g.set_edge_filter(None)
304
    ...   vmask, emask = gt.mark_subgraph(g, sub, vm[i])
305
306
    ...   g.set_vertex_filter(vmask)
    ...   g.set_edge_filter(emask)
307
    ...   assert gt.isomorphism(g, sub)
308
309
310
311
    >>> g.set_vertex_filter(None)
    >>> g.set_edge_filter(None)
    >>> ewidth = g.copy_property(emask, value_type="double")
    >>> ewidth.a += 0.5
Tiago Peixoto's avatar
Tiago Peixoto committed
312
313
314
    >>> ewidth.a *= 2
    >>> gt.graph_draw(g, vertex_fill_color=vmask, edge_color=emask,
    ...               edge_pen_width=ewidth, output_size=(200, 200),
315
    ...               output="subgraph-iso-embed.pdf")
316
    <...>
Tiago Peixoto's avatar
Tiago Peixoto committed
317
    >>> gt.graph_draw(sub, output_size=(200, 200), output="subgraph-iso.pdf")
318
319
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
320
321
322
323
324
325
326
327
    .. testcode::
       :hide:

       gt.graph_draw(g, vertex_fill_color=vmask, edge_color=emask,
                     edge_pen_width=ewidth, output_size=(200, 200),
                     output="subgraph-iso-embed.png")
       gt.graph_draw(sub, output_size=(200, 200), output="subgraph-iso.png")

Tiago Peixoto's avatar
Tiago Peixoto committed
328
329
    .. image:: subgraph-iso.*
    .. image:: subgraph-iso-embed.*
330

331

Tiago Peixoto's avatar
Tiago Peixoto committed
332
    **Left:** Subgraph searched, **Right:** One isomorphic subgraph found in main graph.
333
334
335

    References
    ----------
336
337
338
339
340
341
342
343
344
    .. [cordella-improved-2001] L. P. Cordella, P. Foggia, C. Sansone, and M. Vento,
       "An improved algorithm for matching large graphs.", 3rd IAPR-TC15 Workshop
       on Graph-based Representations in Pattern Recognition, pp. 149-159, Cuen, 2001.
       http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.5342
    .. [cordella-subgraph-2004] L. P. Cordella, P. Foggia, C. Sansone, and M. Vento,
       "A (Sub)Graph Isomorphism Algorithm for Matching Large Graphs.",
       IEEE Trans. Pattern Anal. Mach. Intell., vol. 26, no. 10, pp. 1367-1372, 2004. 
       :doi:`10.1109/TPAMI.2004.75`
    .. [boost-subgraph-iso] http://www.boost.org/libs/graph/doc/vf2_sub_graph_iso.html
345
    .. [subgraph-isormophism-wikipedia] http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem
346
347

    """
348
349
    if sub.num_vertices() == 0:
        raise ValueError("Cannot search for an empty subgraph.")
350
351
352
353
    if vertex_label is None:
        vertex_label = (None, None)
    elif vertex_label[0].value_type() != vertex_label[1].value_type():
        raise ValueError("Both vertex label property maps must be of the same type!")
354
355
356
    elif vertex_label[0].value_type() != "int32_t":
        vertex_label = perfect_prop_hash(vertex_label, htype="int32_t")

357
358
359
360
    if edge_label is None:
        edge_label = (None, None)
    elif edge_label[0].value_type() != edge_label[1].value_type():
        raise ValueError("Both edge label property maps must be of the same type!")
361
362
363
    elif edge_label[0].value_type() != "int32_t":
        edge_label = perfect_prop_hash(edge_label, htype="int32_t")

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    vmaps = libgraph_tool_topology.\
            subgraph_isomorphism(sub._Graph__graph, g._Graph__graph,
                                 _prop("v", sub, vertex_label[0]),
                                 _prop("v", g, vertex_label[1]),
                                 _prop("e", sub, edge_label[0]),
                                 _prop("e", g, edge_label[1]),
                                 max_n, induced, not subgraph,
                                 generator)
    if generator:
        for vmap in vmaps:
            yield PropertyMap(vmap, sub, "v")
    else:
        for i in range(len(vmaps)):
            vmaps[i] = PropertyMap(vmaps[i], sub, "v")
        return vmaps
379

Tiago Peixoto's avatar
Tiago Peixoto committed
380

381
def mark_subgraph(g, sub, vmap, vmask=None, emask=None):
382
383
384
385
386
387
388
389
390
    r"""
    Mark a given subgraph `sub` on the graph `g`.

    The mapping must be provided by the `vmap` and `emap` parameters,
    which map vertices/edges of `sub` to indexes of the corresponding
    vertices/edges in `g`.

    This returns a vertex and an edge property map, with value type 'bool',
    indicating whether or not a vertex/edge in `g` corresponds to the subgraph
391
    `sub`.
392
    """
393
    if vmask is None:
394
        vmask = g.new_vertex_property("bool")
395
    if emask is None:
396
397
398
399
400
401
402
403
        emask = g.new_edge_property("bool")

    vmask.a = False
    emask.a = False

    for v in sub.vertices():
        w = g.vertex(vmap[v])
        vmask[w] = True
404
405
        us = set([g.vertex(vmap[x]) for x in v.out_neighbours()])

406
        for ew in w.out_edges():
407
408
409
            if ew.target() in us:
                emask[ew] = True

410
    return vmask, emask
411

Tiago Peixoto's avatar
Tiago Peixoto committed
412

413
def min_spanning_tree(g, weights=None, root=None, tree_map=None):
414
415
416
417
418
419
420
    """
    Return the minimum spanning tree of a given graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
421
    weights : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
422
423
        The edge weights. If provided, the minimum spanning tree will minimize
        the edge weights.
424
    root : :class:`~graph_tool.Vertex` (optional, default: `None`)
425
        Root of the minimum spanning tree. If this is provided, Prim's algorithm
426
        is used. Otherwise, Kruskal's algorithm is used.
427
    tree_map : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
        If provided, the edge tree map will be written in this property map.

    Returns
    -------
    tree_map : :class:`~graph_tool.PropertyMap`
        Edge property map with mark the tree edges: 1 for tree edge, 0
        otherwise.

    Notes
    -----
    The algorithm runs with :math:`O(E\log E)` complexity, or :math:`O(E\log V)`
    if `root` is specified.

    Examples
    --------
443
444
445
446
447
448
449
450
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

    >>> from numpy.random import random
451
452
453
    >>> g, pos = gt.triangulation(random((400, 2)) * 10, type="delaunay")
    >>> weight = g.new_edge_property("double")
    >>> for e in g.edges():
Tiago Peixoto's avatar
Tiago Peixoto committed
454
    ...    weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
455
    >>> tree = gt.min_spanning_tree(g, weights=weight)
456
    >>> gt.graph_draw(g, pos=pos, output="triang_orig.pdf")
457
    <...>
458
459
    >>> u = gt.GraphView(g, efilt=tree)
    >>> gt.graph_draw(u, pos=pos, output="triang_min_span_tree.pdf")
460
461
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
462
463
464
465
    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="triang_orig.png")
466
       gt.graph_draw(u, pos=pos, output="triang_min_span_tree.png")
467

468
    .. image:: triang_orig.*
Tiago Peixoto's avatar
Tiago Peixoto committed
469
        :width: 400px
470
    .. image:: triang_min_span_tree.*
Tiago Peixoto's avatar
Tiago Peixoto committed
471
        :width: 400px
472
473

    *Left:* Original graph, *Right:* The minimum spanning tree.
474
475
476
477
478

    References
    ----------
    .. [kruskal-shortest-1956] J. B. Kruskal.  "On the shortest spanning subtree
       of a graph and the traveling salesman problem",  In Proceedings of the
Tiago Peixoto's avatar
Tiago Peixoto committed
479
480
       American Mathematical Society, volume 7, pages 48-50, 1956.
       :doi:`10.1090/S0002-9939-1956-0078686-7`
481
482
483
484
485
    .. [prim-shortest-1957] R. Prim.  "Shortest connection networks and some
       generalizations",  Bell System Technical Journal, 36:1389-1401, 1957.
    .. [boost-mst] http://www.boost.org/libs/graph/doc/graph_theory_review.html#sec:minimum-spanning-tree
    .. [mst-wiki] http://en.wikipedia.org/wiki/Minimum_spanning_tree
    """
486
    if tree_map is None:
487
488
489
490
        tree_map = g.new_edge_property("bool")
    if tree_map.value_type() != "bool":
        raise ValueError("edge property 'tree_map' must be of value type bool.")

491
492
493
494
495
496
497
498
499
500
501
    u = GraphView(g, directed=False)
    if root is None:
        libgraph_tool_topology.\
               get_kruskal_spanning_tree(u._Graph__graph,
                                         _prop("e", g, weights),
                                         _prop("e", g, tree_map))
    else:
        libgraph_tool_topology.\
               get_prim_spanning_tree(u._Graph__graph, int(root),
                                      _prop("e", g, weights),
                                      _prop("e", g, tree_map))
502
    return tree_map
503

Tiago Peixoto's avatar
Tiago Peixoto committed
504

505
def random_spanning_tree(g, weights=None, root=None, tree_map=None):
506
    r"""Return a random spanning tree of a given graph, which can be directed or
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
    undirected.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        The edge weights. If provided, the probability of a particular spanning
        tree being selected is the product of its edge weights.
    root : :class:`~graph_tool.Vertex` (optional, default: `None`)
        Root of the spanning tree. If not provided, it will be selected randomly.
    tree_map : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        If provided, the edge tree map will be written in this property map.

    Returns
    -------
    tree_map : :class:`~graph_tool.PropertyMap`
        Edge property map with mark the tree edges: 1 for tree edge, 0
        otherwise.

    Notes
    -----
529
530

    The running time for this algorithm is :math:`O(\tau)`, with :math:`\tau`
531
532
533
534
    being the mean hitting time of a random walk on the graph. In the worse case,
    we have :math:`\tau \sim O(V^3)`, with :math:`V` being the number of
    vertices in the graph. However, in much more typical cases (e.g. sparse
    random graphs) the running time is simply :math:`O(V)`.
535
536
537

    Examples
    --------
538
539
540
541
542
543
544
545
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

    >>> from numpy.random import random
546
    >>> g, pos = gt.triangulation(random((400, 2)), type="delaunay")
547
548
549
550
    >>> weight = g.new_edge_property("double")
    >>> for e in g.edges():
    ...    weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
    >>> tree = gt.random_spanning_tree(g, weights=weight)
551
    >>> tree2 = gt.random_spanning_tree(g, weights=weight)
552
553
    >>> gt.graph_draw(g, pos=pos, output="rtriang_orig.pdf")
    <...>
554
555
556
557
558
    >>> u = gt.GraphView(g, efilt=tree)
    >>> gt.graph_draw(u, pos=pos, output="triang_random_span_tree.pdf")
    <...>
    >>> u2 = gt.GraphView(g, efilt=tree2)
    >>> gt.graph_draw(u2, pos=pos, output="triang_random_span_tree2.pdf")
559
560
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
561
562
563
564
    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="rtriang_orig.png")
565
566
       gt.graph_draw(u, pos=pos, output="triang_random_span_tree.png")
       gt.graph_draw(u2, pos=pos, output="triang_random_span_tree2.png")
567
568

    .. image:: rtriang_orig.*
569
        :width: 300px
570
    .. image:: triang_random_span_tree.*
571
572
573
        :width: 300px
    .. image:: triang_random_span_tree2.*
        :width: 300px
574

575
576
    *Left:* Original graph, *Middle:* A random spanning tree, *Right:* Another
    random spanning tree
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597

    References
    ----------

    .. [wilson-generating-1996] David Bruce Wilson, "Generating random spanning
       trees more quickly than the cover time", Proceedings of the twenty-eighth
       annual ACM symposium on Theory of computing, Pages 296-303, ACM New York,
       1996, :doi:`10.1145/237814.237880`
    .. [boost-rst] http://www.boost.org/libs/graph/doc/random_spanning_tree.html
    """
    if tree_map is None:
        tree_map = g.new_edge_property("bool")
    if tree_map.value_type() != "bool":
        raise ValueError("edge property 'tree_map' must be of value type bool.")

    if root is None:
        root = g.vertex(numpy.random.randint(0, g.num_vertices()),
                        use_index=False)

    # we need to restrict ourselves to the in-component of root
    l = label_out_component(GraphView(g, reversed=True), root)
598
599
600
    u = GraphView(g, vfilt=l)
    if u.num_vertices() != g.num_vertices():
        raise ValueError("There must be a path from all vertices to the root vertex: %d" % int(root) )
601
602
603
604

    libgraph_tool_topology.\
        random_spanning_tree(g._Graph__graph, int(root),
                             _prop("e", g, weights),
605
                             _prop("e", g, tree_map), _get_rng())
606
607
608
    return tree_map


Tiago Peixoto's avatar
Tiago Peixoto committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def dominator_tree(g, root, dom_map=None):
    """Return a vertex property map the dominator vertices for each vertex.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    root : :class:`~graph_tool.Vertex`
        The root vertex.
    dom_map : :class:`~graph_tool.PropertyMap` (optional, default: None)
        If provided, the dominator map will be written in this property map.

    Returns
    -------
    dom_map : :class:`~graph_tool.PropertyMap`
        The dominator map. It contains for each vertex, the index of its
        dominator vertex.

    Notes
    -----
    A vertex u dominates a vertex v, if every path of directed graph from the
    entry to v must go through u.

    The algorithm runs with :math:`O((V+E)\log (V+E))` complexity.

    Examples
    --------
636
637
638
639
640
641
642
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

Tiago Peixoto's avatar
Tiago Peixoto committed
643
644
645
    >>> g = gt.random_graph(100, lambda: (2, 2))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
646
    >>> root = [v for v in g.vertices() if v.in_degree() == 0]
Tiago Peixoto's avatar
Tiago Peixoto committed
647
    >>> dom = gt.dominator_tree(g, root[0])
648
    >>> print(dom.a)
649
650
651
    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Tiago Peixoto's avatar
Tiago Peixoto committed
652
653
654

    References
    ----------
655
    .. [dominator-bgl] http://www.boost.org/libs/graph/doc/lengauer_tarjan_dominator.htm
Tiago Peixoto's avatar
Tiago Peixoto committed
656
657

    """
658
    if dom_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
659
660
661
        dom_map = g.new_vertex_property("int32_t")
    if dom_map.value_type() != "int32_t":
        raise ValueError("vertex property 'dom_map' must be of value type" +
662
663
                         " int32_t.")
    if not g.is_directed():
Tiago Peixoto's avatar
Tiago Peixoto committed
664
        raise ValueError("dominator tree requires a directed graph.")
665
    libgraph_tool_topology.\
Tiago Peixoto's avatar
Tiago Peixoto committed
666
667
668
               dominator_tree(g._Graph__graph, int(root),
                              _prop("v", g, dom_map))
    return dom_map
669

Tiago Peixoto's avatar
Tiago Peixoto committed
670

671
def topological_sort(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
672
673
674
675
676
677
678
    """
    Return the topological sort of the given graph. It is returned as an array
    of vertex indexes, in the sort order.

    Notes
    -----
    The topological sort algorithm creates a linear ordering of the vertices
679
    such that if edge (u,v) appears in the graph, then u comes before v in the
Tiago Peixoto's avatar
Tiago Peixoto committed
680
681
682
683
684
685
    ordering. The graph must be a directed acyclic graph (DAG).

    The time complexity is :math:`O(V + E)`.

    Examples
    --------
686
687
688
689
690
691
692
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

Tiago Peixoto's avatar
Tiago Peixoto committed
693
694
695
696
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
    >>> sort = gt.topological_sort(g)
697
    >>> print(sort)
Tiago Peixoto's avatar
Tiago Peixoto committed
698
699
    [29 28 27 26 23 24 22 21 20 18 17 16 15 14 11 10  9  6  5  4 19 12 13  3  2
     25  1  0  7  8]
Tiago Peixoto's avatar
Tiago Peixoto committed
700
701
702

    References
    ----------
703
    .. [topological-boost] http://www.boost.org/libs/graph/doc/topological_sort.html
Tiago Peixoto's avatar
Tiago Peixoto committed
704
705
706
707
    .. [topological-wiki] http://en.wikipedia.org/wiki/Topological_sorting

    """

708
    topological_order = Vector_int32_t()
Tiago Peixoto's avatar
Tiago Peixoto committed
709
710
711
712
    is_DAG = libgraph_tool_topology.\
        topological_sort(g._Graph__graph, topological_order)
    if not is_DAG:
        raise ValueError("Graph is not a directed acylic graph (DAG).");
713
    return topological_order.a[::-1].copy()
714

Tiago Peixoto's avatar
Tiago Peixoto committed
715

716
def transitive_closure(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
717
718
719
720
721
722
723
724
725
726
727
728
729
    """Return the transitive closure graph of g.

    Notes
    -----
    The transitive closure of a graph G = (V,E) is a graph G* = (V,E*) such that
    E* contains an edge (u,v) if and only if G contains a path (of at least one
    edge) from u to v. The transitive_closure() function transforms the input
    graph g into the transitive closure graph tc.

    The time complexity (worst-case) is :math:`O(VE)`.

    Examples
    --------
730
731
732
733
734
735
736
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

Tiago Peixoto's avatar
Tiago Peixoto committed
737
738
739
740
741
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tc = gt.transitive_closure(g)

    References
    ----------
742
    .. [transitive-boost] http://www.boost.org/libs/graph/doc/transitive_closure.html
Tiago Peixoto's avatar
Tiago Peixoto committed
743
744
745
746
    .. [transitive-wiki] http://en.wikipedia.org/wiki/Transitive_closure

    """

747
748
749
750
751
752
753
    if not g.is_directed():
        raise ValueError("graph must be directed for transitive closure.")
    tg = Graph()
    libgraph_tool_topology.transitive_closure(g._Graph__graph,
                                              tg._Graph__graph)
    return tg

Tiago Peixoto's avatar
Tiago Peixoto committed
754

755
def label_components(g, vprop=None, directed=None, attractors=False):
756
    """
757
    Label the components to which each vertex in the graph belongs. If the
758
759
    graph is directed, it finds the strongly connected components.

760
761
762
    A property map with the component labels is returned, together with an
    histogram of component labels.

763
764
    Parameters
    ----------
765
    g : :class:`~graph_tool.Graph`
766
        Graph to be used.
767
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
768
769
        Vertex property to store the component labels. If none is supplied, one
        is created.
770
    directed : bool (optional, default: ``None``)
771
772
        Treat graph as directed or not, independently of its actual
        directionality.
773
774
775
776
    attractors : bool (optional, default: ``False``)
        If ``True``, and the graph is directed, an additional array with Boolean
        values is returned, specifying if the strongly connected components are
        attractors or not.
777
778
779

    Returns
    -------
780
    comp : :class:`~graph_tool.PropertyMap`
781
        Vertex property map with component labels.
782
783
    hist : :class:`~numpy.ndarray`
        Histogram of component labels.
784
785
786
787
    is_attractor : :class:`~numpy.ndarray`
        A Boolean array specifying if the strongly connected components are
        attractors or not. This returned only if ``attractors == True``, and the
        graph is directed.
788
789
790
791
792
793

    Notes
    -----
    The components are arbitrarily labeled from 0 to N-1, where N is the total
    number of components.

794
    The algorithm runs in :math:`O(V + E)` time.
795
796
797

    Examples
    --------
798
799
800
801
802
803
    .. testcode::
       :hide:

       numpy.random.seed(43)
       gt.seed_rng(43)

804
805
    >>> g = gt.random_graph(100, lambda: (poisson(2), poisson(2)))
    >>> comp, hist, is_attractor = gt.label_components(g, attractors=True)
806
    >>> print(comp.a)
807
808
809
810
    [13 13 13 13 14 12 13 15 16 13 17 19 13 13 13 20 13 13 13 10 13 13 22 13 13
      4 13 13  2 23 13 13 24 13 13 26 27 13 13 13 13  0 13 13  3 13 13 13 28  1
      6 13 13 13 13  5 13 13 13 13 13 13 13  9 13 11 13 29 13 13 13 13 18 13 30
     31 13 13 32 13 33 34 35 13 13 21 13 25  8 36 13 13 13 13 13 37 13 13  7 13]
811
    >>> print(hist)
812
813
    [ 1  1  1  1  1  1  1  1  1  1  1  1  1 63  1  1  1  1  1  1  1  1  1  1  1
      1  1  1  1  1  1  1  1  1  1  1  1  1]
814
    >>> print(is_attractor)
815
816
817
818
    [ True False  True  True  True False False  True False  True  True  True
      True False  True False False False False False False False False False
     False False False False False False False False False  True False  True
     False False]
819
820
    """

821
    if vprop is None:
822
823
824
825
826
        vprop = g.new_vertex_property("int32_t")

    _check_prop_writable(vprop, name="vprop")
    _check_prop_scalar(vprop, name="vprop")

827
828
    if directed is not None:
        g = GraphView(g, directed=directed)
829

830
831
    hist = libgraph_tool_topology.\
               label_components(g._Graph__graph, _prop("v", g, vprop))
832
833
834
835
836
837
838
839
840

    if attractors and g.is_directed() and directed != False:
        is_attractor = numpy.ones(len(hist), dtype="bool")
        libgraph_tool_topology.\
               label_attractors(g._Graph__graph, _prop("v", g, vprop),
                                is_attractor)
        return vprop, hist, is_attractor
    else:
        return vprop, hist
841
842
843
844


def label_largest_component(g, directed=None):
    """
845
846
    Label the largest component in the graph. If the graph is directed, then the
    largest strongly connected component is labelled.
847
848
849
850
851
852
853
854
855
856
857
858
859
860

    A property map with a boolean label is returned.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    directed : bool (optional, default:None)
        Treat graph as directed or not, independently of its actual
        directionality.

    Returns
    -------
    comp : :class:`~graph_tool.PropertyMap`
861
         Boolean vertex property map which labels the largest component.
862
863
864
865
866
867
868

    Notes
    -----
    The algorithm runs in :math:`O(V + E)` time.

    Examples
    --------
869
870
871
872
873
874
875
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

876
877
    >>> g = gt.random_graph(100, lambda: poisson(1), directed=False)
    >>> l = gt.label_largest_component(g)
878
    >>> print(l.a)
879
880
881
    [0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0
     1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0
     0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 1 0]
882
    >>> u = gt.GraphView(g, vfilt=l)   # extract the largest component as a graph
883
    >>> print(u.num_vertices())
884
    18
885
886
887
888
    """

    label = g.new_vertex_property("bool")
    c, h = label_components(g, directed=directed)
889
    vfilt, inv = g.get_vertex_filter()
890
    label.fa = c.fa == h.argmax()
891
    return label
892

Tiago Peixoto's avatar
Tiago Peixoto committed
893

894
def label_out_component(g, root, label=None):
895
896
897
898
899
900
901
902
903
904
    """
    Label the out-component (or simply the component for undirected graphs) of a
    root vertex.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    root : :class:`~graph_tool.Vertex`
        The root vertex.
905
906
907
    label : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        If provided, this must be an initialized Boolean vertex property map
        where the out-component will be labeled.
908
909
910

    Returns
    -------
911
    label : :class:`~graph_tool.PropertyMap`
912
913
914
915
916
917
918
919
         Boolean vertex property map which labels the out-component.

    Notes
    -----
    The algorithm runs in :math:`O(V + E)` time.

    Examples
    --------
920
921
922
923
924
925
926
927
928
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.random_graph(100, lambda: poisson(2.2), directed=False)
    >>> l = gt.label_out_component(g, g.vertex(2))
929
    >>> print(l.a)
930
931
932
    [1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1
     1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0
     1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 0]
933
934
935

    The in-component can be obtained by reversing the graph.

Tiago Peixoto's avatar
Tiago Peixoto committed
936
    >>> l = gt.label_out_component(gt.GraphView(g, reversed=True, directed=True),
937
    ...                            g.vertex(1))
938
    >>> print(l.a)
939
940
941
    [0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 1 1 0 0 0 1 1 0 0 0 0 1 0 1
     1 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0
     1 0 0 0 0 1 1 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 1 0]
942
943
    """

944
945
946
947
948
    if label is None:
        label = g.new_vertex_property("bool")
    elif label.value_type() != "bool":
        raise ValueError("value type of `label` must be `bool`, not %s" %
                         label.value_type())
949
950
951
952
953
954
    libgraph_tool_topology.\
             label_out_component(g._Graph__graph, int(root),
                                 _prop("v", g, label))
    return label


955
def label_biconnected_components(g, eprop=None, vprop=None):
956
957
958
959
    """
    Label the edges of biconnected components, and the vertices which are
    articulation points.

960
961
962
963
    An edge property map with the component labels is returned, together a
    boolean vertex map marking the articulation points, and an histogram of
    component labels.

964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.

    eprop : :class:`~graph_tool.PropertyMap` (optional, default: None)
        Edge property to label the biconnected components.

    vprop : :class:`~graph_tool.PropertyMap` (optional, default: None)
        Vertex property to mark the articulation points. If none is supplied,
        one is created.


    Returns
    -------
    bicomp : :class:`~graph_tool.PropertyMap`
        Edge property map with the biconnected component labels.
    articulation : :class:`~graph_tool.PropertyMap`
        Boolean vertex property map which has value 1 for each vertex which is
        an articulation point, and zero otherwise.
    nc : int
        Number of biconnected components.

    Notes
    -----

    A connected graph is biconnected if the removal of any single vertex (and
    all edges incident on that vertex) can not disconnect the graph. More
    generally, the biconnected components of a graph are the maximal subsets of
    vertices such that the removal of a vertex from a particular component will
    not disconnect the component. Unlike connected components, vertices may
    belong to multiple biconnected components: those vertices that belong to
    more than one biconnected component are called "articulation points" or,
    equivalently, "cut vertices". Articulation points are vertices whose removal
    would increase the number of connected components in the graph. Thus, a
    graph without articulation points is biconnected. Vertices can be present in
    multiple biconnected components, but each edge can only be contained in a
    single biconnected component.

    The algorithm runs in :math:`O(V + E)` time.

    Examples
    --------
1007
1008
1009
1010
1011
1012
1013
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

Tiago Peixoto's avatar
Tiago Peixoto committed
1014
    >>> g = gt.random_graph(100, lambda: poisson(2), directed=False)
1015
    >>> comp, art, hist = gt.label_biconnected_components(g)
1016
    >>> print(comp.a)
1017
1018
1019
1020
1021
    [31 42 41 41 41 21  2 41 41 19 41 33 41 41 12 41 40 41 41 41 41 41 41  8 41
     10 41 32 28 30 41 41 41  5 41 41 41 41 39 38 41 41 41 41 45 44 41 41 22 41
     41 41  0 41 41 41 41 41 41 41 41  7 13 41 20 41 41 41 41 34  9 41 41  4 43
     18 41 41 15 29  1 41 41 41 41  6 41 25 23 35 16 24 37 11  3 36 17 26 27 14
     41]
1022
    >>> print(art.a)
1023
1024
1025
    [1 0 1 1 0 1 0 0 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0
     1 1 0 0 1 0 0 0 1 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 1
     1 0 0 0 0 0 0 1 1 0 0 0 1 0 1 1 0 0 0 1 0 0 0 1 0 0]
1026
    >>> print(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
1027
    [ 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
1028
      1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 56  1  1  1  1]
1029
    """
1030

1031
    if vprop is None:
1032
        vprop = g.new_vertex_property("bool")
1033
    if eprop is None:
1034
1035
1036
1037
1038
1039
1040
        eprop = g.new_edge_property("int32_t")

    _check_prop_writable(vprop, name="vprop")
    _check_prop_scalar(vprop, name="vprop")
    _check_prop_writable(eprop, name="eprop")
    _check_prop_scalar(eprop, name="eprop")

1041
1042
    g = GraphView(g, directed=False)
    hist = libgraph_tool_topology.\
1043
1044
             label_biconnected_components(g._Graph__graph, _prop("e", g, eprop),
                                          _prop("v", g, vprop))
1045
    return eprop, vprop, hist
1046

Tiago Peixoto's avatar
Tiago Peixoto committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
def kcore_decomposition(g, deg="out", vprop=None):
    """
    Perform a k-core decomposition of the given graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    deg : string
        Degree to be used for the decomposition. It can be either "in", "out" or
        "total", for in-, out-, or total degree of the vertices.
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vertex property to store the decomposition. If ``None`` is supplied,
        one is created.

    Returns
    -------
    kval : :class:`~graph_tool.PropertyMap`
        Vertex property map with the k-core decomposition, i.e. a given vertex v
        belongs to the ``kval[v]``-core.

    Notes
    -----

    The k-core is a maximal set of vertices such that its induced subgraph only
    contains vertices with degree larger than or equal to k.

    This algorithm is described in [batagelk-algorithm]_ and runs in :math:`O(V + E)`
    time.

    Examples
    --------

    >>> g = gt.collection.data["netscience"]
    >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
    >>> kcore = gt.kcore_decomposition(g)
    >>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=kcore, vertex_text=kcore, output="netsci-kcore.pdf")
    <...>

    .. testcode::
       :hide:

       gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=kcore, vertex_text=kcore, output="netsci-kcore.png")

    .. figure:: netsci-kcore.*
        :align: center

        K-core decomposition of a network of network scientists.

    References
    ----------
    .. [k-core] http://en.wikipedia.org/wiki/Degeneracy_%28graph_theory%29
1099
1100
1101
1102
1103
    .. [batagelk-algorithm]  Vladimir Batagelj, Matjaž Zaveršnik, "Fast
       algorithms for determining (generalized) core groups in social
       networks", Advances in Data Analysis and Classification
       Volume 5, Issue 2, pp 129-145 (2011), :DOI:`10.1007/s11634-010-0079-y`,
       :arxiv:`cs/0310049`
Tiago Peixoto's avatar
Tiago Peixoto committed
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125

    """

    if vprop is None:
        vprop = g.new_vertex_property("int32_t")

    _check_prop_writable(vprop, name="vprop")
    _check_prop_scalar(vprop, name="vprop")
    if deg not in ["in", "out", "total"]:
        raise ValueError("invalid degree: " + str(deg))

    if g.is_directed():
        if deg == "out":
            g = GraphView(g, reversed=True)
        if deg == "total":
            g = GraphView(g, directed=False)

    libgraph_tool_topology.\
               kcore_decomposition(g._Graph__graph, _prop("v", g, vprop),
                                   _degree(g, deg))
    return vprop

Tiago Peixoto's avatar
Tiago Peixoto committed
1126

1127
1128
1129
def shortest_distance(g, source=None, target=None, weights=None,
                      negative_weights=False, max_dist=None, directed=None,
                      dense=False, dist_map=None, pred_map=False):
1130
    """Calculate the distance from a source to a target vertex, or to of all
1131
1132
    vertices from a given source, or the all pairs shortest paths, if the source
    is not specified.
1133
1134
1135
1136
1137

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
1138
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
1139
        Source vertex of the search. If unspecified, the all pairs shortest
1140
        distances are computed.
1141
    target : :class:`~graph_tool.Vertex` or iterable of such objects (optional, default: ``None``)
1142
1143
        Target vertex (or vertices) of the search. If unspecified, the distance
        to all vertices from the source will be computed.
1144
1145
1146
1147
1148
1149
1150
    weights : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        The edge weights. If provided, the shortest path will correspond to the
        minimal sum of weights.
    negative_weights : ``bool`` (optional, default: ``False``)
        If `True`, this will trigger the use of Bellman-Ford algorithm.
        Ignored if ``source`` is ``None``.
    max_dist : scalar value (optional, default: ``None``)
1151
        If specified, this limits the maximum distance of the vertices
1152
1153
1154
        searched. This parameter has no effect if source is ``None``, or if
        `negative_weights=True`.
    directed : ``bool`` (optional, default:``None``)
1155
1156
        Treat graph as directed or not, independently of its actual
        directionality.
1157
1158
1159
    dense : ``bool`` (optional, default: ``False``)
        If ``True``, and source is ``None``, the Floyd-Warshall algorithm is used,
        otherwise the Johnson algorithm is used. If source is not ``None``, this option
1160
        has no effect.
1161
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
1162
1163
        Vertex property to store the distances. If none is supplied, one
        is created.
1164
1165
1166
    pred_map : ``bool`` (optional, default: ``False``)
        If ``True``, a vertex property map with the predecessors is returned.
        Ignored if ``source`` is ``None``.
1167
1168
1169
1170

    Returns
    -------
    dist_map : :class:`~graph_tool.PropertyMap`
1171
        Vertex property map with the distances from source. If source is ``None``,
1172
        it will have a vector value type, with the distances to every vertex.
1173
1174
    pred_map : :class:`~graph_tool.PropertyMap` (optional, if ``pred_map == True``)
        Vertex property map with the predecessors in the search tree.
1175
1176
1177
1178
1179
1180

    Notes
    -----

    If a source is given, the distances are calculated with a breadth-first
    search (BFS) or Dijkstra's algorithm [dijkstra]_, if weights are given. If
1181
1182
1183
1184
1185
    ``negative_weights == True``, the Bellman-Ford algorithm is used
    [bellman_ford]_, which accepts negative weights, as long as there are no
    negative loops. If source is not given, the distances are calculated with
    Johnson's algorithm [johnson-apsp]_. If dense=True, the Floyd-Warshall
    algorithm [floyd-warshall-apsp]_ is used instead.
1186
1187

    If source is specified, the algorithm runs in :math:`O(V + E)` time, or
1188
1189
1190
    :math:`O(V \log V)` if weights are given. If ``negative_weights == True``,
    the complexity is :math:`O(VE)`. If source is not specified, it runs in
    :math:`O(VE\log V)` time, or :math:`O(V^3)` if dense == True.
1191
1192
1193

    Examples
    --------
1194
1195
1196
1197
1198
1199
1200
1201
    .. testcode::
       :hide:

       import numpy.random
       numpy.random.seed(42)
       gt.seed_rng(42)

    >>> from numpy.random import poisson
1202
1203
    >>> g = gt.random_graph(100, lambda: (poisson(3), poisson(3)))
    >>> dist = gt.shortest_distance(g, source=g.vertex(0))
1204
    >>> print(dist.a)
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
    [         0          1          5          4 2147483647          4
              9          5          8          5          7          6
              3          5          6          8          3          3
              5          6 2147483647          1          4          5
              5          2          5          7          4          5
              5          5          4          4          5          2
              5 2147483647          5          2 2147483647          6
              5          6          6          2          5          4
              3          6          5          4          4          5
              3          3          5          5          1          5
              4          6          3          4          3          3
              7          5          5          4 2147483647 2147483647
              2          5          3          5          5          6
              3          5          6          6          5          4
              5          3          6          3          4 2147483647
              4          6          4          4          4          4
              6          5          4          4]
    >>>
1223
    >>> dist = gt.shortest_distance(g)
1224
    >>> print(dist[g.vertex(0)].a)
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
    [         0          1          5          4 2147483647          4
              9          5          8          5          7          6
              3          5          6          8          3          3
              5          6 2147483647          1          4          5
              5          2          5          7          4          5
              5          5          4          4          5          2
              5 2147483647          5          2 2147483647          6
              5          6          6          2          5          4
              3          6          5          4          4          5
              3          3          5          5          1          5
              4          6          3          4          3          3
              7          5          5          4 2147483647 2147483647
              2          5          3          5          5          6
              3          5          6          6          5          4
              5          3          6          3          4 2147483647
              4          6          4          4          4          4
              6          5          4          4]
1242
    >>> dist = gt.shortest_distance(g, source=g.vertex(0), target=g.vertex(2))
1243
    >>> print(dist)
1244
1245
    5
    >>> dist = gt.shortest_distance(g, source=g.vertex(0), target=[g.vertex(2), g.vertex(6)])
1246
    >>> print(dist)
1247
    [5 9]
1248
1249
1250
1251

    References
    ----------
    .. [bfs] Edward Moore, "The shortest path through a maze", International
1252
       Symposium on the Theory of Switching (1959), Harvard University Press.
Tiago Peixoto's avatar
Tiago Peixoto committed
1253
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
1254
1255
    .. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
       graphs." Numerische Mathematik, 1:269-271, 1959.
Tiago Peixoto's avatar
Tiago Peixoto committed
1256
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
1257
1258
    .. [johnson-apsp] http://www.boost.org/libs/graph/doc/johnson_all_pairs_shortest.html
    .. [floyd-warshall-apsp] http://www.boost.org/libs/graph/doc/floyd_warshall_shortest.html
1259
    .. [bellman-ford] http://www.boost.org/libs/graph/doc/bellman_ford_shortest.html
1260
1261
    """

1262
1263
1264
1265
1266
1267
    if isinstance(target, collections.Iterable):
        target = numpy.asarray(target, dtype="int64")
    elif target is None:
        target = numpy.array([], dtype="int64")
    else:
        target = numpy.asarray([int(target)], dtype="int64")
1268

1269
    if weights is None:
1270
1271
1272
1273
        dist_type = 'int32_t'
    else:
        dist_type = weights.value_type()

1274
1275
    if dist_map is None:
        if source is not None:
1276
1277
1278
1279
1280
            dist_map = g.new_vertex_property(dist_type)
        else:
            dist_map = g.new_vertex_property("vector<%s>" % dist_type)

    _check_prop_writable(dist_map, name="dist_map")
1281
    if source is not None:
1282
1283
1284
1285
        _check_prop_scalar(dist_map, name="dist_map")
    else:
        _check_prop_vector(dist_map, name="dist_map")

1286
    if max_dist is None:
1287
1288
        max_dist = 0

1289
    if directed is not None:
1290
1291
1292
        u = GraphView(g, directed=directed)
    else:
        u = g
1293

1294
1295
1296
1297
    if source is not None:
        pmap = g.copy_property(u.vertex_index, value_type="int64_t")
        libgraph_tool_topology.get_dists(g._Graph__graph,
                                         int(source),
1298
                                         target,
1299
1300
1301
                                         _prop("v", g, dist_map),
                                         _prop("e", g, weights),
                                         _prop("v", g, pmap),
1302
1303
                                         float(max_dist),
                                         negative_weights)
1304
1305
    else:
        libgraph_tool_topology.get_all_dists(u._Graph__graph,
1306
                                             _prop("v", g, dist_map),