__init__.py 45.7 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-2012 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
41
42
43
44
45
   min_spanning_tree
   dominator_tree
   topological_sort
   transitive_closure
   label_components
   label_biconnected_components
46
   label_largest_component
47
   is_planar
Tiago Peixoto's avatar
Tiago Peixoto committed
48
   edge_reciprocity
49
50
51

Contents
++++++++
52

53
54
"""

55
56
from __future__ import division, absolute_import, print_function

Tiago Peixoto's avatar
Tiago Peixoto committed
57
from .. dl_import import dl_import
58
dl_import("from . import libgraph_tool_topology")
59

60
from .. import _prop, Vector_int32_t, _check_prop_writable, \
61
     _check_prop_scalar, _check_prop_vector, Graph, PropertyMap, GraphView
62
63
from .. flow import libgraph_tool_flow
import random, sys, numpy
64
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
65
           "max_cardinality_matching", "max_independent_vertex_set",
66
           "min_spanning_tree", "dominator_tree", "topological_sort",
67
           "transitive_closure", "label_components", "label_largest_component",
68
           "label_biconnected_components", "shortest_distance", "shortest_path",
Tiago Peixoto's avatar
Tiago Peixoto committed
69
           "pseudo_diameter", "is_planar", "similarity", "edge_reciprocity"]
70
71
72
73
74
75
76
77
78
79


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
80
        Second graph to be compared.
81
82
83
84
85
86
87
88
89
90
91
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    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
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> g = gt.random_graph(100, lambda: (3,3))
    >>> u = g.copy()
    >>> gt.similarity(u, g)
    1.0
    >>> gt.random_rewire(u);
    >>> gt.similarity(u, g)
    0.03333333333333333
    """

    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
132

Tiago Peixoto's avatar
Tiago Peixoto committed
133

134
def isomorphism(g1, g2, isomap=False):
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    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

153
    """
154
155
    imap = g1.new_vertex_property("int32_t")
    iso = libgraph_tool_topology.\
156
           check_isomorphism(g1._Graph__graph, g2._Graph__graph,
Tiago Peixoto's avatar
Tiago Peixoto committed
157
                             _prop("v", g1, imap))
158
159
160
161
162
    if isomap:
        return iso, imap
    else:
        return iso

Tiago Peixoto's avatar
Tiago Peixoto committed
163

164
def subgraph_isomorphism(sub, g, max_n=0, random=False):
165
    r"""
166
167
    Obtain all subgraph isomorphisms of `sub` in `g` (or at most `max_n`
    subgraphs, if `max_n > 0`).
168

169
170
171
    If `random` = True, the vertices of `g` are indexed in random order before
    the search.

172
173
174
175
176
177
178
179
180
181
182
    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)
183
    >>> print(len(vm))
184
    102
185
    >>> for i in range(len(vm)):
186
187
188
189
190
191
192
193
194
195
    ...   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
196
197
198
    >>> ewidth.a *= 2
    >>> gt.graph_draw(g, vertex_fill_color=vmask, edge_color=emask,
    ...               edge_pen_width=ewidth, output_size=(200, 200),
199
    ...               output="subgraph-iso-embed.pdf")
200
    <...>
Tiago Peixoto's avatar
Tiago Peixoto committed
201
    >>> gt.graph_draw(sub, output_size=(200, 200), output="subgraph-iso.pdf")
202
203
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
204
205
    .. image:: subgraph-iso.*
    .. image:: subgraph-iso-embed.*
206

207

Tiago Peixoto's avatar
Tiago Peixoto committed
208
    **Left:** Subgraph searched, **Right:** One isomorphic subgraph found in main graph.
209
210
211

    Notes
    -----
