__init__.py 32.3 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) 2007-2010 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`` - Important functions for 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
33
   isomorphism
34
35
   subgraph_isomorphism
   mark_subgraph
36
37
38
39
40
41
   min_spanning_tree
   dominator_tree
   topological_sort
   transitive_closure
   label_components
   label_biconnected_components
42
   is_planar
43
44
45

Contents
++++++++
46

47
48
"""

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

52
from .. core import _prop, Vector_int32_t, _check_prop_writable, \
53
54
55
56
57
     _check_prop_scalar,  _check_prop_vector, Graph, PropertyMap
import random, sys, numpy, weakref
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
           "min_spanning_tree", "dominator_tree", "topological_sort",
           "transitive_closure", "label_components",
58
59
           "label_biconnected_components", "shortest_distance",
           "shortest_path", "is_planar"]
60

Tiago Peixoto's avatar
Tiago Peixoto committed
61

62
def isomorphism(g1, g2, isomap=False):
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    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
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> 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

81
    """
82
83
    imap = g1.new_vertex_property("int32_t")
    iso = libgraph_tool_topology.\
84
           check_isomorphism(g1._Graph__graph, g2._Graph__graph,
Tiago Peixoto's avatar
Tiago Peixoto committed
85
                             _prop("v", g1, imap))
86
87
88
89
90
    if isomap:
        return iso, imap
    else:
        return iso

Tiago Peixoto's avatar
Tiago Peixoto committed
91

92
def subgraph_isomorphism(sub, g, max_n=0, random=True):
93
    r"""
94
95
    Obtain all subgraph isomorphisms of `sub` in `g` (or at most `max_n`
    subgraphs, if `max_n > 0`).
96

97
98
99
    If `random` = True, the vertices of `g` are indexed in random order before
    the search.

100
101
102
103
104
105
106
107
108
109
110
111
    It returns two lists, containing the vertex and edge property maps for `sub`
    with the isomorphism mappings. The value of the properties are the
    vertex/edge index of the corresponding vertex/edge in `g`.

    Examples
    --------
    >>> from numpy.random import seed, poisson
    >>> seed(42)
    >>> g = gt.random_graph(30, lambda: (poisson(6),poisson(6)))
    >>> sub = gt.random_graph(10, lambda: (poisson(1.8), poisson(1.9)))
    >>> vm, em = gt.subgraph_isomorphism(sub, g)
    >>> print len(vm)
Tiago Peixoto's avatar
Tiago Peixoto committed
112
    93
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    >>> for i in xrange(len(vm)):
    ...   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 *= 1.5
    >>> ewidth.a += 0.5
    >>> gt.graph_draw(g, vcolor=vmask, ecolor=emask, penwidth=ewidth,
    ...               output="subgraph-iso-embed.png")
    <...>
    >>> gt.graph_draw(sub, output="subgraph-iso.png")
    <...>

    .. image:: subgraph-iso.png
    .. image:: subgraph-iso-embed.png

    *Left:* Subgraph searched, *Right:* One isomorphic subgraph found in main
     graph.

    Notes
    -----
139
140
141
142
    The algorithm used is described in [ullmann-algorithm-1976]. It has
    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`.
143
144
145

    References
    ----------
146
    .. [ullmann-algorithm-1976] Ullmann, J. R., "An algorithm for subgraph
Tiago Peixoto's avatar
Tiago Peixoto committed
147
       isomorphism", Journal of the ACM 23 (1): 31–42, 1976, :doi:`10.1145/321921.321925`
148
    .. [subgraph-isormophism-wikipedia] http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem
149
150
151
152

    """
    # vertex and edge labels disabled for the time being, until GCC is capable
    # of compiling all the variants using reasonable amounts of memory
Tiago Peixoto's avatar
Tiago Peixoto committed
153
154
    vlabels=(None, None)
    elabels=(None, None)
155
156
    vmaps = []
    emaps = []
157
158
159
160
    if random:
        seed = numpy.random.randint(0, sys.maxint)
    else:
        seed = 42
161
162
163
164
165
166
    libgraph_tool_topology.\
           subgraph_isomorphism(sub._Graph__graph, g._Graph__graph,
                                _prop("v", sub, vlabels[0]),
                                _prop("v", g, vlabels[1]),
                                _prop("e", sub, elabels[0]),
                                _prop("e", g, elabels[1]),
167
                                vmaps, emaps, max_n, seed)
168
169
170
171
172
    for i in xrange(len(vmaps)):
        vmaps[i] = PropertyMap(vmaps[i], sub, "v")
        emaps[i] = PropertyMap(emaps[i], sub, "e")
    return vmaps, emaps

