__init__.py 65.8 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-2014 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,\
Tiago Peixoto's avatar
Tiago Peixoto committed
70
     libcore, _get_rng, _degree
71
import random, sys, numpy
72
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
73
           "max_cardinality_matching", "max_independent_vertex_set",
74
           "min_spanning_tree", "random_spanning_tree", "dominator_tree",
Tiago Peixoto's avatar
Tiago Peixoto committed
75
           "topological_sort", "transitive_closure", "tsp_tour",
76
77
           "sequential_vertex_coloring", "label_components",
           "label_largest_component", "label_biconnected_components",
Tiago Peixoto's avatar
Tiago Peixoto committed
78
79
80
           "label_out_component", "kcore_decomposition", "shortest_distance",
           "shortest_path", "pseudo_diameter", "is_bipartite", "is_DAG",
           "is_planar", "make_maximal_planar", "similarity", "edge_reciprocity"]
81
82
83
84
85
86
87
88
89
90


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
91
        Second graph to be compared.
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    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
    --------
118
119
120
121
122
123
124
    .. testcode::
       :hide:

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

125
126
127
128
    >>> g = gt.random_graph(100, lambda: (3,3))
    >>> u = g.copy()
    >>> gt.similarity(u, g)
    1.0
Tiago Peixoto's avatar
Tiago Peixoto committed
129
    >>> gt.random_rewire(u)
Tiago Peixoto's avatar
Tiago Peixoto committed
130
    19
131
    >>> gt.similarity(u, g)
Tiago Peixoto's avatar
Tiago Peixoto committed
132
    0.03
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    """

    if label1 is None:
        label1 = g1.vertex_index
    if label2 is None:
        label2 = g2.vertex_index
    if label1.value_type() != label2.value_type():
        raise ValueError("label property maps must be of the same type")
    s = libgraph_tool_topology.\
           similarity(g1._Graph__graph, g2._Graph__graph,
                      _prop("v", g1, label1), _prop("v", g1, label2))
    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
149

Tiago Peixoto's avatar
Tiago Peixoto committed
150

151
def isomorphism(g1, g2, isomap=False):
152
153
154
155
156
157
158
    r"""Check whether two graphs are isomorphic.

    If `isomap` is True, a vertex :class:`~graph_tool.PropertyMap` with the
    isomorphism mapping is returned as well.

    Examples
    --------
159
160
161
162
163
164
165
    .. testcode::
       :hide:

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

166
167
168
169
170
171
172
173
174
    >>> 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

175
    """
176
177
    imap = g1.new_vertex_property("int32_t")
    iso = libgraph_tool_topology.\
178
           check_isomorphism(g1._Graph__graph, g2._Graph__graph,
Tiago Peixoto's avatar
Tiago Peixoto committed
179
                             _prop("v", g1, imap))
180
181
182
183
184
    if isomap:
        return iso, imap
    else:
        return iso

Tiago Peixoto's avatar
Tiago Peixoto committed
185

186
187
188
def subgraph_isomorphism(sub, g, max_n=0, vertex_label=None, edge_label=None,
                         random=False):
    r"""Obtain all subgraph isomorphisms of `sub` in `g` (or at most `max_n` subgraphs, if `max_n > 0`).
189

190

Tiago Peixoto's avatar
Tiago Peixoto committed
191
192
193
194
195
196
    Parameters
    ----------
    sub : :class:`~graph_tool.Graph`
        Subgraph for which to be searched.
    g : :class:`~graph_tool.Graph`
        Graph in which the search is performed.
197
    max_n : int (optional, default: `0`)
Tiago Peixoto's avatar
Tiago Peixoto committed
198
199
        Maximum number of matches to find. If `max_n == 0`, all matches are
        found.