212
213
214
215
    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`.
216
217
218

    References
    ----------
219
    .. [ullmann-algorithm-1976] Ullmann, J. R., "An algorithm for subgraph
Tiago Peixoto's avatar
Tiago Peixoto committed
220
       isomorphism", Journal of the ACM 23 (1): 31–42, 1976, :doi:`10.1145/321921.321925`
221
    .. [subgraph-isormophism-wikipedia] http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem
222
223
224
225

    """
    # 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
226
227
    vlabels=(None, None)
    elabels=(None, None)
228
229
    vmaps = []
    emaps = []
230
    if random:
231
        seed = numpy.random.randint(0, sys.maxsize)
232
233
    else:
        seed = 42
234
235
236
237
238
239
    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]),
240
                                vmaps, emaps, max_n, seed)
241
    for i in range(len(vmaps)):
242
243
244
245
        vmaps[i] = PropertyMap(vmaps[i], sub, "v")
        emaps[i] = PropertyMap(emaps[i], sub, "e")
    return vmaps, emaps

Tiago Peixoto's avatar
Tiago Peixoto committed
246

247
248
249
250
251
252
253
254
255
256
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
257
    `sub`.
258
    """
259
    if vmask is None:
260
        vmask = g.new_vertex_property("bool")
261
    if emask is None:
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        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
276

Tiago Peixoto's avatar
Tiago Peixoto committed
277

278
def min_spanning_tree(g, weights=None, root=None, tree_map=None):
279
280
281
282
283
284
285
286
287
288
289
    """
    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)
290
        Root of the minimum spanning tree. If this is provided, Prim's algorithm
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        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
    --------
Tiago Peixoto's avatar
Tiago Peixoto committed
308
    >>> from numpy.random import seed, random
309
    >>> seed(42)
310
311
312
    >>> 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
313
    ...    weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
314
    >>> tree = gt.min_spanning_tree(g, weights=weight)
315
    >>> gt.graph_draw(g, pos=pos, output="triang_orig.pdf")
316
317
    <...>
    >>> g.set_edge_filter(tree)
318
    >>> gt.graph_draw(g, pos=pos, output="triang_min_span_tree.pdf")
319
320
321
    <...>


322
    .. image:: triang_orig.*
Tiago Peixoto's avatar
Tiago Peixoto committed
323
        :width: 400px
324
    .. image:: triang_min_span_tree.*
Tiago Peixoto's avatar
Tiago Peixoto committed
325
        :width: 400px
326
327

    *Left:* Original graph, *Right:* The minimum spanning tree.
328
329
330
331
332

    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
333
334
       American Mathematical Society, volume 7, pages 48-50, 1956.
       :doi:`10.1090/S0002-9939-1956-0078686-7`
335
336
337
338
339
    .. [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
    """
340
    if tree_map is None:
341
342
343
344
        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.")

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    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)
360
    return tree_map
361

Tiago Peixoto's avatar
Tiago Peixoto committed
362

Tiago Peixoto's avatar
Tiago Peixoto committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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)
395
    >>> root = [v for v in g.vertices() if v.in_degree() == 0]
Tiago Peixoto's avatar
Tiago Peixoto committed
396
    >>> dom = gt.dominator_tree(g, root[0])
397
    >>> print(dom.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
398
399
400
    [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 5 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]
Tiago Peixoto's avatar
Tiago Peixoto committed
401
402
403

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

    """
407
    if dom_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
408
409
410
        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" +
411
412
                         " int32_t.")
    if not g.is_directed():
Tiago Peixoto's avatar
Tiago Peixoto committed
413
        raise ValueError("dominator tree requires a directed graph.")
414
    libgraph_tool_topology.\
Tiago Peixoto's avatar
Tiago Peixoto committed
415
416
417
               dominator_tree(g._Graph__graph, int(root),
                              _prop("v", g, dom_map))
    return dom_map
418

Tiago Peixoto's avatar
Tiago Peixoto committed
419

420
def topological_sort(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
    """
    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)
441
    >>> print(sort)
Tiago Peixoto's avatar
Tiago Peixoto committed
442
443
    [ 3 20  9 29 15  0 10 23  1  2 21  7  4 12 11  5 26 27  6  8 13 14 22 16 17
     28 18 19 24 25]
Tiago Peixoto's avatar
Tiago Peixoto committed
444
445
446

    References
    ----------
447
    .. [topological-boost] http://www.boost.org/libs/graph/doc/topological_sort.html
Tiago Peixoto's avatar
Tiago Peixoto committed
448
449
450
451
    .. [topological-wiki] http://en.wikipedia.org/wiki/Topological_sorting

    """

452
453
454
    topological_order = Vector_int32_t()
    libgraph_tool_topology.\
               topological_sort(g._Graph__graph, topological_order)
Tiago Peixoto's avatar
Tiago Peixoto committed
455
    return numpy.array(topological_order)
456

Tiago Peixoto's avatar
Tiago Peixoto committed
457

458
def transitive_closure(g):
Tiago Peixoto's avatar
Tiago Peixoto committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    """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
    ----------
479
    .. [transitive-boost] http://www.boost.org/libs/graph/doc/transitive_closure.html
Tiago Peixoto's avatar
Tiago Peixoto committed
480
481
482
483
    .. [transitive-wiki] http://en.wikipedia.org/wiki/Transitive_closure

    """

484
485
486
487
488
489
490
    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
491

492
493
def label_components(g, vprop=None, directed=None):
    """
494
    Label the components to which each vertex in the graph belongs. If the
495
496
    graph is directed, it finds the strongly connected components.

497
498
499
    A property map with the component labels is returned, together with an
    histogram of component labels.

500
501
    Parameters
    ----------
502
    g : :class:`~graph_tool.Graph`
503
        Graph to be used.
504
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: None)
505
506
507
508
509
510
511
512
        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
    -------
513
    comp : :class:`~graph_tool.PropertyMap`
514
        Vertex property map with component labels.
515
516
    hist : :class:`~numpy.ndarray`
        Histogram of component labels.
517
518
519
520
521
522

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

523
    The algorithm runs in :math:`O(V + E)` time.
524
525
526

    Examples
    --------
527
528
529
    >>> from numpy.random import seed
    >>> seed(43)
    >>> g = gt.random_graph(100, lambda: (1, 1))
530
    >>> comp, hist = gt.label_components(g)
531
    >>> print(comp.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
532
533
534
    [0 0 0 1 0 2 0 0 0 0 2 0 0 0 2 1 0 2 0 1 2 0 1 0 0 1 0 2 0 2 1 0 2 0 0 0 0
     0 0 1 0 0 2 2 2 0 0 0 0 0 0 2 0 0 1 1 0 0 2 0 1 0 0 0 2 0 0 2 2 1 2 1 0 0
     2 0 0 1 2 1 2 2 0 0 0 0 0 2 0 0 0 1 1 0 0 0 1 1 2 2]
535
    >>> print(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
536
    [58 18 24]
537
538
    """

539
    if vprop is None:
540
541
542
543
544
        vprop = g.new_vertex_property("int32_t")

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

545
546
    if directed is not None:
        g = GraphView(g, directed=directed)
547

548
549
550
551
552
553
554
    hist = libgraph_tool_topology.\
               label_components(g._Graph__graph, _prop("v", g, vprop))
    return vprop, hist


def label_largest_component(g, directed=None):
    """
555
556
    Label the largest component in the graph. If the graph is directed, then the
    largest strongly connected component is labelled.
557
558
559
560
561
562
563
564
565
566
567
568
569
570

    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`