Tiago Peixoto's avatar
Tiago Peixoto committed
173

174
175
176
177
178
179
180
181
182
183
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
184
    `sub`.
185
    """
186
    if vmask is None:
187
        vmask = g.new_vertex_property("bool")
188
    if emask is None:
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        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
203

Tiago Peixoto's avatar
Tiago Peixoto committed
204

205
def min_spanning_tree(g, weights=None, root=None, tree_map=None):
206
207
208
209
210
211
212
213
214
215
216
    """
    Return the minimum spanning tree of a given graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: None)
        The edge weights. If provided, the minimum spanning tree will minimize
        the edge weights.
    root : :class:`~graph_tool.Vertex` (optional, default: None)
217
        Root of the minimum spanning tree. If this is provided, Prim's algorithm
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        is used. Otherwise, Kruskal's algorithm is used.
    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 algorithm runs with :math:`O(E\log E)` complexity, or :math:`O(E\log V)`
    if `root` is specified.

    Examples
    --------
    >>> from numpy.random import seed
    >>> seed(42)
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    >>> g, pos = gt.triangulation(random((400, 2)) * 10, type="delaunay")
    >>> weight = g.new_edge_property("double")
    >>> for e in g.edges():
    ...    weight[e] = norm(pos[e.target()].a - pos[e.source()].a)
    >>> tree = gt.min_spanning_tree(g, weights=weight)
    >>> graph_draw(g, pos=pos, pin=True, output="triang_orig.png")
    <...>
    >>> g.set_edge_filter(tree)
    >>> graph_draw(g, pos=pos, pin=True, output="triang_min_span_tree.png")
    <...>


    .. image:: triang_orig.png
    .. image:: triang_orig_span_tree.png

    *Left:* Original graph, *Right:* The minimum spanning tree.
253
254
255
256
257

    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
258
259
       American Mathematical Society, volume 7, pages 48-50, 1956.
       :doi:`10.1090/S0002-9939-1956-0078686-7`
260
261
262
263
264
    .. [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
    """
265
    if tree_map is None:
266
267
268
269
        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.")

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    try:
        g.stash_filter(directed=True)
        g.set_directed(False)
        if root is None:
            libgraph_tool_topology.\
                   get_kruskal_spanning_tree(g._Graph__graph,
                                             _prop("e", g, weights),
                                             _prop("e", g, tree_map))
        else:
            libgraph_tool_topology.\
                   get_prim_spanning_tree(g._Graph__graph, int(root),
                                          _prop("e", g, weights),
                                          _prop("e", g, tree_map))
    finally:
        g.pop_filter(directed=True)
285
    return tree_map
286

Tiago Peixoto's avatar
Tiago Peixoto committed
287

Tiago Peixoto's avatar
Tiago Peixoto committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> g = gt.random_graph(100, lambda: (2, 2))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
320
    >>> root = [v for v in g.vertices() if v.in_degree() == 0]
Tiago Peixoto's avatar
Tiago Peixoto committed
321
322
    >>> dom = gt.dominator_tree(g, root[0])
    >>> print dom.a
Tiago Peixoto's avatar
Tiago Peixoto committed
323
324
325
326
    [ 0  0 72  0  0  0  0  0  0  0  0  0  0  0 21  0  0  0  0  0  0  3  0  0  0
      0  0  0  0  0  0 41  0  0  0  0  0  0  0  0  0 11  0  0  0  0  0  0  0  0
      0  0  0  0  0  0  0  0  0  0  0  0  0  2  0  0  0  0  0  0  0  0  3  0  0
      0  0  0  0  0  2  0  0  0  0  0  0  0 80  0  0  0  0  0  0  0  0  0  0  0]
Tiago Peixoto's avatar
Tiago Peixoto committed
327
328
329

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

    """
333
    if dom_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
334
335
336
        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" +
337
338
                         " int32_t.")
    if not g.is_directed():
Tiago Peixoto's avatar
Tiago Peixoto committed
339
        raise ValueError("dominator tree requires a directed graph.")
340
    libgraph_tool_topology.\
Tiago Peixoto's avatar
Tiago Peixoto committed
341
342
343
               dominator_tree(g._Graph__graph, int(root),
                              _prop("v", g, dom_map))
    return dom_map
344

Tiago Peixoto's avatar
Tiago Peixoto committed
345

