__init__.py 17.2 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
Tiago Peixoto's avatar
Tiago Peixoto committed
3
#
4
5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2007-2010 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# 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/>.

"""
``graph_tool.flow`` - Maximum flow algorithms
---------------------------------------------
24
25
26
27
28
29
30
31
32
33
34
35
36
37

Summary
+++++++

.. autosummary::
   :nosignatures:

   edmonds_karp_max_flow
   push_relabel_max_flow
   kolmogorov_max_flow
   max_cardinality_matching

Contents
++++++++
Tiago Peixoto's avatar
Tiago Peixoto committed
38
39
40
41
42
43
44
"""

from .. dl_import import dl_import
dl_import("import libgraph_tool_flow")

from .. core import _prop, _check_prop_scalar, _check_prop_writable
__all__ = ["edmonds_karp_max_flow", "push_relabel_max_flow",
45
           "kolmogorov_max_flow", "max_cardinality_matching"]
Tiago Peixoto's avatar
Tiago Peixoto committed
46

Tiago Peixoto's avatar
Tiago Peixoto committed
47

Tiago Peixoto's avatar
Tiago Peixoto committed
48
def edmonds_karp_max_flow(g, source, target, capacity, residual=None):
49
50
    r"""
    Calculate maximum flow on the graph with Edmonds-Karp algorithm.
51
52
53

    Parameters
    ----------
54
    g : :class:`~graph_tool.Graph`
55
56
57
58
59
        Graph to be used.
    source : Vertex
        The source vertex.
    target : Vertex
        The target (or "sink") vertex.
60
    capacity : :class:`~graph_tool.PropertyMap`
61
        Edge property map with the edge capacities.
62
    residual : :class:`~graph_tool.PropertyMap` (optional, default: none)
63
64
65
66
        Edge property map where the residuals should be stored.

    Returns
    -------
67
    residual : :class:`~graph_tool.PropertyMap`
68
69
70
71
        Edge property map with the residual capacities (capacity - flow).

    Notes
    -----
72
73
74
    The algorithm is due to [edmonds-theoretical-1972]_, though we are using the
    variation called the "labeling algorithm" described in
    [ravindra-network-1993]_.
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

    This algorithm provides a very simple and easy to implement solution to the
    maximum flow problem. However, there are several reasons why this algorithm
    is not as good as the push_relabel_max_flow() or the kolmogorov_max_flow()
    algorithm.

    - In the non-integer capacity case, the time complexity is :math:`O(V E^2)`
      which is worse than the time complexity of the push-relabel algorithm
      :math:`O(V^2E^{1/2})` for all but the sparsest of graphs.

    - In the integer capacity case, if the capacity bound U is very large then
      the algorithm will take a long time.

    Examples
    --------
    >>> from numpy.random import seed, random
Tiago Peixoto's avatar
Tiago Peixoto committed
91
    >>> seed(43)
92
93
94
95
96
97
    >>> g = gt.random_graph(100, lambda: (2,2))
    >>> c = g.new_edge_property("double")
    >>> c.a = random(len(c.a))
    >>> res = gt.edmonds_karp_max_flow(g, g.vertex(0), g.vertex(1), c)
    >>> res.a = c.a - res.a  # the actual flow
    >>> print res.a[0:g.num_edges()]
Tiago Peixoto's avatar
Tiago Peixoto committed
98
99
100
101
102
    [ 0.13339096  0.24058962  0.          0.          0.          0.          0.
      0.          0.31026953  0.          0.          0.          0.          0.
      0.10719866  0.          0.          0.          0.          0.          0.
      0.          0.13339096  0.          0.          0.          0.10719866
      0.          0.          0.          0.          0.10719866  0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
103
      0.          0.          0.          0.          0.          0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
104
      0.          0.          0.24058962  0.          0.          0.          0.
105
      0.          0.          0.          0.          0.          0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
106
107
108
      0.          0.          0.          0.10719866  0.          0.          0.
      0.          0.          0.          0.          0.31026953  0.          0.
      0.          0.          0.44366049  0.          0.          0.          0.
109
      0.          0.          0.          0.          0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
110
      0.10719866  0.          0.          0.          0.          0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
111
      0.          0.          0.          0.          0.          0.          0.
112
      0.          0.          0.          0.          0.          0.          0.
Tiago Peixoto's avatar
Tiago Peixoto committed
113
      0.          0.10719866  0.          0.          0.          0.          0.
114
115
116
      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
117
118
119
120
121
122
123
124
125
126
      0.          0.          0.          0.          0.          0.          0.
      0.          0.          0.          0.10719866  0.          0.          0.
      0.          0.10719866  0.          0.44366049  0.          0.          0.
      0.          0.          0.          0.          0.          0.          0.
      0.          0.          0.          0.          0.          0.          0.
      0.          0.          0.          0.          0.          0.10719866
      0.          0.          0.31026953  0.          0.31026953  0.          0.
      0.          0.          0.          0.          0.          0.          0.
      0.          0.          0.          0.          0.          0.          0.
      0.          0.          0.          0.          0.          0.          0.        ]
127
128
129

    References
    ----------
130
131
    .. [boost-edmonds-karp] http://www.boost.org/libs/graph/doc/edmonds_karp_max_flow.html
    .. [edmonds-theoretical-1972] Jack Edmonds and Richard M. Karp, "Theoretical
132
133
       improvements in the algorithmic efficiency for network flow problems.
       Journal of the ACM", 1972 19:248-264
134
    .. [ravindra-network-1993] Ravindra K. Ahuja and Thomas L. Magnanti and
135
136
137
138
       James B. Orlin,"Network Flows: Theory, Algorithms, and Applications".
       Prentice Hall, 1993.
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
139
140
141
142
143
144
145
146
147
148
149
150
    _check_prop_scalar(capacity, "capacity")
    if residual == None:
        residual = g.new_edge_property(capacity.value_type())
    _check_prop_scalar(residual, "residual")
    _check_prop_writable(residual, "residual")

    libgraph_tool_flow.\
           edmonds_karp_max_flow(g._Graph__graph, int(source), int(target),
                                 _prop("e", g, capacity),
                                 _prop("e", g, residual))
    return residual

Tiago Peixoto's avatar
Tiago Peixoto committed
151

Tiago Peixoto's avatar
Tiago Peixoto committed
152
def push_relabel_max_flow(g, source, target, capacity, residual=None):
153
154
    r"""
    Calculate maximum flow on the graph with push-relabel algorithm.