571
         Boolean vertex property map which labels the largest component.
572
573
574
575
576
577
578
579
580
581
582

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

    Examples
    --------
    >>> from numpy.random import seed, poisson
    >>> seed(43)
    >>> g = gt.random_graph(100, lambda: poisson(1), directed=False)
    >>> l = gt.label_largest_component(g)
583
    >>> print(l.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
584
585
586
    [1 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 0 0 1 1 1 1 0 0 0 1 0 0 0 0 0 0 0 1
     1 1 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0
     0 0 0 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 0 1 0 0 0 0 0]
587
    >>> u = gt.GraphView(g, vfilt=l)   # extract the largest component as a graph
588
    >>> print(u.num_vertices())
Tiago Peixoto's avatar
Tiago Peixoto committed
589
    31
590
591
592
593
    """

    label = g.new_vertex_property("bool")
    c, h = label_components(g, directed=directed)
594
595
596
597
598
    vfilt, inv = g.get_vertex_filter()
    if vfilt is None:
        label.a = c.a == h.argmax()
    else:
        label.a = (c.a == h.argmax()) & (vfilt.a ^ inv)
599
    return label
600

Tiago Peixoto's avatar
Tiago Peixoto committed
601

602
def label_biconnected_components(g, eprop=None, vprop=None):
603
604
605
606
    """
    Label the edges of biconnected components, and the vertices which are
    articulation points.

607
608
609
610
    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.

611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    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
655
    >>> seed(43)
656
    >>> g = gt.random_graph(100, lambda: 2, directed=False)
657
    >>> comp, art, hist = gt.label_biconnected_components(g)
658
    >>> print(comp.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
659
660
661
    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0
     0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1
     0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0]
662
    >>> print(art.a)
663
664
665
    [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]
666
    >>> print(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
667
    [87 13]
668
    """
669

670
    if vprop is None:
671
        vprop = g.new_vertex_property("bool")
672
    if eprop is None:
673
674
675
676
677
678
679
        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")

680
681
    g = GraphView(g, directed=False)
    hist = libgraph_tool_topology.\
682
683
             label_biconnected_components(g._Graph__graph, _prop("e", g, eprop),
                                          _prop("v", g, vprop))
684
    return eprop, vprop, hist
685

Tiago Peixoto's avatar
Tiago Peixoto committed
686

687
def shortest_distance(g, source=None, weights=None, max_dist=None,
688
689
                      directed=None, dense=False, dist_map=None,
                      pred_map=False):
690
691
692
693
694
695
696
697
698
    """
    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)
699
        Source vertex of the search. If unspecified, the all pairs shortest
700
701
702
703
704
705
        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
706
        are searched. This parameter has no effect if source is None.
707
708
709
710
    directed : bool (optional, default:None)
        Treat graph as directed or not, independently of its actual
        directionality.
    dense : bool (optional, default: False)
711
712
        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
713
714
715
716
        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.
717
718
719
    pred_map : bool (optional, default: False)
        If true, a vertex property map with the predecessors is returned.
        Ignored if source=None.
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745

    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))