346
def topological_sort(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    """
    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
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tree = gt.min_spanning_tree(g)
    >>> g.set_edge_filter(tree)
    >>> sort = gt.topological_sort(g)
    >>> print sort
Tiago Peixoto's avatar
Tiago Peixoto committed
368
369
    [19 27  1  7  0 23  8 16  2 15 24 12  3  4 22  5  6  9 10 11 18 13 21 14 20
     17 25 26 28 29]
Tiago Peixoto's avatar
Tiago Peixoto committed
370
371
372

    References
    ----------
373
    .. [topological-boost] http://www.boost.org/libs/graph/doc/topological_sort.html
Tiago Peixoto's avatar
Tiago Peixoto committed
374
375
376
377
    .. [topological-wiki] http://en.wikipedia.org/wiki/Topological_sorting

    """

378
379
380
    topological_order = Vector_int32_t()
    libgraph_tool_topology.\
               topological_sort(g._Graph__graph, topological_order)
Tiago Peixoto's avatar
Tiago Peixoto committed
381
    return numpy.array(topological_order)
382

Tiago Peixoto's avatar
Tiago Peixoto committed
383

384
def transitive_closure(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    """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
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> g = gt.random_graph(30, lambda: (3, 3))
    >>> tc = gt.transitive_closure(g)

    References
    ----------
405
    .. [transitive-boost] http://www.boost.org/libs/graph/doc/transitive_closure.html
Tiago Peixoto's avatar
Tiago Peixoto committed
406
407
408
409
    .. [transitive-wiki] http://en.wikipedia.org/wiki/Transitive_closure

    """

410
411
412
413
414
415
416
    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
417

418
419
def label_components(g, vprop=None, directed=None):
    """
420
    Label the components to which each vertex in the graph belongs. If the
421
422
423
424
    graph is directed, it finds the strongly connected components.

    Parameters
    ----------
425
    g : :class:`~graph_tool.Graph`
426
427
        Graph to be used.

428
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: None)
429
430
431
432
433
434
435
436
437
        Vertex property to store the component labels. If none is supplied, one
        is created.

    directed : bool (optional, default:None)
        Treat graph as directed or not, independently of its actual
        directionality.

    Returns
    -------
438
    comp : :class:`~graph_tool.PropertyMap`
439
440
441
442
443
444
445
        Vertex property map with component labels.

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

446
    The algorithm runs in :math:`O(V + E)` time.
447
448
449

    Examples
    --------
450
451
452
    >>> from numpy.random import seed
    >>> seed(43)
    >>> g = gt.random_graph(100, lambda: (1, 1))
453
454
    >>> comp = gt.label_components(g)
    >>> print comp.get_array()
Tiago Peixoto's avatar
Tiago Peixoto committed
455
456
457
    [0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 2 0 0 0 1 0 0 0 0 1 1 0 2 0 1 1 0 0 0 0 1 0
     0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 2 0 0 0 0 1 0 0 0 0 0 1 0 0 0
     1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0]
458
459
    """

460
    if vprop is None:
461
462
463
464
465
        vprop = g.new_vertex_property("int32_t")

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

466
467
468
469
    try:
        if directed is not None:
            g.stash_filter(directed=True)
            g.set_directed(directed)
470

471
472
473
474
475
        libgraph_tool_topology.\
              label_components(g._Graph__graph, _prop("v", g, vprop))
    finally:
        if directed is not None:
            g.pop_filter(directed=True)
476
477
    return vprop

Tiago Peixoto's avatar
Tiago Peixoto committed
478

479
def label_biconnected_components(g, eprop=None, vprop=None):
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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
523
524
525
526
527
    """
    Label the edges of biconnected components, and the vertices which are
    articulation points.

    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
    --------
    >>> from numpy.random import seed
Tiago Peixoto's avatar
Tiago Peixoto committed
528
    >>> seed(43)
529
530
531
    >>> g = gt.random_graph(100, lambda: 2, directed=False)
    >>> comp, art, nc = gt.label_biconnected_components(g)
    >>> print comp.a
Tiago Peixoto's avatar
Tiago Peixoto committed
532
533
534
    [1 0 0 0 2 0 1 0 0 0 0 0 1 0 0 3 0 0 0 0 0 0 0 0 2 0 0 0 0 0 1 1 0 0 0 0 0
     1 0 1 3 0 2 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 3 0 0 0 0 0 0 0 0 0 1 0
     0 0 0 0 0 0 0 0 0 0 1 3 1 0 2 1 0 0 0 0 0 2 0 0 0 2]
535
536
537
538
539
540
541
542
    >>> print art.a
    [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 0 0]
    >>> print nc
    4

    """
543

544
    if vprop is None:
545
        vprop = g.new_vertex_property("bool")
546
    if eprop is None:
547
548
549
550
551
552
553
554
        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")

    g.stash_filter(directed=True)
555
556
557
558
559
560
561
    try:
        g.set_directed(False)
        nc = libgraph_tool_topology.\
             label_biconnected_components(g._Graph__graph, _prop("e", g, eprop),
                                          _prop("v", g, vprop))
    finally:
        g.pop_filter(directed=True)
562
    return eprop, vprop, nc
563

Tiago Peixoto's avatar
Tiago Peixoto committed
564

565
def shortest_distance(g, source=None, weights=None, max_dist=None,
566
567
                      directed=None, dense=False, dist_map=None,
                      pred_map=False):
568
569
570
571
572
573
574
575
576
    """
    Calculate the distance of all vertices from a given source, or the all pairs
    shortest paths, if the source is not specified.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex` (optional, default: None)
577
        Source vertex of the search. If unspecified, the all pairs shortest
578
579
580
581
582
583
        distances are computed.
    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
584
        are searched. This parameter has no effect if source is None.
585
586
587
588
    directed : bool (optional, default:None)
        Treat graph as directed or not, independently of its actual
        directionality.
    dense : bool (optional, default: False)
589
590
        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
591
592
593
594
        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.
595
596
597
    pred_map : bool (optional, default: False)
        If true, a vertex property map with the predecessors is returned.
        Ignored if source=None.
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624

    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
    --------
    >>> from numpy.random import seed, poisson
    >>> seed(42)
    >>> g = gt.random_graph(100, lambda: (poisson(3), poisson(3)))
    >>> dist = gt.shortest_distance(g, source=g.vertex(0))
    >>> print dist.get_array()
Tiago Peixoto's avatar
Tiago Peixoto committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
    [         0          3          5          4 2147483647          1
              6          3          4          4          5          4
              4          4          4          4          1          3
              3          1          5          3 2147483647          4
              2          5          5 2147483647          5          5
              4          3          3          2          4          4
              4          4          5          5 2147483647 2147483647
              4          4          3          5          3          4
     2147483647          3          2          4          5          5
              3          3          3          5          4 2147483647
              3          4          5          4          2 2147483647
              4          3          2          4          2 2147483647
              3          3          4          3          4          5
              2          3          6          4          4 2147483647
              6          4          5          1          4          5
              3          4          4          2          4          6
              3          4          2          4]
642
643
    >>> dist = gt.shortest_distance(g)
    >>> print array(dist[g.vertex(0)])
Tiago Peixoto's avatar
Tiago Peixoto committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    [         0          3          5          4 2147483647          1
              6          3          4          4          5          4
              4          4          4          4          1          3
              3          1          5          3 2147483647          4
              2          5          5 2147483647          5          5
              4          3          3          2          4          4
              4          4          5          5 2147483647 2147483647
              4          4          3          5          3          4
     2147483647          3          2          4          5          5
              3          3          3          5          4 2147483647
              3          4          5          4          2 2147483647
              4          3          2          4          2 2147483647
              3          3          4          3          4          5
              2          3          6          4          4 2147483647
              6          4          5          1          4          5
              3          4          4          2          4          6
              3          4          2          4]
661
662
663
664
665

    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
666
667
       Press;
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
668
669
    .. [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
670
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
671
672
673
674
    .. [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
    """

675
    if weights is None:
676
677
678
679
        dist_type = 'int32_t'
    else:
        dist_type = weights.value_type()

680
681
    if dist_map is None:
        if source is not None:
682
683
684
685
686
            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")
687
    if source is not None:
688
689
690
691
        _check_prop_scalar(dist_map, name="dist_map")
    else:
        _check_prop_vector(dist_map, name="dist_map")

692
    if max_dist is None:
693
694
        max_dist = 0

695
    if directed is not None:
696
697
698
699
        g.stash_filter(directed=True)
        g.set_directed(directed)

    try:
700
        if source is not None:
701
            pmap = g.copy_property(g.vertex_index, value_type="int64_t")
702
703
704
            libgraph_tool_topology.get_dists(g._Graph__graph, int(source),
                                             _prop("v", g, dist_map),
                                             _prop("e", g, weights),
705
                                             _prop("v", g, pmap),
706
707
708
709
710
711
712
                                             float(max_dist))
        else:
            libgraph_tool_topology.get_all_dists(g._Graph__graph,
                                                 _prop("v", g, dist_map),
                                                 _prop("e", g, weights), dense)

    finally:
713
        if directed is not None:
714
            g.pop_filter(directed=True)
715
    if source is not None and pred_map:
716
717
718
719
        return dist_map, pmap
    else:
        return dist_map

Tiago Peixoto's avatar
Tiago Peixoto committed
720

721
722
723
724
725
726
727
728
729
730
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
731
    target : :class:`~graph_tool.Vertex`
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
        Target vertex of the search.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: None)
        The edge weights. If provided, the minimum spanning tree will minimize
        the edge weights.
    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
    --------
    >>> from numpy.random import seed, poisson
    >>> seed(42)
    >>> g = gt.random_graph(300, lambda: (poisson(3), poisson(3)))
    >>> vlist, elist = gt.shortest_path(g, g.vertex(10), g.vertex(11))
    >>> print [str(v) for v in vlist]
Tiago Peixoto's avatar
Tiago Peixoto committed
764
    ['10', '66', '46', '266', '101', '143', '91', '275', '82', '11']
765
    >>> print [str(e) for e in elist]
Tiago Peixoto's avatar
Tiago Peixoto committed
766
    ['(10,66)', '(66,46)', '(46,266)', '(266,101)', '(101,143)', '(143,91)', '(91,275)', '(275,82)', '(82,11)']
767
768
769
770
771

    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
772
773
       Press
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
774
775
    .. [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
776
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
777
778
    """

779
    if pred_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
780
781
        pred_map = shortest_distance(g, source, weights=weights,
                                     pred_map=True)[1]
782

Tiago Peixoto's avatar
Tiago Peixoto committed
783
    if pred_map[target] == int(target):  # no path to source
784
785
786
787
788
        return [], []

    vlist = [target]
    elist = []

789
    if weights is not None:
790
791
792
793
794
795
796
797
798
799
800
801
802
        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:
803
                if weights is not None:
804
805
806
807
808
809
810
811
812
813
814
                    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

815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860

def is_planar(g, embedding=False, kuratowski=False):
    """
    Test if the graph is planar.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    embedding : bool (optional, default: False)
        If true, return a mapping from vertices to the clockwise order of
        out-edges in the planar embedding.
    kuratowski : bool (optional, default: False)
        If true, the minimal set of edges that form the obstructing Kuratowski
        subgraph will be returned as a property map, if the graph is not planar.

    Returns
    -------
    is_planar : bool
        Whether or not the graph is planar.
    embedding : :class:`~graph_tool.PropertyMap` (only if `embedding=True`)
        A vertex property map with the out-edges indexes in clockwise order in
        the planar embedding,
    kuratowski : :class:`~graph_tool.PropertyMap` (only if `kuratowski=True`)
        An edge property map with the minimal set of edges that form the
        obstructing Kuratowski subgraph (if the value of kuratowski[e] is 1,
        the edge belongs to the set)

    Notes
    -----

    A graph is planar if it can be drawn in two-dimensional space without any of
    its edges crossing. This algorithm performs the Boyer-Myrvold planarity
    testing [boyer-myrvold]_. See [boost-planarity]_ for more details.

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

    Examples
    --------
    >>> from numpy.random import seed, random
    >>> seed(42)
    >>> g = gt.triangulation(random((100,2)))[0]
    >>> p, embed_order = gt.is_planar(g, embedding=True)
    >>> print p
    True
    >>> print list(embed_order[g.vertex(0)])
Tiago Peixoto's avatar
Tiago Peixoto committed
861
    [0, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
862
863
864
865
866
    >>> g = gt.random_graph(100, lambda: 4, directed=False)
    >>> p, kur = gt.is_planar(g, kuratowski=True)
    >>> print p
    False
    >>> g.set_edge_filter(kur, True)
867
    >>> gt.graph_draw(g, output="kuratowski.png")
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    <...>

    .. figure:: kuratowski.png
        :align: center

        Obstructing Kuratowski subgraph of a random graph.

    References
    ----------
    .. [boyer-myrvold] John M. Boyer and Wendy J. Myrvold, "On the Cutting Edge:
       Simplified O(n) Planarity by Edge Addition Journal of Graph Algorithms
       and Applications", 8(2): 241-273, 2004.
    .. [boost-planarity] http://www.boost.org/libs/graph/doc/boyer_myrvold.html
    """

    g.stash_filter(directed=True)
    g.set_directed(False)

    if embedding:
        embed = g.new_vertex_property("vector<int>")
    else:
        embed = None

    if kuratowski:
        kur = g.new_edge_property("bool")
    else:
        kur = None

    try:
        is_planar = libgraph_tool_topology.is_planar(g._Graph__graph,
                                                     _prop("v", g, embed),
                                                     _prop("e", g, kur))
    finally:
        g.pop_filter(directed=True)

    ret = [is_planar]
904
    if embed is not None:
905
        ret.append(embed)
906
    if kur is not None:
907
908
909
910
911
        ret.append(kur)
    if len(ret) == 1:
        return ret[0]
    else:
        return tuple(ret)