155
156
157

    Parameters
    ----------
158
    g : :class:`~graph_tool.Graph`
159
160
161
162
163
        Graph to be used.
    source : Vertex
        The source vertex.
    target : Vertex
        The target (or "sink") vertex.
164
    capacity : :class:`~graph_tool.PropertyMap`
165
        Edge property map with the edge capacities.
166
    residual : :class:`~graph_tool.PropertyMap` (optional, default: none)
167
168
169
170
        Edge property map where the residuals should be stored.

    Returns
    -------
171
    residual : :class:`~graph_tool.PropertyMap`
172
173
174
175
        Edge property map with the residual capacities (capacity - flow).

    Notes
    -----
176
    The algorithm is defined in [goldberg-new-1985]_. The complexity is
177
178
179
180
181
    :math:`O(V^3)`.

    Examples
    --------
    >>> from numpy.random import seed, random
Tiago Peixoto's avatar
Tiago Peixoto committed
182
    >>> seed(43)
183
184
185
186
187
188
    >>> g = gt.random_graph(100, lambda: (2,2))
    >>> c = g.new_edge_property("double")
    >>> c.a = random(len(c.a))
    >>> res = gt.push_relabel_max_flow(g, g.vertex(0), g.vertex(1), c)
    >>> res.a = c.a - res.a  # the actual flow
    >>> print res.a[0:g.num_edges()]
Tiago Peixoto's avatar
Tiago Peixoto committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    [ 0.13339096  0.24058962  0.          0.01254176  0.          0.          0.
      0.          0.31026953  0.          0.00745848  0.00335702  0.03601961
      0.01254176  0.0794977   0.          0.00745848  0.          0.06036354
      0.01254176  0.00335702  0.          0.14084944  0.          0.03601961
      0.00745848  0.08285472  0.          0.          0.06372057  0.
      0.10384163  0.          0.00335702  0.          0.          0.          0.
      0.          0.02434393  0.          0.          0.02434393  0.2480481   0.
      0.          0.          0.          0.0368857   0.          0.06372057
      0.          0.03601961  0.          0.00335702  0.01254176  0.02434393
      0.          0.10719866  0.04347809  0.01254176  0.          0.01254176
      0.          0.          0.00335702  0.31026953  0.03601961  0.          0.
      0.          0.45111897  0.00335702  0.          0.          0.
      0.00335702  0.          0.00335702  0.06036354  0.00745848  0.01589879
      0.0794977   0.          0.06372057  0.          0.00508328  0.          0.
      0.06036354  0.06036354  0.03601961  0.0368857   0.          0.
      0.00335702  0.          0.          0.          0.03601961  0.01589879
      0.01254176  0.          0.01254176  0.03601961  0.          0.0368857
      0.03601961  0.01589879  0.03601961  0.          0.03601961  0.          0.
      0.          0.00335702  0.01589879  0.0368857   0.03601961  0.03601961
      0.01254176  0.01254176  0.          0.00335702  0.02434393  0.00745848
      0.          0.03937663  0.06036354  0.          0.          0.          0.
      0.          0.          0.          0.02434393  0.          0.03601961
      0.          0.          0.11974042  0.          0.          0.03601961
      0.01254176  0.11465713  0.09465689  0.46800442  0.03601961  0.
      0.00335702  0.          0.          0.03601961  0.          0.
      0.00745848  0.          0.          0.03601961  0.          0.
      0.09974018  0.00335702  0.01254176  0.00335702  0.01254176  0.
      0.01254176  0.10719866  0.          0.          0.          0.31026953
      0.          0.31026953  0.          0.01254176  0.          0.          0.
      0.02000024  0.0108155   0.03601961  0.          0.03601961  0.03937663
      0.00335702  0.01254176  0.          0.          0.          0.01688546
      0.          0.          0.06036354  0.03601961  0.          0.        ]