746
    >>> print(dist.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    [         0          3          6          4 2147483647          3
              4          3          4          2          3          4
              3          4          2          4          2          5
              4          4 2147483647          4 2147483647          6
              4          7          5 2147483647          3          4
              2          3          5          5          4          5
              1          5          6          1 2147483647          8
              4          2          1          5          5          6
              7          4          5          3          4          4
              5          3          3          5          4          5
              4          3          5          4          2 2147483647
              6          5          4          5          1 2147483647
              5          5          4          2          5          4
              6          3          5          3          4 2147483647
              4          4          7          4          3          5
              5          2          7          3          4          4
              4          3          4          4]
764
    >>> dist = gt.shortest_distance(g)
765
    >>> print(dist[g.vertex(0)].a)
Tiago Peixoto's avatar
Tiago Peixoto committed
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
    [         0          3          6          4 2147483647          3
              4          3          4          2          3          4
              3          4          2          4          2          5
              4          4 2147483647          4 2147483647          6
              4          7          5 2147483647          3          4
              2          3          5          5          4          5
              1          5          6          1 2147483647          8
              4          2          1          5          5          6
              7          4          5          3          4          4
              5          3          3          5          4          5
              4          3          5          4          2 2147483647
              6          5          4          5          1 2147483647
              5          5          4          2          5          4
              6          3          5          3          4 2147483647
              4          4          7          4          3          5
              5          2          7          3          4          4
              4          3          4          4]
783
784
785
786
787

    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
788
789
       Press;
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
790
791
    .. [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
792
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
793
794
795
796
    .. [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
    """

797
    if weights is None:
798
799
800
801
        dist_type = 'int32_t'
    else:
        dist_type = weights.value_type()

802
803
    if dist_map is None:
        if source is not None:
804
805
806
807
808
            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")
809
    if source is not None:
810
811
812
813
        _check_prop_scalar(dist_map, name="dist_map")
    else:
        _check_prop_vector(dist_map, name="dist_map")

814
    if max_dist is None:
815
816
        max_dist = 0

817
    if directed is not None:
818
819
820
821
        g.stash_filter(directed=True)
        g.set_directed(directed)

    try:
822
        if source is not None:
823
            pmap = g.copy_property(g.vertex_index, value_type="int64_t")
824
825
826
            libgraph_tool_topology.get_dists(g._Graph__graph, int(source),
                                             _prop("v", g, dist_map),
                                             _prop("e", g, weights),
827
                                             _prop("v", g, pmap),
828
829
830
831
832
833
834
                                             float(max_dist))
        else:
            libgraph_tool_topology.get_all_dists(g._Graph__graph,
                                                 _prop("v", g, dist_map),
                                                 _prop("e", g, weights), dense)

    finally:
835
        if directed is not None:
836
            g.pop_filter(directed=True)
837
    if source is not None and pred_map:
838
839
840
841
        return dist_map, pmap
    else:
        return dist_map

Tiago Peixoto's avatar
Tiago Peixoto committed
842

843
844
845
846
847
848
849
850
851
852
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
853
    target : :class:`~graph_tool.Vertex`
854
855
        Target vertex of the search.
    weights : :class:`~graph_tool.PropertyMap` (optional, default: None)
Tiago Peixoto's avatar
Tiago Peixoto committed
856
        The edge weights.
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
    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))
884
    >>> print([str(v) for v in vlist])
Tiago Peixoto's avatar
Tiago Peixoto committed
885
    ['10', '222', '246', '0', '50', '257', '12', '242', '11']
886
    >>> print([str(e) for e in elist])
887
    ['(10, 222)', '(222, 246)', '(246, 0)', '(0, 50)', '(50, 257)', '(257, 12)', '(12, 242)', '(242, 11)']
888
889
890
891
892

    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
893
894
       Press
    .. [bfs-boost] http://www.boost.org/libs/graph/doc/breadth_first_search.html
895
896
    .. [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
897
    .. [dijkstra-boost] http://www.boost.org/libs/graph/doc/dijkstra_shortest_paths.html
898
899
    """

900
    if pred_map is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
901
902
        pred_map = shortest_distance(g, source, weights=weights,
                                     pred_map=True)[1]
903

Tiago Peixoto's avatar
Tiago Peixoto committed
904
    if pred_map[target] == int(target):  # no path to source
905
906
907
908
909
        return [], []

    vlist = [target]
    elist = []

910
    if weights is not None:
911
912
913
914
915
916
917
918
919
920
921
922
923
        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:
924
                if weights is not None:
925
926
927
928
929
930
931
932
933
934
935
                    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

936

Tiago Peixoto's avatar
Tiago Peixoto committed
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
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
    --------
    >>> from numpy.random import seed, poisson
    >>> seed(42)
    >>> g = gt.random_graph(300, lambda: (poisson(3), poisson(3)))
    >>> dist, ends = gt.pseudo_diameter(g)
982
    >>> print(dist)
983
    9.0
984
    >>> print(int(ends[0]), int(ends[1]))
985
    0 255
Tiago Peixoto's avatar
Tiago Peixoto committed
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008

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

    if source is None:
        source = g.vertex(0)
    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))


1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
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)
1051
    >>> print(p)