200
201
202
203
204
205
206
207
    vertex_label : pair of :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        If provided, this should be a pair of :class:`~graph_tool.PropertyMap`
        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`)
        If provided, this should be a pair of :class:`~graph_tool.PropertyMap`
        objects, belonging to `sub` and `g` (in this order), which specify edge labels
        which should match, in addition to the topological isomorphism.
Tiago Peixoto's avatar
Tiago Peixoto committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    random : bool (optional, default: False)
        If `True`, the vertices of `g` are indexed in random order before
        the search.

    Returns
    -------
    vertex_maps : list of :class:`~graph_tool.PropertyMap` objects
        List containing vertex property map objects which indicate different
        isomorphism mappings. The property maps vertices in `sub` to the
        corresponding vertex index in `g`.
    edge_maps : list of :class:`~graph_tool.PropertyMap` objects
        List containing edge property map objects which indicate different
        isomorphism mappings. The property maps edges in `sub` to the
        corresponding edge index in `g`.

    Notes
    -----
225
226
227
228
229
    Here "subgraph" does not mean "node-induced subgraph", i.e. there may exist
    an edge in the matched subgraph in `g` that does not exist in `sub`. For
    node-induced subgraph isomorphism, see the :func:`+graph_tool.clustering.motifs`
    function.

Tiago Peixoto's avatar
Tiago Peixoto committed
230
231
232
233
    The algorithm used is described in [ullmann-algorithm-1976]_. It has a
    worse-case complexity of :math:`O(N_g^{N_{sub}})`, but for random graphs it
    typically has a complexity of :math:`O(N_g^\gamma)` with :math:`\gamma`
    depending sub-linearly on the size of `sub`.
234
235
236

    Examples
    --------
237
238
239
240
241
242
243
244
    .. testcode::
       :hide:

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

    >>> from numpy.random import poisson
Tiago Peixoto's avatar
Tiago Peixoto committed
245
    >>> g = gt.random_graph(30, lambda: (poisson(6.1), poisson(6.1)))
246
    >>> sub = gt.random_graph(10, lambda: (poisson(1.9), poisson(1.9)))
247
    >>> vm, em = gt.subgraph_isomorphism(sub, g)
248
    >>> print(len(vm))
Tiago Peixoto's avatar
Tiago Peixoto committed
249
    35
250
    >>> for i in range(len(vm)):
251
252
253
254
255
256
257
258
259
260
    ...   g.set_vertex_filter(None)
    ...   g.set_edge_filter(None)
    ...   vmask, emask = gt.mark_subgraph(g, sub, vm[i], em[i])
    ...   g.set_vertex_filter(vmask)
    ...   g.set_edge_filter(emask)
    ...   assert(gt.isomorphism(g, sub))
    >>> 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
261
262
263
    >>> ewidth.a *= 2
    >>> gt.graph_draw(g, vertex_fill_color=vmask, edge_color=emask,
    ...               edge_pen_width=ewidth, output_size=(200, 200),
264
    ...               output="subgraph-iso-embed.pdf")
265
    <...>
Tiago Peixoto's avatar
Tiago Peixoto committed
266
    >>> gt.graph_draw(sub, output_size=(200, 200), output="subgraph-iso.pdf")
267
268
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
269
270
271
272
273
274
275
276
    .. 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
277
278
    .. image:: subgraph-iso.*
    .. image:: subgraph-iso-embed.*
279

280

Tiago Peixoto's avatar
Tiago Peixoto committed
281
    **Left:** Subgraph searched, **Right:** One isomorphic subgraph found in main graph.
282
283
284

    References
    ----------
285
    .. [ullmann-algorithm-1976] Ullmann, J. R., "An algorithm for subgraph
286
       isomorphism", Journal of the ACM 23 (1): 31-42, 1976, :doi:`10.1145/321921.321925`
287
    .. [subgraph-isormophism-wikipedia] http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem
288
289

    """
290
291
    if sub.num_vertices() == 0:
        raise ValueError("Cannot search for an empty subgraph.")
292
293
294
295
296
297
298
299
    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!")
    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!")
300
301
    vmaps = []
    emaps = []
302
    if random:
303
        rng = _get_rng()
304
    else:
305
        rng = libcore.rng_t()
306
307
    libgraph_tool_topology.\
           subgraph_isomorphism(sub._Graph__graph, g._Graph__graph,
308
309
310
311
                                _prop("v", sub, vertex_label[0]),
                                _prop("v", g, vertex_label[1]),
                                _prop("e", sub, edge_label[0]),
                                _prop("e", g, edge_label[1]),
312
                                vmaps, emaps, max_n, rng)
313
    for i in range(len(vmaps)):
314
315
316
317
        vmaps[i] = PropertyMap(vmaps[i], sub, "v")
        emaps[i] = PropertyMap(emaps[i], sub, "e")
    return vmaps, emaps

Tiago Peixoto's avatar
Tiago Peixoto committed
318

319
320
321
322
323
324
325
326
327
328
def mark_subgraph(g, sub, vmap, emap, vmask=None, emask=None):
    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
329
    `sub`.
330
    """
331
    if vmask is None:
332
        vmask = g.new_vertex_property("bool")
333
    if emask is None:
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        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
        for ew in w.out_edges():
            for ev in v.out_edges():
                if emap[ev] == g.edge_index[ew]:
                    emask[ew] = True
                    break
    return vmask, emask
348

Tiago Peixoto's avatar
Tiago Peixoto committed
349

350
def min_spanning_tree(g, weights=None, root=None, tree_map=None):
351
352
353
354
355
356
357
    """
    Return the minimum spanning tree of a given graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
358
    weights : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
359
360
        The edge weights. If provided, the minimum spanning tree will minimize
        the edge weights.
361
    root : :class:`~graph_tool.Vertex` (optional, default: `None`)
362
        Root of the minimum spanning tree. If this is provided, Prim's algorithm
363
        is used. Otherwise, Kruskal's algorithm is used.
364
    tree_map : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        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
    --------
380
381
382
383
384
385
386
387
    .. testcode::
       :hide:

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

    >>> from numpy.random import random
388
389
390
    >>> 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
391
    ...    weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
392
    >>> tree = gt.min_spanning_tree(g, weights=weight)
393
    >>> gt.graph_draw(g, pos=pos, output="triang_orig.pdf")
394
395
    <...>
    >>> g.set_edge_filter(tree)
396
    >>> gt.graph_draw(g, pos=pos, output="triang_min_span_tree.pdf")
397
398
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
399
400
401
402
403
    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="triang_orig.png")
       gt.graph_draw(g, pos=pos, output="triang_min_span_tree.png")
404

405
    .. image:: triang_orig.*
Tiago Peixoto's avatar
Tiago Peixoto committed
406
        :width: 400px
407
    .. image:: triang_min_span_tree.*
Tiago Peixoto's avatar
Tiago Peixoto committed
408
        :width: 400px
409
410

    *Left:* Original graph, *Right:* The minimum spanning tree.
411
412
413
414
415

    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
416
417
       American Mathematical Society, volume 7, pages 48-50, 1956.
       :doi:`10.1090/S0002-9939-1956-0078686-7`
418
419
420
421
422
    .. [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
    """
423
    if tree_map is None:
424
425
426
427
        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.")

428
429
430
431
432
433
434
435
436
437
438
    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))
439
    return tree_map
440

Tiago Peixoto's avatar
Tiago Peixoto committed
441

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def random_spanning_tree(g, weights=None, root=None, tree_map=None):
    """
    Return a random spanning tree of a given graph, which can be directed or
    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
    -----
    The typical running time for random graphs is :math:`O(N\log N)`.

    Examples
    --------
471
472
473
474
475
476
477
478
    .. testcode::
       :hide:

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

    >>> from numpy.random import random
479
480
481
482
483
484
485
486
    >>> g, pos = gt.triangulation(random((400, 2)) * 10, type="delaunay")
    >>> 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)
    >>> gt.graph_draw(g, pos=pos, output="rtriang_orig.pdf")
    <...>
    >>> g.set_edge_filter(tree)
Tiago Peixoto's avatar
Tiago Peixoto committed
487
    >>> gt.graph_draw(g, pos=pos, output="triang_random_span_tree.pdf")
488
489
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
490
491
492
493
494
    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="rtriang_orig.png")
       gt.graph_draw(g, pos=pos, output="triang_random_span_tree.png")
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

    .. image:: rtriang_orig.*
        :width: 400px
    .. image:: triang_random_span_tree.*
        :width: 400px

    *Left:* Original graph, *Right:* A random spanning tree.

    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)
523
524
525
    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) )
526
527
528
529

    libgraph_tool_topology.\
        random_spanning_tree(g._Graph__graph, int(root),
                             _prop("e", g, weights),
530
                             _prop("e", g, tree_map), _get_rng())
531
532
533
    return tree_map


Tiago Peixoto's avatar
Tiago Peixoto committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
    --------
561
562
563
564
565
566
567
    .. testcode::
       :hide:

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

Tiago Peixoto's avatar
Tiago Peixoto committed
568
569
570
    >>> g = gt.random_graph(100, lambda: (2, 2))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
571
    >>> root = [v for v in g.vertices() if v.in_degree() == 0]
Tiago Peixoto's avatar
Tiago Peixoto committed
572
    >>> dom = gt.dominator_tree(g, root[0])
573
    >>> print(dom.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
574
    [ 0  0  0  0  0  0 62  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
575
      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
576
577
      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
578
579
580

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

    """
584
    if dom_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
585
586
587
        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" +
588
589
                         " int32_t.")
    if not g.is_directed():
Tiago Peixoto's avatar
Tiago Peixoto committed
590
        raise ValueError("dominator tree requires a directed graph.")
591
    libgraph_tool_topology.\
Tiago Peixoto's avatar
Tiago Peixoto committed
592
593
594
               dominator_tree(g._Graph__graph, int(root),
                              _prop("v", g, dom_map))
    return dom_map
595

Tiago Peixoto's avatar
Tiago Peixoto committed
596

597
def topological_sort(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
    """
    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
    such that if edge (u,v) appears in the graph, then v comes before u in the
    ordering. The graph must be a directed acyclic graph (DAG).

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

    Examples
    --------
612
613
614
615
616
617
618
    .. testcode::
       :hide:

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

Tiago Peixoto's avatar
Tiago Peixoto committed
619
620
621
622
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
    >>> sort = gt.topological_sort(g)
623
    >>> print(sort)
Tiago Peixoto's avatar
Tiago Peixoto committed
624
625
    [ 1  7 17  0  9  2  3  4  5  6  8 10 11 12 13 25 16 23 27 28 19 29 14 15 18
     20 21 22 24 26]
Tiago Peixoto's avatar
Tiago Peixoto committed
626
627
628

    References
    ----------
629
    .. [topological-boost] http://www.boost.org/libs/graph/doc/topological_sort.html
Tiago Peixoto's avatar
Tiago Peixoto committed
630
631
632
633
    .. [topological-wiki] http://en.wikipedia.org/wiki/Topological_sorting

    """

634
    topological_order = Vector_int32_t()
Tiago Peixoto's avatar
Tiago Peixoto committed
635
636
637
638
639
    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).");
    return topological_order.a.copy()
640

Tiago Peixoto's avatar
Tiago Peixoto committed
641

642
def transitive_closure(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
643
644
645
646
647
648
649
650
651
652
653
654
655
    """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
    --------
656
657
658
659
660
661
662
    .. testcode::
       :hide:

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

Tiago Peixoto's avatar
Tiago Peixoto committed
663
664
665
666
667
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tc = gt.transitive_closure(g)

    References
    ----------
668
    .. [transitive-boost] http://www.boost.org/libs/graph/doc/transitive_closure.html
Tiago Peixoto's avatar
Tiago Peixoto committed
669
670
671
672
    .. [transitive-wiki] http://en.wikipedia.org/wiki/Transitive_closure

    """

673
674
675
676
677
678
679
    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
680

681
def label_components(g, vprop=None, directed=None, attractors=False):
682
    """
683
    Label the components to which each vertex in the graph belongs. If the
684
685
    graph is directed, it finds the strongly connected components.

686
687
688
    A property map with the component labels is returned, together with an
    histogram of component labels.

689
690
    Parameters
    ----------
691
    g : :class:`~graph_tool.Graph`
692
        Graph to be used.
693
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
694
695
        Vertex property to store the component labels. If none is supplied, one
        is created.
696
    directed : bool (optional, default: ``None``)
697
698
        Treat graph as directed or not, independently of its actual
        directionality.
699
700
701
702
    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.
703
704
705

    Returns
    -------
706
    comp : :class:`~graph_tool.PropertyMap`
707
        Vertex property map with component labels.
708
709
    hist : :class:`~numpy.ndarray`
        Histogram of component labels.
710
711
712
713
    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.
714
715
716
717
718
719

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

720
    The algorithm runs in :math:`O(V + E)` time.
721
722
723

    Examples
    --------
724
725
726
727
728
729
    .. testcode::
       :hide:

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

730
731
    >>> g = gt.random_graph(100, lambda: (poisson(2), poisson(2)))
    >>> comp, hist, is_attractor = gt.label_components(g, attractors=True)
732
    >>> print(comp.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
733
    [14 15 14 14 14  5 14 14 18 14 14  8 14 14 13 14 14 21 14 14  6 23 10 14 14
Tiago Peixoto's avatar
Tiago Peixoto committed
734
     14 24  4 14 14  0 14 14 14 25 14 14  1 14 26 14 19  9 14 14  3 14 14 27 28
Tiago Peixoto's avatar
Tiago Peixoto committed
735
     29 14 14  7 14 14 14 30 14 14 20 14  2 14 22 33 34 14 14 14 35 14 14 16 14
Tiago Peixoto's avatar
Tiago Peixoto committed
736
     11 36 37 14 14 31 14 14 17 14 14 14 14 14  0 14 38 39 32 14 12 14 40 14 14]
737
    >>> print(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
738
739
    [ 2  1  1  1  1  1  1  1  1  1  1  1  1  1 59  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  1]
740
    >>> print(is_attractor)
Tiago Peixoto's avatar
Tiago Peixoto committed
741
742
    [ True  True  True False False False  True  True False False False False
      True  True False False False False False False False False  True False
743
     False False False False False False False False False False False False
Tiago Peixoto's avatar
Tiago Peixoto committed
744
     False False False False False]
745
746
    """

747
    if vprop is None:
748
749
750
751
752
        vprop = g.new_vertex_property("int32_t")

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

753
754
    if directed is not None:
        g = GraphView(g, directed=directed)
755

756
757
    hist = libgraph_tool_topology.\
               label_components(g._Graph__graph, _prop("v", g, vprop))
758
759
760
761
762
763
764
765
766

    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
767
768
769
770


def label_largest_component(g, directed=None):
    """
771
772
    Label the largest component in the graph. If the graph is directed, then the
    largest strongly connected component is labelled.
773
774
775
776
777
778
779
780
781
782
783
784
785
786

    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`