221
222
223

    References
    ----------
224
225
    .. [boost-push-relabel] http://www.boost.org/libs/graph/doc/push_relabel_max_flow.html
    .. [goldberg-new-1985] A. V. Goldberg, "A New Max-Flow Algorithm",  MIT
226
227
228
       Tehnical report MIT/LCS/TM-291, 1985.
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
229
230
231
232
233
234
235
236
237
238
239
240
    _check_prop_scalar(capacity, "capacity")
    if residual == None:
        residual = g.new_edge_property(capacity.value_type())
    _check_prop_scalar(residual, "residual")
    _check_prop_writable(residual, "residual")

    libgraph_tool_flow.\
           push_relabel_max_flow(g._Graph__graph, int(source), int(target),
                                 _prop("e", g, capacity),
                                 _prop("e", g, residual))
    return residual

Tiago Peixoto's avatar
Tiago Peixoto committed
241

Tiago Peixoto's avatar
Tiago Peixoto committed
242
def kolmogorov_max_flow(g, source, target, capacity, residual=None):
243
244
245
246
    r"""Calculate maximum flow on the graph with Kolmogorov algorithm.

    Parameters
    ----------
247
    g : :class:`~graph_tool.Graph`
248
249
250
251
252
        Graph to be used.
    source : Vertex
        The source vertex.
    target : Vertex
        The target (or "sink") vertex.
253
    capacity : :class:`~graph_tool.PropertyMap`
254
        Edge property map with the edge capacities.
255
    residual : :class:`~graph_tool.PropertyMap` (optional, default: none)
256
257
258
259
        Edge property map where the residuals should be stored.

    Returns
    -------
260
    residual : :class:`~graph_tool.PropertyMap`
261
262
263
264
265
        Edge property map with the residual capacities (capacity - flow).

    Notes
    -----

266
267
    The algorithm is defined in [kolmogorov-graph-2003]_ and
    [boykov-experimental-2004]_. The worst case complexity is
268
    :math:`O(EV^2|C|)`, where :math:`|C|` is the minimum cut (but typically
Tiago Peixoto's avatar
Tiago Peixoto committed
269
    performs much better).
270

271
    For a more detailed description, see [boost-kolmogorov]_.
272
273
274
275

    Examples
    --------
    >>> from numpy.random import seed, random
Tiago Peixoto's avatar
Tiago Peixoto committed
276
    >>> seed(43)
277
278
279
280
281
282
    >>> g = gt.random_graph(100, lambda: (2,2))
    >>> c = g.new_edge_property("double")
    >>> c.a = random(len(c.a))
    >>> res = gt.push_relabel_max_flow(g, g.vertex(0), g.vertex(1), c)
    >>> res.a = c.a - res.a  # the actual flow
    >>> print res.a[0:g.num_edges()]
Tiago Peixoto's avatar
Tiago Peixoto committed
283
284
285
286
287
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
    [ 0.13339096  0.24058962  0.          0.01254176  0.          0.          0.
      0.          0.31026953  0.          0.00745848  0.00335702  0.03601961
      0.01254176  0.0794977   0.          0.00745848  0.          0.06036354
      0.01254176  0.00335702  0.          0.14084944  0.          0.03601961
      0.00745848  0.08285472  0.          0.          0.06372057  0.
      0.10384163  0.          0.00335702  0.          0.          0.          0.
      0.          0.02434393  0.          0.          0.02434393  0.2480481   0.
      0.          0.          0.          0.0368857   0.          0.06372057
      0.          0.03601961  0.          0.00335702  0.01254176  0.02434393
      0.          0.10719866  0.04347809  0.01254176  0.          0.01254176
      0.          0.          0.00335702  0.31026953  0.03601961  0.          0.
      0.          0.45111897  0.00335702  0.          0.          0.
      0.00335702  0.          0.00335702  0.06036354  0.00745848  0.01589879
      0.0794977   0.          0.06372057  0.          0.00508328  0.          0.
      0.06036354  0.06036354  0.03601961  0.0368857   0.          0.
      0.00335702  0.          0.          0.          0.03601961  0.01589879
      0.01254176  0.          0.01254176  0.03601961  0.          0.0368857
      0.03601961  0.01589879  0.03601961  0.          0.03601961  0.          0.
      0.          0.00335702  0.01589879  0.0368857   0.03601961  0.03601961
      0.01254176  0.01254176  0.          0.00335702  0.02434393  0.00745848
      0.          0.03937663  0.06036354  0.          0.          0.          0.
      0.          0.          0.          0.02434393  0.          0.03601961
      0.          0.          0.11974042  0.          0.          0.03601961
      0.01254176  0.11465713  0.09465689  0.46800442  0.03601961  0.
      0.00335702  0.          0.          0.03601961  0.          0.
      0.00745848  0.          0.          0.03601961  0.          0.
      0.09974018  0.00335702  0.01254176  0.00335702  0.01254176  0.
      0.01254176  0.10719866  0.          0.          0.          0.31026953
      0.          0.31026953  0.          0.01254176  0.          0.          0.
      0.02000024  0.0108155   0.03601961  0.          0.03601961  0.03937663
      0.00335702  0.01254176  0.          0.          0.          0.01688546
      0.          0.          0.06036354  0.03601961  0.          0.        ]
315
316
317

    References
    ----------
318
319
    .. [boost-kolmogorov] http://www.boost.org/libs/graph/doc/kolmogorov_max_flow.html
    .. [kolmogorov-graph-2003] Vladimir Kolmogorov, "Graph Based Algorithms for
320
321
       Scene Reconstruction from Two or More Views", PhD thesis, Cornell
        University, September 2003.
322
    .. [boykov-experimental-2004] Yuri Boykov and Vladimir Kolmogorov, "An
323
324
325
326
       Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy
       Minimization", Vision In IEEE Transactions on Pattern Analysis and
       Machine Intelligence, vol. 26, no. 9, pp. 1124-1137, Sept. 2004.
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
327
328
329
330
331
332
333
334
335
336
337
    _check_prop_scalar(capacity, "capacity")
    if residual == None:
        residual = g.new_edge_property(capacity.value_type())
    _check_prop_scalar(residual, "residual")
    _check_prop_writable(residual, "residual")

    libgraph_tool_flow.\
           kolmogorov_max_flow(g._Graph__graph, int(source), int(target),
                                 _prop("e", g, capacity),
                                 _prop("e", g, residual))
    return residual
338

Tiago Peixoto's avatar
Tiago Peixoto committed
339

340
def max_cardinality_matching(g, match=None):
341
342
343
344
    r"""Find the maximum cardinality matching in the graph.

    Parameters
    ----------