1052
    True
1053
    >>> print(list(embed_order[g.vertex(0)]))
Tiago Peixoto's avatar
Tiago Peixoto committed
1054
    [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]
1055
1056
    >>> g = gt.random_graph(100, lambda: 4, directed=False)
    >>> p, kur = gt.is_planar(g, kuratowski=True)
1057
    >>> print(p)
1058
1059
    False
    >>> g.set_edge_filter(kur, True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1060
    >>> gt.graph_draw(g, output_size=(300, 300), output="kuratowski.pdf")
1061
1062
    <...>

1063
    .. figure:: kuratowski.*
1064
1065
1066
1067
1068
1069
1070
        :align: center

        Obstructing Kuratowski subgraph of a random graph.

    References
    ----------
    .. [boyer-myrvold] John M. Boyer and Wendy J. Myrvold, "On the Cutting Edge:
Tiago Peixoto's avatar
Tiago Peixoto committed
1071
1072
       Simplified O(n) Planarity by Edge Addition" Journal of Graph Algorithms
       and Applications, 8(2): 241-273, 2004. http://www.emis.ams.org/journals/JGAA/accepted/2004/BoyerMyrvold2004.8.3.pdf
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
    .. [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]
1097
    if embed is not None:
1098
        ret.append(embed)
1099
    if kur is not None:
1100
1101
1102
1103
1104
        ret.append(kur)
    if len(ret) == 1:
        return ret[0]
    else:
        return tuple(ret)
1105
1106
1107
1108


def max_cardinality_matching(g, heuristic=False, weight=None, minimize=True,
                             match=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1109
    r"""Find a maximum cardinality matching in the graph.
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    heuristic : bool (optional, default: `False`)
        If true, a random heuristic will be used, which runs in linear time.
    weight : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        If provided, the matching will minimize the edge weights (or maximize
        if ``minimize == False``. This option has no effect if
        ``heuristic == False``.
    minimize : bool (optional, default: `True`)
        If `True`, the matching will minimize the weights, otherwise they will
        be maximized. This option has no effect if ``heuristic == False``.
    match : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        Edge property map where the matching will be specified.

    Returns
    -------
    match : :class:`~graph_tool.PropertyMap`
        Boolean edge property map where the matching is specified.
    is_maximal : bool
        True if the matching is indeed maximal, or False otherwise. This is only
        returned if ``heuristic == False``.

    Notes
    -----
    A *matching* is a subset of the edges of a graph such that no two edges
    share a common vertex. A *maximum cardinality matching* has maximum size
    over all matchings in the graph.

Tiago Peixoto's avatar
Tiago Peixoto committed
1141
1142
1143
1144
    This algorithm runs in time :math:`O(EV\times\alpha(E,V))`, where
    :math:`\alpha(m,n)` is a slow growing function that is at most 4 for any
    feasible input. If `heuristic == True`, the algorithm runs in time :math:`O(V + E)`.

1145
1146
1147
1148
    For a more detailed description, see [boost-max-matching]_.

    Examples
    --------
Tiago Peixoto's avatar
Tiago Peixoto committed
1149
    >>> from numpy.random import seed
1150
    >>> seed(43)
Tiago Peixoto's avatar
Tiago Peixoto committed
1151
    >>> g = gt.GraphView(gt.price_network(300), directed=False)
1152
    >>> res = gt.max_cardinality_matching(g)
1153
    >>> print(res[1])
1154
    True
Tiago Peixoto's avatar
Tiago Peixoto committed
1155
1156
1157
1158
    >>> w = res[0].copy("double")
    >>> w.a = 2 * w.a + 2
    >>> gt.graph_draw(g, edge_color=res[0], edge_pen_width=w, vertex_fill_color="grey",
    ...               output="max_card_match.pdf")
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
    <...>

    .. figure:: max_card_match.*
        :align: center

        Edges belonging to the matching are in red.

    References
    ----------
    .. [boost-max-matching] http://www.boost.org/libs/graph/doc/maximum_matching.html
    .. [matching-heuristic] B. Hendrickson and R. Leland. "A Multilevel Algorithm
       for Partitioning Graphs." In S. Karin, editor, Proc. Supercomputing ’95,
       San Diego. ACM Press, New York, 1995, :doi:`10.1145/224170.224228`

    """
    if match is None:
        match = g.new_edge_property("bool")
    _check_prop_scalar(match, "match")
    _check_prop_writable(match, "match")
    if weight is not None:
        _check_prop_scalar(weight, "weight")

1181
    seed = numpy.random.randint(0, sys.maxsize)
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    u = GraphView(g, directed=False)
    if not heuristic:
        check = libgraph_tool_flow.\
                max_cardinality_matching(u._Graph__graph, _prop("e", u, match))
        return match, check
    else:
        libgraph_tool_topology.\
                random_matching(u._Graph__graph, _prop("e", u, weight),
                                 _prop("e", u, match), minimize, seed)
        return match
1192
1193
1194


def max_independent_vertex_set(g, high_deg=False, mivs=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1195
    r"""Find a maximal independent vertex set in the graph.
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    high_deg : bool (optional, default: `False`)
        If `True`, vertices with high degree will be included first in the set,
        otherwise they will be included last.
    mivs : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        Vertex property map where the vertex set will be specified.

    Returns
    -------
Tiago Peixoto's avatar
Tiago Peixoto committed
1209
1210
    mivs : :class:`~graph_tool.PropertyMap`
        Boolean vertex property map where the set is specified.
1211
1212
1213

    Notes
    -----
Tiago Peixoto's avatar
Tiago Peixoto committed
1214
1215
1216
    A maximal independent vertex set is an independent set such that adding any
    other vertex to the set forces the set to contain an edge between two
    vertices of the set.
1217

Tiago Peixoto's avatar
Tiago Peixoto committed
1218
1219
    This implements the algorithm described in [mivs-luby]_, which runs in time
    :math:`O(V + E)`.
1220
1221
1222

    Examples
    --------
Tiago Peixoto's avatar
Tiago Peixoto committed
1223
    >>> from numpy.random import seed
1224
    >>> seed(43)
Tiago Peixoto's avatar
Tiago Peixoto committed
1225
1226
1227
    >>> g = gt.GraphView(gt.price_network(300), directed=False)
    >>> res = gt.max_independent_vertex_set(g)
    >>> gt.graph_draw(g, vertex_fill_color=res, output="mivs.pdf")
1228
1229
    <...>

Tiago Peixoto's avatar
Tiago Peixoto committed
1230
    .. figure:: mivs.*
1231
1232
        :align: center

Tiago Peixoto's avatar
Tiago Peixoto committed
1233
        Vertices belonging to the set are in red.
1234
1235
1236

    References
    ----------
Tiago Peixoto's avatar
Tiago Peixoto committed
1237
1238
1239
1240
    .. [mivs-wikipedia] http://en.wikipedia.org/wiki/Independent_set_%28graph_theory%29
    .. [mivs-luby] Luby, M., "A simple parallel algorithm for the maximal independent set problem",
       Proc. 17th Symposium on Theory of Computing, Association for Computing Machinery, pp. 1–10, (1985)
       :doi:`10.1145/22145.22146`.
1241
1242
1243
1244
1245
1246
1247

    """
    if mivs is None:
        mivs = g.new_vertex_property("bool")
    _check_prop_scalar(mivs, "mivs")
    _check_prop_writable(mivs, "mivs")

1248
    seed = numpy.random.randint(0, sys.maxsize)
1249
1250
1251
1252
1253
1254
    u = GraphView(g, directed=False)
    libgraph_tool_topology.\
        maximal_vertex_set(u._Graph__graph, _prop("v", u, mivs), high_deg,
                           seed)
    mivs = g.own_property(mivs)
    return mivs
Tiago Peixoto's avatar
Tiago Peixoto committed
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299


def edge_reciprocity(g):
    r"""Calculate the edge reciprocity of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used
        edges.

    Returns
    -------
    reciprocity : float
        The reciprocity value.

    Notes
    -----

    The edge [reciprocity]_ is defined as :math:`E^\leftrightarrow/E`, where
    :math:`E^\leftrightarrow` and :math:`E` are the number of bidirectional and
    all edges in the graph, respectively.

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

    Examples
    --------

    >>> g = gt.Graph()
    >>> g.add_vertex(2)
    [<Vertex object with index '0' at 0x1254dd0>,
     <Vertex object with index '1' at 0x1254bd0>]
    >>> g.add_edge(g.vertex(0), g.vertex(1))
    <Edge object with source '0' and target '1' at 0x33bc710>
    >>> gt.edge_reciprocity(g)
    0.0
    >>> g.add_edge(g.vertex(1), g.vertex(0))
    <Edge object with source '1' and target '0' at 0x33bc7a0>
    >>> gt.edge_reciprocity(g)
    1.0

    References
    ----------
    .. [reciprocity] S. Wasserman and K. Faust, "Social Network Analysis".
       (Cambridge University Press, Cambridge, 1994)
1300
    .. [lopez-reciprocity-2007] Gorka Zamora-López, Vinko Zlatić, Changsong Zhou, Hrvoje Štefančić, and Jürgen Kurths
Tiago Peixoto's avatar
Tiago Peixoto committed
1301
1302
1303
1304
1305
1306
1307
       "Reciprocity of networks with degree correlations and arbitrary degree sequences", Phys. Rev. E 77, 016106 (2008)
       :doi:`10.1103/PhysRevE.77.016106`, :arxiv:`0706.3372`

    """

    r = libgraph_tool_topology.reciprocity(g._Graph__graph)
    return r
1308