787
         Boolean vertex property map which labels the largest component.
788
789
790
791
792
793
794

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

    Examples
    --------
795
796
797
798
799
800
801
    .. testcode::
       :hide:

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

802
803
    >>> g = gt.random_graph(100, lambda: poisson(1), directed=False)
    >>> l = gt.label_largest_component(g)
804
    >>> print(l.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
805
806
807
    [0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
     0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 1 0 0
     0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 1 1 0 1 0 0 0 0 0 1 0]
808
    >>> u = gt.GraphView(g, vfilt=l)   # extract the largest component as a graph
809
    >>> print(u.num_vertices())
Tiago Peixoto's avatar
Tiago Peixoto committed
810
    22
811
812
813
814
    """

    label = g.new_vertex_property("bool")
    c, h = label_components(g, directed=directed)
815
    vfilt, inv = g.get_vertex_filter()
816
    label.fa = c.fa == h.argmax()
817
    return label
818

Tiago Peixoto's avatar
Tiago Peixoto committed
819

820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
def label_out_component(g, root):
    """
    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.

    Returns
    -------
    comp : :class:`~graph_tool.PropertyMap`
         Boolean vertex property map which labels the out-component.

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

    Examples
    --------
843
844
845
846
847
848
849
850
851
    .. 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))
852
    >>> print(l.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
853
854
855
    [1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1
     1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1
     1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 0 1 0]
856
857
858

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

Tiago Peixoto's avatar
Tiago Peixoto committed
859
    >>> l = gt.label_out_component(gt.GraphView(g, reversed=True, directed=True),
860
    ...                            g.vertex(1))
861
    >>> print(l.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
862
863
864
    [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 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]
865
866
867
868
869
870
871
872
873
    """

    label = g.new_vertex_property("bool")
    libgraph_tool_topology.\
             label_out_component(g._Graph__graph, int(root),
                                 _prop("v", g, label))
    return label


874
def label_biconnected_components(g, eprop=None, vprop=None):
875
876
877
878
    """
    Label the edges of biconnected components, and the vertices which are
    articulation points.

879
880
881
882
    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.

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
    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
    --------
926
927
928
929
930
931
932
    .. testcode::
       :hide:

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

Tiago Peixoto's avatar
Tiago Peixoto committed
933
    >>> g = gt.random_graph(100, lambda: poisson(2), directed=False)
934
    >>> comp, art, hist = gt.label_biconnected_components(g)
935
    >>> print(comp.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
936
937
938
939
    [33 34 34 34 34 34  4 20 34 34 18 34 34 34 34 34 15 34 34 34 28 34 34 34 34
     34 34 34 34 34 34 11 14 34 34 34  3 34 34 34 34 34 34 34 34 27 34 34  7 10
     34 34 34 34 34 24 25 34  6 35 34 13 21 30 31 12  5 34  1 32 34 34 26 34 16
     34 34 23 34 34 34 34 34 36 34 34 34 34 34 29 22 17  0  2  8 37 34 38  9 19]
940
    >>> print(art.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
941
942
943
    [1 0 1 1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 1 0 0 1 0 1 0
     1 1 0 0 0 1 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1
     1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0]
944
    >>> print(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
945
    [ 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
Tiago Peixoto's avatar
Tiago Peixoto committed
946
      1  1  1  1  1  1  1  1  1 62  1  1  1  1]
947
    """
948

949
    if vprop is None:
950
        vprop = g.new_vertex_property("bool")
951
    if eprop is None:
952
953
954
955
956
957
958
        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")

959
960
    g = GraphView(g, directed=False)
    hist = libgraph_tool_topology.\
961
962
             label_biconnected_components(g._Graph__graph, _prop("e", g, eprop),
                                          _prop("v", g, vprop))
963
    return eprop, vprop, hist
964

Tiago Peixoto's avatar
Tiago Peixoto committed
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
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
1017
1018
1019
1020
1021
    .. [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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043

    """

    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
1044

1045
def shortest_distance(g, source=None, target=None, weights=None, max_dist=None,
1046
1047
                      directed=None, dense=False, dist_map=None,
                      pred_map=False):
1048
    """
1049
1050
1051
    Calculate the distance from a source to a target vertex, or to of all
    vertices from a given source, or the all pairs shortest paths, if the source
    is not specified.
1052
1053
1054
1055
1056
1057

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex` (optional, default: None)
1058
        Source vertex of the search. If unspecified, the all pairs shortest
1059
        distances are computed.
1060
1061
1062
    target : :class:`~graph_tool.Vertex` (optional, default: None)
        Target vertex of the search. If unspecified, the distance to all
        vertices from the source will be computed.
1063
1064
1065
1066
1067
    weights : :class:`~graph_tool.PropertyMap` (optional, default: None)
        The edge weights. If provided, the minimum spanning tree will minimize
        the edge weights.
    max_dist : scalar value (optional, default: None)
        If specified, this limits the maximum distance of the vertices
Tiago Peixoto's avatar
Tiago Peixoto committed
1068
        searched. This parameter has no effect if source is None.
1069
1070
1071
1072
    directed : bool (optional, default:None)
        Treat graph as directed or not, independently of its actual
        directionality.
    dense : bool (optional, default: False)
1073
1074
        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
1075
1076
1077
1078
        has no effect.
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: None)
        Vertex property to store the distances. If none is supplied, one
        is created.
1079
1080
1081
    pred_map : bool (optional, default: False)
        If true, a vertex property map with the predecessors is returned.
        Ignored if source=None.
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103

    Returns
    -------
    dist_map : :class:`~graph_tool.PropertyMap`
        Vertex property map with the distances from source. If source is 'None',
        it will have a vector value type, with the distances to every vertex.

    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
    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.

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

    Examples
    --------
1104
1105
1106
1107
1108
1109
1110
1111
    .. testcode::
       :hide:

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

    >>> from numpy.random import poisson
1112
1113
    >>> g = gt.random_graph(100, lambda: (poisson(3), poisson(3)))
    >>> dist = gt.shortest_distance(g, source=g.vertex(0))
1114
    >>> print(dist.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
    [         0          6          3          6 2147483647 2147483647
              6          5          2          4          5          6
              6          3          7          5          4          4
              3          4          2          4          3          3
              4          4          6          6          4          1
              5          2          4          5          3          5
              6          5          4          5 2147483647          9
              4          4          4          6          3          4
              6          6          3          2          4          4
              5          4          5          8          6          6
              5          5          4          5          6          3
              4          3          5          5 2147483647 2147483647
              5          5          8          3          7          4
              5          2          7          5          2          5
              5          5          7          7          4          3
              6          5          5          4          5          5
              4          4          6          5]
1132

1133
    >>> dist = gt.shortest_distance(g)
1134
    >>> print(dist[g.vertex(0)].a)
Tiago Peixoto's avatar
Tiago Peixoto committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
    [         0          6          3          6 2147483647 2147483647
              6          5          2          4          5          6
              6          3          7          5          4          4
              3          4          2          4          3          3
              4          4          6          6          4          1
              5          2          4          5          3          5
              6          5          4          5 2147483647          9
              4          4          4          6          3          4
              6          6          3          2          4          4
              5          4          5          8          6          6
              5          5          4          5          6          3
              4          3          5          5 2147483647 2147483647
              5          5          8          3          7          4
              5          2          7          5          2          5
              5          5          7          7          4          3
              6          5          5          4          5          5
              4          4          6          5]
1152
1153
1154
1155
1156

    References
    ----------
    .. [bfs] Edward Moore, "The shortest path through a maze", International
       Symposium on the Theory of Switching (1959), Harvard University
Tiago Peixoto's avatar
Tiago Peixoto committed
1157
1158
       Press;
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
1159
1160
    .. [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
1161
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
1162
1163
1164
1165
    .. [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
    """

1166
    if weights is None:
1167
1168
1169
1170
        dist_type = 'int32_t'
    else:
        dist_type = weights.value_type()

1171
1172
    if dist_map is None:
        if source is not None:
1173
1174
1175
1176
1177
            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")
1178
    if source is not None:
1179
1180
1181
1182
        _check_prop_scalar(dist_map, name="dist_map")
    else:
        _check_prop_vector(dist_map, name="dist_map")

1183
    if max_dist is None:
1184
1185
        max_dist = 0

1186
    if directed is not None:
1187
1188
1189
        u = GraphView(g, directed=directed)
    else:
        u = g
1190

1191
1192
1193
    if target is None:
        target = -1

1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
    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),
                                         int(target),
                                         _prop("v", g, dist_map),
                                         _prop("e", g, weights),
                                         _prop("v", g, pmap),
                                         float(max_dist))
    else:
        libgraph_tool_topology.get_all_dists(u._Graph__graph,
1205
                                             _prop("v", g, dist_map),
1206
                                             _prop("e", g, weights), dense)
1207

1208
1209
1210
1211

    if source is not None and target != -1:
        dist_map = dist_map[target]

1212
    if source is not None and pred_map:
1213
1214
1215
1216
        return dist_map, pmap
    else:
        return dist_map

Tiago Peixoto's avatar
Tiago Peixoto committed
1217

1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def shortest_path(g, source, target, weights=None, pred_map=None):
    """
    Return the shortest path from `source` to `target`.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex`
        Source vertex of the search.
Tiago Peixoto's avatar
Tiago Peixoto committed
1228
    target : :class:`~graph_tool.Vertex`
1229
1230
        Target vertex of the search.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: None)
Tiago Peixoto's avatar
Tiago Peixoto committed
1231
        The edge weights.
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
    pred_map :  :class:`~graph_tool.PropertyMap` (optional, default: None)
        Vertex property map with the predecessors in the search tree. If this is
        provided, the shortest paths are not computed, and are obtained directly
        from this map.

    Returns
    -------
    vertex_list : list of :class:`~graph_tool.Vertex`
        List of vertices from `source` to `target` in the shortest path.
    edge_list : list of :class:`~graph_tool.Edge`
        List of edges from `source` to `target` in the shortest path.

    Notes
    -----

    The paths are computed with a breadth-first search (BFS) or Dijkstra's
    algorithm [dijkstra]_, if weights are given.

    The algorithm runs in :math:`O(V + E)` time, or :math:`O(V \log V)` if
    weights are given.

    Examples
    --------
1255
1256
1257
1258
1259
1260
1261
1262
1263
    .. testcode::
       :hide:

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

    >>> from numpy.random import poisson
    >>> g = gt.random_graph(300, lambda: (poisson(4), poisson(4)))
1264
    >>> vlist, elist = gt.shortest_path(g, g.vertex(10), g.vertex(11))
1265
    >>> print([str(v) for v in vlist])
Tiago Peixoto's avatar
Tiago Peixoto committed
1266
    ['10', '131', '184', '265', '223', '11']
1267
    >>> print([str(e) for e in elist])
Tiago Peixoto's avatar
Tiago Peixoto committed
1268
    ['(10, 131)', '(131, 184)', '(184, 265)', '(265, 223)', '(223, 11)']
1269
1270
1271
1272
1273

    References
    ----------
    .. [bfs] Edward Moore, "The shortest path through a maze", International
       Symposium on the Theory of Switching (1959), Harvard University
Tiago Peixoto's avatar
Tiago Peixoto committed
1274
1275
       Press
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
1276
1277
    .. [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
1278
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
1279
1280
    """

1281
    if pred_map is None:
1282
1283
        pred_map = shortest_distance(g, source, target,
                                     weights=weights,
Tiago Peixoto's avatar
Tiago Peixoto committed
1284
                                     pred_map=True)[1]
1285

1286
    if pred_map[target] == int(target):  # no path to target
1287
1288
1289
1290
1291
        return [], []

    vlist = [target]
    elist = []

1292
    if weights is not None:
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
        max_w = weights.a.max() + 1
    else:
        max_w = None

    v = target
    while v != source:
        p = g.vertex(pred_map[v])
        min_w = max_w
        pe = None
        s = None
        for e in v.in_edges() if g.is_directed() else v.out_edges():
            s = e.source() if g.is_directed() else e.target()
            if s == p:
1306
                if weights is not None:
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
                    if weights[e] < min_w:
                        min_w = weights[e]
                        pe = e
                else:
                    pe = e
                    break
        elist.insert(0, pe)
        vlist.insert(0, p)
        v = p
    return vlist, elist

1318

Tiago Peixoto's avatar
Tiago Peixoto committed
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
def pseudo_diameter(g, source=None, weights=None):
    """
    Compute the pseudo-diameter of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex` (optional, default: `None`)
        Source vertex of the search. If not supplied, the first vertex
        in the graph will be chosen.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        The edge weights.

    Returns
    -------
    pseudo_diameter : int
        The pseudo-diameter of the graph.
    end_points : pair of :class:`~graph_tool.Vertex`
        The two vertices which correspond to the pseudo-diameter found.

    Notes
    -----

    The pseudo-diameter is an approximate graph diameter. It is obtained by
    starting from a vertex `source`, and finds a vertex `target` that is
    farthest away from `source`. This process is repeated by treating
    `target` as the new starting vertex, and ends when the graph distance no
    longer increases. A vertex from the last level set that has the smallest
    degree is chosen as the final starting vertex u, and a traversal is done
    to see if the graph distance can be increased. This graph distance is
    taken to be the pseudo-diameter.

    The paths are computed with a breadth-first search (BFS) or Dijkstra's
    algorithm [dijkstra]_, if weights are given.

    The algorithm runs in :math:`O(V + E)` time, or :math:`O(V \log V)` if
    weights are given.

    Examples
    --------
1360
1361
1362
1363
1364
1365
1366
1367
    .. testcode::
       :hide:

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

    >>> from numpy.random import poisson
Tiago Peixoto's avatar
Tiago Peixoto committed
1368
1369
    >>> g = gt.random_graph(300, lambda: (poisson(3), poisson(3)))
    >>> dist, ends = gt.pseudo_diameter(g)
1370
    >>> print(dist)
Tiago Peixoto's avatar
Tiago Peixoto committed
1371
    9.0
1372
    >>> print(int(ends[0]), int(ends[1]))
Tiago Peixoto's avatar
Tiago Peixoto committed
1373
    0 140
Tiago Peixoto's avatar
Tiago Peixoto committed
1374
1375
1376
1377
1378
1379
1380

    References
    ----------
    .. [pseudo-diameter] http://en.wikipedia.org/wiki/Distance_%28graph_theory%29
    """

    if source is None:
1381
        source = g.vertex(0, use_index=False)
Tiago Peixoto's avatar
Tiago Peixoto committed
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
    dist, target = 0, source
    while True:
        new_source = target
        new_target, new_dist = libgraph_tool_topology.get_diam(g._Graph__graph,
                                                               int(new_source),
                                                               _prop("e", g, weights))
        if new_dist > dist:
            target = new_target
            source = new_source
            dist = new_dist
        else:
            break
    return dist, (g.vertex(source), g.vertex(target))


1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
def is_bipartite(g, partition=False):
    """
    Test if the graph is bipartite.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    partition : bool (optional, default: ``False``)
        If ``True``, return the two partitions in case the graph is bipartite.

    Returns
    -------
    is_bipartite : bool
        Whether or not the graph is bipartite.
    partition : :class:`~graph_tool.PropertyMap` (only if `partition=True`)
        A vertex property map with the graph partitioning (or `None`) if the
        graph is not bipartite.

    Notes
    -----

    An undirected graph is bipartite if one can partition its set of vertices
    into two sets, such that all edges go from one set to the other.

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

    Examples
    --------
    >>> g = gt.lattice([10, 10])
    >>> is_bi, part = gt.is_bipartite(g, partition=True)
    >>> print(is_bi)
    True
Tiago Peixoto's avatar
Tiago Peixoto committed
1430
    >>> gt.graph_draw(g, vertex_fill_color=part, output_size=(300, 300), output="bipartite.pdf")
1431
1432
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
1433
1434
1435