345
    g : :class:`~graph_tool.Graph`
346
        Graph to be used.
347
    match : :class:`~graph_tool.PropertyMap` (optional, default: none)
348
349
350
351
        Edge property map where the matching will be specified.

    Returns
    -------
352
    match : :class:`~graph_tool.PropertyMap`
353
354
355
356
357
358
359
360
361
362
        Boolean edge property map where the matching is specified.
    is_maximal : bool
        True if the matching is indeed maximal, or False otherwise.

    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.

363
    For a more detailed description, see [boost-max-matching]_.
364
365
366
367

    Examples
    --------
    >>> from numpy.random import seed, random
Tiago Peixoto's avatar
Tiago Peixoto committed
368
    >>> seed(43)
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    >>> g = gt.random_graph(100, lambda: (2,2))
    >>> res = gt.max_cardinality_matching(g)
    >>> print res[1]
    True
    >>> gt.graph_draw(g, ecolor=res[0], output="max_card_match.png")
    <...>

    .. figure:: max_card_match.png
        :align: center

        Edges belonging to the matching are in red.

    References
    ----------
383
    .. [boost-max-matching] http://www.boost.org/libs/graph/doc/maximum_matching.html
384
    """
385
386
387
388
389
390
391
392
393
394
395
    if match == None:
        match = g.new_edge_property("bool")
    _check_prop_scalar(match, "match")
    _check_prop_writable(match, "match")

    g.stash_filter(directed=True)
    g.set_directed(False)
    check = libgraph_tool_flow.\
            max_cardinality_matching(g._Graph__graph, _prop("e", g, match))
    g.pop_filter(directed=True)
    return match, check