__init__.py 73.4 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1 2 3 4 5
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2017 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 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#
# 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.search`` - Search algorithms
-----------------------------------------

This module includes several search algorithms, which are customizable to
arbitrary purposes. It is mostly a wrapper around the Visitor interface of the
`Boost Graph Library <http://www.boost.org/doc/libs/release/libs/graph/doc/visitor_concepts.html>`_,
and the respective search functions.


Summary
+++++++

.. autosummary::
   :nosignatures:

   bfs_search
38
   bfs_iterator
Tiago Peixoto's avatar
Tiago Peixoto committed
39
   dfs_search
40
   dfs_iterator
Tiago Peixoto's avatar
Tiago Peixoto committed
41
   dijkstra_search
42
   dijkstra_iterator
Tiago Peixoto's avatar
Tiago Peixoto committed
43
   astar_search
44 45
   astar_iterator
   bellman_ford_search
Tiago Peixoto's avatar
Tiago Peixoto committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59
   BFSVisitor
   DFSVisitor
   DijkstraVisitor
   BellmanFordVisitor
   AStarVisitor
   StopSearch

Examples
++++++++

In this module, most documentation examples will make use of the network
:download:`search_example.xml <search_example.xml>`, shown below.

>>> g = gt.load_graph("search_example.xml")
Tiago Peixoto's avatar
Tiago Peixoto committed
60 61 62 63 64 65 66
>>> name = g.vp["name"]
>>> weight = g.ep["weight"]
>>> pos = g.vp["pos"]
>>> gt.graph_draw(g, pos, vertex_text=name, vertex_font_size=12, vertex_shape="double_circle",
...               vertex_fill_color="#729fcf", vertex_pen_width=3,
...               edge_pen_width=weight, output="search_example.pdf")
<...>
67 68 69 70 71 72 73

.. testcode::
   :hide:

   gt.graph_draw(g, pos=pos, vertex_text=name, vertex_font_size=12, vertex_shape="double_circle",
                 vertex_fill_color="#729fcf", vertex_pen_width=3,
                 edge_pen_width=weight, output="search_example.png")
Tiago Peixoto's avatar
Tiago Peixoto committed
74

75
.. figure:: search_example.*
Tiago Peixoto's avatar
Tiago Peixoto committed
76 77 78 79 80 81 82 83 84 85 86
   :alt: search example
   :align: center

   This is the network used in the examples below. The width of the edges
   correspond to the values of the "weight" property map.


Contents
++++++++
"""

87
from __future__ import division, absolute_import, print_function
88 89 90
import sys
if sys.version_info < (3,):
    range = xrange
91

Tiago Peixoto's avatar
Tiago Peixoto committed
92
from .. dl_import import dl_import
93
dl_import("from . import libgraph_tool_search")
Tiago Peixoto's avatar
Tiago Peixoto committed
94

95
from .. import _prop, _python_type, _get_null_vertex
Tiago Peixoto's avatar
Tiago Peixoto committed
96
import weakref
97
import numpy
Tiago Peixoto's avatar
Tiago Peixoto committed
98

99 100 101 102
__all__ = ["bfs_search", "bfs_iterator", "BFSVisitor", "dfs_search",
           "dfs_iterator", "DFSVisitor", "dijkstra_search", "dijkstra_iterator",
           "DijkstraVisitor", "bellman_ford_search", "BellmanFordVisitor",
           "astar_search", "astar_iterator", "AStarVisitor", "StopSearch"]
Tiago Peixoto's avatar
Tiago Peixoto committed
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159


class BFSVisitor(object):
    r"""A visitor object that is invoked at the event-points inside the
    :func:`~graph_tool.search.bfs_search` algorithm. By default, it performs no
    action, and should be used as a base class in order to be useful."""

    def initialize_vertex(self, u):
        """This is invoked on every vertex of the graph before the start of the
        graph search. """
        return

    def discover_vertex(self, u):
        """This is invoked when a vertex is encountered for the first time."""
        return

    def examine_vertex(self, u):
        """This is invoked on a vertex as it is popped from the queue. This
        happens immediately before examine_edge() is invoked on each of the
        out-edges of vertex u."""
        return

    def examine_edge(self, e):
        """This is invoked on every out-edge of each vertex after it is
        discovered."""
        return

    def tree_edge(self, e):
        """This is invoked on each edge as it becomes a member of the edges that
        form the search tree."""
        return

    def non_tree_edge(self, e):
        """This is invoked on back or cross edges for directed graphs and cross
        edges for undirected graphs. """
        return

    def gray_target(self, e):
        """This is invoked on the subset of non-tree edges whose target vertex
        is colored gray at the time of examination. The color gray indicates
        that the vertex is currently in the queue."""
        return

    def black_target(self, e):
        """This is invoked on the subset of non-tree edges whose target vertex
        is colored black at the time of examination. The color black indicates
        that the vertex has been removed from the queue."""
        return

    def finish_vertex(self, u):
        """This invoked on a vertex after all of its out edges have been added
        to the search tree and all of the adjacent vertices have been discovered
        (but before the out-edges of the adjacent vertices have been examined).
        """
        return


160
def bfs_search(g, source=None, visitor=BFSVisitor()):
161
    r"""Breadth-first traversal of a directed or undirected graph.
Tiago Peixoto's avatar
Tiago Peixoto committed
162 163 164 165 166

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
167 168 169 170
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
Tiago Peixoto's avatar
Tiago Peixoto committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    visitor : :class:`~graph_tool.search.BFSVisitor` (optional, default: ``BFSVisitor()``)
        A visitor object that is invoked at the event points inside the
        algorithm. This should be a subclass of
        :class:`~graph_tool.search.BFSVisitor`.

    See Also
    --------
    dfs_search: Depth-first search
    dijkstra_search: Dijkstra's search algorithm
    astar_search: :math:`A^*` heuristic search algorithm

    Notes
    -----

    A breadth-first traversal visits vertices that are closer to the source
    before visiting vertices that are further away. In this context "distance"
    is defined as the number of edges in the shortest path from the source
    vertex.

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

    The pseudo-code for the BFS algorithm is listed below, with the annotated
    event points, for which the given visitor object will be called with the
    appropriate method.

    ::

        BFS(G, source)
         for each vertex u in V[G]       initialize vertex u
           color[u] := WHITE
           d[u] := infinity
         end for
         color[source] := GRAY
         d[source] := 0
         ENQUEUE(Q, source)              discover vertex source
         while (Q != Ø)
           u := DEQUEUE(Q)               examine vertex u
           for each vertex v in Adj[u]   examine edge (u,v)
             if (color[v] = WHITE)       (u,v) is a tree edge
               color[v] := GRAY
               ENQUEUE(Q, v)             discover vertex v
             else                        (u,v) is a non-tree edge
               if (color[v] = GRAY)
                 ...                     (u,v) has a gray target
               else
                 ...                     (u,v) has a black target
           end for
           color[u] := BLACK             finish vertex u
         end while


    Examples
    --------

    We must define what should be done during the search by subclassing
    :class:`~graph_tool.search.BFSVisitor`, and specializing the appropriate
    methods. In the following we will keep track of the distance from the root,
    and the predecessor tree.

    .. testcode::

        class VisitorExample(gt.BFSVisitor):

            def __init__(self, name, pred, dist):
                self.name = name
                self.pred = pred
                self.dist = dist

            def discover_vertex(self, u):
240
                print("-->", self.name[u], "has been discovered!")
Tiago Peixoto's avatar
Tiago Peixoto committed
241 242

            def examine_vertex(self, u):
243
                print(self.name[u], "has been examined...")
Tiago Peixoto's avatar
Tiago Peixoto committed
244 245 246 247 248 249 250 251

            def tree_edge(self, e):
                self.pred[e.target()] = int(e.source())
                self.dist[e.target()] = self.dist[e.source()] + 1

    With the above class defined, we can perform the BFS search as follows.

    >>> dist = g.new_vertex_property("int")
252
    >>> pred = g.new_vertex_property("int64_t")
Tiago Peixoto's avatar
Tiago Peixoto committed
253 254 255 256 257 258 259 260
    >>> gt.bfs_search(g, g.vertex(0), VisitorExample(name, pred, dist))
    --> Bob has been discovered!
    Bob has been examined...
    --> Eve has been discovered!
    --> Chuck has been discovered!
    --> Carlos has been discovered!
    --> Isaac has been discovered!
    Eve has been examined...
261
    --> Imothep has been discovered!
262
    --> Carol has been discovered!
Tiago Peixoto's avatar
Tiago Peixoto committed
263 264 265 266
    Chuck has been examined...
    Carlos has been examined...
    --> Alice has been discovered!
    Isaac has been examined...
267
    Imothep has been examined...
268
    Carol has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
269 270 271 272 273
    Alice has been examined...
    --> Oscar has been discovered!
    --> Dave has been discovered!
    Oscar has been examined...
    Dave has been examined...
274
    >>> print(dist.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
275
    [0 2 2 1 1 3 1 1 3 2]
276
    >>> print(pred.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
277 278 279 280 281 282 283 284 285 286 287 288
    [0 3 6 0 0 1 0 0 1 6]


    References
    ----------
    .. [bfs] Edward Moore, "The shortest path through a maze", International
             Symposium on the Theory of Switching, 1959
    .. [bfs-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/breadth_first_search.html
    .. [bfs-wikipedia] http://en.wikipedia.org/wiki/Breadth-first_search
    """

    try:
289 290 291 292
        if source is None:
            source = _get_null_vertex()
        else:
            source = int(source)
Tiago Peixoto's avatar
Tiago Peixoto committed
293
        libgraph_tool_search.bfs_search(g._Graph__graph,
294
                                        source, visitor)
Tiago Peixoto's avatar
Tiago Peixoto committed
295 296 297
    except StopSearch:
        pass

298
def bfs_iterator(g, source=None, array=False):
299 300 301 302 303 304 305
    r"""Return an iterator of the edges corresponding to a breath-first traversal of
    the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
306 307 308 309
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
310 311 312
    array : ``bool`` (optional, default: ``False``)
        If ``True``, a :class:`numpy.ndarray` will the edge endpoints be
        returned instead.
313 314 315

    Returns
    -------
316 317 318 319
    bfs_iterator : Iterator or :class:`numpy.ndarray`
        An iterator over the edges in breath-first order. If ``array == True``,
        this will be a :class:`numpy.ndarray` instead, of shape ``(E,2)``,
        containing the edge endpoints.
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

    See Also
    --------
    dfs_iterator: Depth-first search
    dijkstra_iterator: Dijkstra's search algorithm
    astar_iterator: :math:`A^*` heuristic search algorithm

    Notes
    -----

    See :func:`~graph_tool.search.bfs_search` for an explanation of the
    algorithm.

    The time complexity is :math:`O(1)` to create the generator and
    :math:`O(V + E)` to traverse it completely.

    Examples
    --------

    >>> for e in gt.bfs_iterator(g, g.vertex(0)):
    ...    print(name[e.source()], "->", name[e.target()])
    Bob -> Eve
    Bob -> Chuck
    Bob -> Carlos
    Bob -> Isaac
    Eve -> Imothep
346
    Eve -> Carol
347 348 349 350 351 352 353 354 355 356
    Carlos -> Alice
    Alice -> Oscar
    Alice -> Dave

    References
    ----------
    .. [bfs] Edward Moore, "The shortest path through a maze", International
             Symposium on the Theory of Switching, 1959
    .. [bfs-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/breadth_first_search.html
    .. [bfs-wikipedia] http://en.wikipedia.org/wiki/Breadth-first_search
357

358
    """
359 360 361 362
    if source is None:
        source = _get_null_vertex()
    else:
        source = int(source)
363 364 365 366
    if not array:
        return libgraph_tool_search.bfs_search_generator(g._Graph__graph, source)
    else:
        return libgraph_tool_search.bfs_search_array(g._Graph__graph, source)
367

Tiago Peixoto's avatar
Tiago Peixoto committed
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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

class DFSVisitor(object):
    r"""
    A visitor object that is invoked at the event-points inside the
    :func:`~graph_tool.search.dfs_search` algorithm. By default, it performs no
    action, and should be used as a base class in order to be useful.
    """

    def initialize_vertex(self, u):
        """
        This is invoked on every vertex of the graph before the start of the
        graph search.
        """
        return

    def start_vertex(self, u):
        """
        This is invoked on the source vertex once before the start of the
        search.
        """
        return

    def discover_vertex(self, u):
        """This is invoked when a vertex is encountered for the first time."""
        return

    def examine_edge(self, e):
        """
        This is invoked on every out-edge of each vertex after it is discovered.
        """
        return

    def tree_edge(self, e):
        """
        This is invoked on each edge as it becomes a member of the edges that
        form the search tree.
        """
        return

    def back_edge(self, e):
        """
        This is invoked on the back edges in the graph. For an undirected graph
        there is some ambiguity between tree edges and back edges since the edge
        (u,v) and (v,u) are the same edge, but both the
        :meth:`~graph_tool.search.DFSVisitor.tree_edge` and
        :meth:`~graph_tool.search..DFSVisitor.back_edge` functions will be
        invoked. One way to resolve this ambiguity is to record the tree edges,
        and then disregard the back-edges that are already marked as tree
        edges. An easy way to record tree edges is to record predecessors at the
        tree_edge event point.
        """
        return

    def forward_or_cross_edge(self, e):
        """
        This is invoked on forward or cross edges in the graph. In an undirected
        graph this method is never called.
        """
        return

    def finish_vertex(self, e):
        """
        This is invoked on vertex u after finish_vertex has been called for all
        the vertices in the DFS-tree rooted at vertex u. If vertex u is a leaf
        in the DFS-tree, then the
        :meth:`~graph_tool..search.DFSVisitor.finish_vertex` function is called
        on u after all the out-edges of u have been examined.
        """
        return


439
def dfs_search(g, source=None, visitor=DFSVisitor()):
440
    r"""Depth-first traversal of a directed or undirected graph.
Tiago Peixoto's avatar
Tiago Peixoto committed
441 442 443 444 445

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
446 447 448 449
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
Tiago Peixoto's avatar
Tiago Peixoto committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 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
    visitor : :class:`~graph_tool.search.DFSVisitor` (optional, default: ``DFSVisitor()``)
        A visitor object that is invoked at the event points inside the
        algorithm. This should be a subclass of
        :class:`~graph_tool.search.DFSVisitor`.

    See Also
    --------
    bfs_search: Breadth-first search
    dijkstra_search: Dijkstra's search algorithm
    astar_search: :math:`A^*` heuristic search algorithm

    Notes
    -----

    When possible, a depth-first traversal chooses a vertex adjacent to the
    current vertex to visit next. If all adjacent vertices have already been
    discovered, or there are no adjacent vertices, then the algorithm backtracks
    to the last vertex that had undiscovered neighbors. Once all reachable
    vertices have been visited, the algorithm selects from any remaining
    undiscovered vertices and continues the traversal. The algorithm finishes
    when all vertices have been visited.

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

    The pseudo-code for the DFS algorithm is listed below, with the annotated
    event points, for which the given visitor object will be called with the
    appropriate method.

    ::

        DFS(G)
          for each vertex u in V
            color[u] := WHITE                 initialize vertex u
          end for
          time := 0
          call DFS-VISIT(G, source)           start vertex s

        DFS-VISIT(G, u)
          color[u] := GRAY                    discover vertex u
          for each v in Adj[u]                examine edge (u,v)
            if (color[v] = WHITE)             (u,v) is a tree edge
              call DFS-VISIT(G, v)
            else if (color[v] = GRAY)         (u,v) is a back edge
              ...
            else if (color[v] = BLACK)        (u,v) is a cross or forward edge
              ...
          end for
          color[u] := BLACK                   finish vertex u


    Examples
    --------

    We must define what should be done during the search by subclassing
    :class:`~graph_tool.search.DFSVisitor`, and specializing the appropriate
    methods. In the following we will keep track of the discover time, and the
    predecessor tree.

    .. testcode::

        class VisitorExample(gt.DFSVisitor):

            def __init__(self, name, pred, time):
                self.name = name
                self.pred = pred
                self.time = time
                self.last_time = 0

            def discover_vertex(self, u):
519
                print("-->", self.name[u], "has been discovered!")
Tiago Peixoto's avatar
Tiago Peixoto committed
520 521 522 523
                self.time[u] = self.last_time
                self.last_time += 1

            def examine_edge(self, e):
524 525
                print("edge (%s, %s) has been examined..." % \
                    (self.name[e.source()], self.name[e.target()]))
Tiago Peixoto's avatar
Tiago Peixoto committed
526 527 528 529 530 531 532 533

            def tree_edge(self, e):
                self.pred[e.target()] = int(e.source())


    With the above class defined, we can perform the DFS search as follows.

    >>> time = g.new_vertex_property("int")
534
    >>> pred = g.new_vertex_property("int64_t")
Tiago Peixoto's avatar
Tiago Peixoto committed
535 536 537 538
    >>> gt.dfs_search(g, g.vertex(0), VisitorExample(name, pred, time))
    --> Bob has been discovered!
    edge (Bob, Eve) has been examined...
    --> Eve has been discovered!
539 540 541 542 543 544 545 546 547 548
    edge (Eve, Isaac) has been examined...
    --> Isaac has been discovered!
    edge (Isaac, Bob) has been examined...
    edge (Isaac, Chuck) has been examined...
    --> Chuck has been discovered!
    edge (Chuck, Eve) has been examined...
    edge (Chuck, Isaac) has been examined...
    edge (Chuck, Imothep) has been examined...
    --> Imothep has been discovered!
    edge (Imothep, Carol) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
549 550 551 552 553
    --> Carol has been discovered!
    edge (Carol, Eve) has been examined...
    edge (Carol, Imothep) has been examined...
    edge (Imothep, Carlos) has been examined...
    --> Carlos has been discovered!
554 555
    edge (Carlos, Eve) has been examined...
    edge (Carlos, Imothep) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
556 557 558 559 560 561 562 563
    edge (Carlos, Bob) has been examined...
    edge (Carlos, Alice) has been examined...
    --> Alice has been discovered!
    edge (Alice, Oscar) has been examined...
    --> Oscar has been discovered!
    edge (Oscar, Alice) has been examined...
    edge (Oscar, Dave) has been examined...
    --> Dave has been discovered!
564
    edge (Dave, Oscar) has been examined...
565
    edge (Dave, Alice) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
566 567 568
    edge (Alice, Dave) has been examined...
    edge (Alice, Carlos) has been examined...
    edge (Imothep, Chuck) has been examined...
569
    edge (Imothep, Eve) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
570 571
    edge (Chuck, Bob) has been examined...
    edge (Isaac, Eve) has been examined...
572
    edge (Eve, Imothep) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
573 574
    edge (Eve, Carlos) has been examined...
    edge (Eve, Chuck) has been examined...
575 576
    edge (Eve, Bob) has been examined...
    edge (Eve, Carol) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
577 578 579
    edge (Bob, Chuck) has been examined...
    edge (Bob, Carlos) has been examined...
    edge (Bob, Isaac) has been examined...
580
    >>> print(time.a)
581
    [0 7 5 6 3 9 1 2 8 4]
582
    >>> print(pred.a)
583
    [0 3 9 9 7 8 0 6 1 4]
Tiago Peixoto's avatar
Tiago Peixoto committed
584 585 586 587 588

    References
    ----------
    .. [dfs-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/depth_first_search.html
    .. [dfs-wikipedia] http://en.wikipedia.org/wiki/Depth-first_search
589

Tiago Peixoto's avatar
Tiago Peixoto committed
590 591 592
    """

    try:
593 594 595 596
        if source is None:
            source = _get_null_vertex()
        else:
            source = int(source)
Tiago Peixoto's avatar
Tiago Peixoto committed
597
        libgraph_tool_search.dfs_search(g._Graph__graph,
598
                                        source, visitor)
Tiago Peixoto's avatar
Tiago Peixoto committed
599 600 601
    except StopSearch:
        pass

602
def dfs_iterator(g, source=None, array=False):
603 604 605 606 607 608 609
    r"""Return an iterator of the edges corresponding to a depth-first traversal of
    the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
610 611 612 613
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
614 615 616
    array : ``bool`` (optional, default: ``False``)
        If ``True``, a :class:`numpy.ndarray` will the edge endpoints be
        returned instead.
617 618 619

    Returns
    -------
620 621 622 623
    dfs_iterator : Iterator or :class:`numpy.ndarray`
        An iterator over the edges in depth-first order. If ``array == True``,
        this will be a :class:`numpy.ndarray` instead, of shape ``(E,2)``,
        containing the edge endpoints.
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

    See Also
    --------
    bfs_iterator: Breadth-first search
    dijkstra_iterator: Dijkstra's search algorithm
    astar_iterator: :math:`A^*` heuristic search algorithm

    Notes
    -----

    See :func:`~graph_tool.search.dfs_search` for an explanation of the
    algorithm.

    The time complexity is :math:`O(1)` to create the generator and
    :math:`O(V + E)` to traverse it completely.

    Examples
    --------

    >>> for e in gt.dfs_iterator(g, g.vertex(0)):
    ...    print(name[e.source()], "->", name[e.target()])
    Bob -> Eve
646 647 648 649
    Eve -> Isaac
    Isaac -> Chuck
    Chuck -> Imothep
    Imothep -> Carol
650 651 652 653 654 655 656 657 658
    Imothep -> Carlos
    Carlos -> Alice
    Alice -> Oscar
    Oscar -> Dave

    References
    ----------
    .. [dfs-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/depth_first_search.html
    .. [dfs-wikipedia] http://en.wikipedia.org/wiki/Depth-first_search
659

660 661
    """

662 663 664 665
    if source is None:
        source = _get_null_vertex()
    else:
        source = int(source)
666 667 668 669
    if not array:
        return libgraph_tool_search.dfs_search_generator(g._Graph__graph, source)
    else:
        return libgraph_tool_search.dfs_search_array(g._Graph__graph, source)
Tiago Peixoto's avatar
Tiago Peixoto committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

class DijkstraVisitor(object):
    r"""A visitor object that is invoked at the event-points inside the
    :func:`~graph_tool.search.dijkstra_search` algorithm. By default, it
    performs no action, and should be used as a base class in order to be
    useful.
    """

    def initialize_vertex(self, u):
        """
        This is invoked on every vertex of the graph before the start of the
        graph search.
        """
        return

    def examine_vertex(self, u):
        """
        This is invoked on a vertex as it is popped from the queue. This happens
        immediately before :meth:`~graph_tool.DijsktraVisitor.examine_edge` is
        invoked on each of the out-edges of vertex u.
        """
        return

    def examine_edge(self, e):
        """
        This is invoked on every out-edge of each vertex after it is discovered.
        """
        return

    def discover_vertex(self, u):
        """This is invoked when a vertex is encountered for the first time."""
        return

    def edge_relaxed(self, e):
        """
        Upon examination, if the following condition holds then the edge is
        relaxed (its distance is reduced), and this method is invoked.

        ::

            (u, v) = tuple(e)
            assert(compare(combine(d[u], weight[e]), d[v]))

        """
        return

    def edge_not_relaxed(self, e):
        """
        Upon examination, if the edge is not relaxed (see
        :meth:`~graph_tool.search.DijsktraVisitor.edge_relaxed`) then this
        method is invoked.
        """
        return

    def finish_vertex(self, u):
        """
        This invoked on a vertex after all of its out edges have been added to
        the search tree and all of the adjacent vertices have been discovered
        (but before their out-edges have been examined).
        """
        return


733
def dijkstra_search(g, weight, source=None, visitor=DijkstraVisitor(), dist_map=None,
Tiago Peixoto's avatar
Tiago Peixoto committed
734
                    pred_map=None, combine=lambda a, b: a + b,
735
                    compare=lambda a, b: a < b, zero=0, infinity=numpy.inf):
736
    r"""Dijsktra traversal of a directed or undirected graph, with non-negative weights.
Tiago Peixoto's avatar
Tiago Peixoto committed
737 738 739 740 741 742 743

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weight : :class:`~graph_tool.PropertyMap`
        Edge property map with weight values.
744 745 746 747
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
Tiago Peixoto's avatar
Tiago Peixoto committed
748
    visitor : :class:`~graph_tool.search.DijkstraVisitor` (optional, default: ``DijkstraVisitor()``)
Tiago Peixoto's avatar
Tiago Peixoto committed
749 750 751
        A visitor object that is invoked at the event points inside the
        algorithm. This should be a subclass of
        :class:`~graph_tool.search.DijkstraVisitor`.
Tiago Peixoto's avatar
Tiago Peixoto committed
752
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
753 754
        A vertex property map where the distances from the source will be
        stored.
Tiago Peixoto's avatar
Tiago Peixoto committed
755
    pred_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
756
        A vertex property map where the predecessor map will be
757
        stored (must have value type "int64_t").
Tiago Peixoto's avatar
Tiago Peixoto committed
758
    combine : binary function (optional, default: ``lambda a, b: a + b``)
Tiago Peixoto's avatar
Tiago Peixoto committed
759 760
        This function is used to combine distances to compute the distance of a
        path.
Tiago Peixoto's avatar
Tiago Peixoto committed
761
    compare : binary function (optional, default: ``lambda a, b: a < b``)
Tiago Peixoto's avatar
Tiago Peixoto committed
762 763
        This function is use to compare distances to determine which vertex is
        closer to the source vertex.
764 765 766
    zero : int or float (optional, default: ``0``)
         Value assumed to correspond to a distance of zero by the combine and
         compare functions.
767
    infinity : int or float (optional, default: ``numpy.inf``)
768 769
         Value assumed to correspond to a distance of infinity by the combine and
         compare functions.
Tiago Peixoto's avatar
Tiago Peixoto committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

    Returns
    -------
    dist_map : :class:`~graph_tool.PropertyMap`
        A vertex property map with the computed distances from the source.
    pred_map : :class:`~graph_tool.PropertyMap`
        A vertex property map with the predecessor tree.

    See Also
    --------
    bfs_search: Breadth-first search
    dfs_search: Depth-first search
    astar_search: :math:`A^*` heuristic search algorithm

    Notes
    -----

    Dijkstra's algorithm finds all the shortest paths from the source vertex to
    every other vertex by iteratively "growing" the set of vertices S to which
    it knows the shortest path. At each step of the algorithm, the next vertex
    added to S is determined by a priority queue. The queue contains the
    vertices in V - S prioritized by their distance label, which is the length
    of the shortest path seen so far for each vertex. The vertex u at the top of
    the priority queue is then added to S, and each of its out-edges is relaxed:
    if the distance to u plus the weight of the out-edge (u,v) is less than the
    distance label for v then the estimated distance for vertex v is
    reduced. The algorithm then loops back, processing the next vertex at the
    top of the priority queue. The algorithm finishes when the priority queue is
    empty.

800
    The time complexity is :math:`O(E + V \log V)`.
Tiago Peixoto's avatar
Tiago Peixoto committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 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

    The pseudo-code for Dijkstra's algorithm is listed below, with the annotated
    event points, for which the given visitor object will be called with the
    appropriate method.

    ::

        DIJKSTRA(G, source, weight)
          for each vertex u in V                      initialize vertex u
            d[u] := infinity
            p[u] := u
          end for
          d[source] := 0
          INSERT(Q, source)                           discover vertex s
          while (Q != Ø)
            u := EXTRACT-MIN(Q)                       examine vertex u
            for each vertex v in Adj[u]               examine edge (u,v)
              if (weight[(u,v)] + d[u] < d[v])        edge (u,v) relaxed
                d[v] := weight[(u,v)] + d[u]
                p[v] := u
                DECREASE-KEY(Q, v)
              else                                    edge (u,v) not relaxed
                ...
              if (d[v] was originally infinity)
                INSERT(Q, v)                          discover vertex v
            end for                                   finish vertex u
          end while
          return d

    Examples
    --------

    We must define what should be done during the search by subclassing
    :class:`~graph_tool.search.DijkstraVisitor`, and specializing the
    appropriate methods. In the following we will keep track of the discover
    time, and the predecessor tree.

    .. testcode::

        class VisitorExample(gt.DijkstraVisitor):

            def __init__(self, name, time):
                self.name = name
                self.time = time
                self.last_time = 0

            def discover_vertex(self, u):
848
                print("-->", self.name[u], "has been discovered!")
Tiago Peixoto's avatar
Tiago Peixoto committed
849 850 851 852
                self.time[u] = self.last_time
                self.last_time += 1

            def examine_edge(self, e):
853 854
                print("edge (%s, %s) has been examined..." % \
                    (self.name[e.source()], self.name[e.target()]))
Tiago Peixoto's avatar
Tiago Peixoto committed
855 856

            def edge_relaxed(self, e):
857 858
                print("edge (%s, %s) has been relaxed..." % \
                    (self.name[e.source()], self.name[e.target()]))
Tiago Peixoto's avatar
Tiago Peixoto committed
859 860 861 862 863


    With the above class defined, we can perform the Dijkstra search as follows.

    >>> time = g.new_vertex_property("int")
864
    >>> dist, pred = gt.dijkstra_search(g, weight, g.vertex(0), VisitorExample(name, time))
Tiago Peixoto's avatar
Tiago Peixoto committed
865
    --> Bob has been discovered!
Tiago Peixoto's avatar
Tiago Peixoto committed
866 867 868 869 870 871 872 873 874 875 876 877
    edge (Bob, Eve) has been examined...
    edge (Bob, Eve) has been relaxed...
    --> Eve has been discovered!
    edge (Bob, Chuck) has been examined...
    edge (Bob, Chuck) has been relaxed...
    --> Chuck has been discovered!
    edge (Bob, Carlos) has been examined...
    edge (Bob, Carlos) has been relaxed...
    --> Carlos has been discovered!
    edge (Bob, Isaac) has been examined...
    edge (Bob, Isaac) has been relaxed...
    --> Isaac has been discovered!
878 879 880 881
    edge (Eve, Isaac) has been examined...
    edge (Eve, Imothep) has been examined...
    edge (Eve, Imothep) has been relaxed...
    --> Imothep has been discovered!
882 883 884 885 886 887
    edge (Eve, Carlos) has been examined...
    edge (Eve, Chuck) has been examined...
    edge (Eve, Bob) has been examined...
    edge (Eve, Carol) has been examined...
    edge (Eve, Carol) has been relaxed...
    --> Carol has been discovered!
Tiago Peixoto's avatar
Tiago Peixoto committed
888 889 890 891 892 893
    edge (Isaac, Bob) has been examined...
    edge (Isaac, Chuck) has been examined...
    edge (Isaac, Eve) has been examined...
    edge (Chuck, Eve) has been examined...
    edge (Chuck, Isaac) has been examined...
    edge (Chuck, Imothep) has been examined...
894 895 896
    edge (Chuck, Bob) has been examined...
    edge (Carlos, Eve) has been examined...
    edge (Carlos, Imothep) has been examined...
Tiago Peixoto's avatar
Tiago Peixoto committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    edge (Carlos, Bob) has been examined...
    edge (Carlos, Alice) has been examined...
    edge (Carlos, Alice) has been relaxed...
    --> Alice has been discovered!
    edge (Imothep, Carol) has been examined...
    edge (Imothep, Carlos) has been examined...
    edge (Imothep, Chuck) has been examined...
    edge (Imothep, Eve) has been examined...
    edge (Alice, Oscar) has been examined...
    edge (Alice, Oscar) has been relaxed...
    --> Oscar has been discovered!
    edge (Alice, Dave) has been examined...
    edge (Alice, Dave) has been relaxed...
    --> Dave has been discovered!
    edge (Alice, Carlos) has been examined...
    edge (Carol, Eve) has been examined...
    edge (Carol, Imothep) has been examined...
    edge (Oscar, Alice) has been examined...
    edge (Oscar, Dave) has been examined...
916
    edge (Dave, Oscar) has been examined...
917
    edge (Dave, Alice) has been examined...
918
    >>> print(time.a)
919
    [0 7 6 3 2 9 1 4 8 5]
920
    >>> print(pred.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
921
    [0 3 6 0 0 1 0 0 1 6]
922
    >>> print(dist.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    [  0.           8.91915887   9.27141329   4.29277116   4.02118246
      12.23513866   3.23790211   3.45487436  11.04391549   7.74858396]

    References
    ----------
    .. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
        graphs", Numerische Mathematik, 1:269-271, 1959.
    .. [dijkstra-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/dijkstra_shortest_paths_no_color_map.html
    .. [dijkstra-wikipedia] http://en.wikipedia.org/wiki/Dijkstra's_algorithm
    """

    if visitor is None:
        visitor = DijkstraVisitor()
    if dist_map is None:
        dist_map = g.new_vertex_property(weight.value_type())
    if pred_map is None:
939 940 941
        pred_map = g.new_vertex_property("int64_t")
    if pred_map.value_type() != "int64_t":
        raise ValueError("pred_map must be of value type 'int64_t', not '%s'." % \
Tiago Peixoto's avatar
Tiago Peixoto committed
942 943
                             pred_map.value_type())

944
    try:
945 946
        if dist_map.value_type() != "python::object":
            zero = _python_type(dist_map.value_type())(zero)
947 948 949 950 951
    except OverflowError:
        zero = (weight.a.max() + 1) * g.num_vertices()
        zero = _python_type(dist_map.value_type())(zero)

    try:
952 953
        if dist_map.value_type() != "python::object":
            infinity = _python_type(dist_map.value_type())(infinity)
954 955 956 957
    except OverflowError:
        infinity = (weight.a.max() + 1) * g.num_vertices()
        infinity = _python_type(dist_map.value_type())(infinity)

Tiago Peixoto's avatar
Tiago Peixoto committed
958
    try:
959 960 961 962
        if source is None:
            source = _get_null_vertex()
        else:
            source = int(source)
Tiago Peixoto's avatar
Tiago Peixoto committed
963
        libgraph_tool_search.dijkstra_search(g._Graph__graph,
964
                                             source,
Tiago Peixoto's avatar
Tiago Peixoto committed
965 966 967 968 969 970 971 972 973
                                             _prop("v", g, dist_map),
                                             _prop("v", g, pred_map),
                                             _prop("e", g, weight), visitor,
                                             compare, combine, zero, infinity)
    except StopSearch:
        pass

    return dist_map, pred_map

974
def dijkstra_iterator(g, weight, source=None, dist_map=None, combine=None,
975
                      compare=None, zero=0, infinity=numpy.inf, array=False):
976 977 978 979 980 981 982 983 984
    r"""Return an iterator of the edges corresponding to a Dijkstra traversal of
    the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weight : :class:`~graph_tool.PropertyMap`
        Edge property map with weight values.
985 986 987 988
    source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
        Source vertex. If unspecified, all vertices will be traversed, by
        iterating over starting vertices according to their index in increasing
        order.
989 990 991 992 993 994 995 996 997 998 999 1000 1001
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        A vertex property map where the distances from the source will be
        stored.
    combine : binary function (optional, default: ``lambda a, b: a + b``)
        This function is used to combine distances to compute the distance of a
        path.
    compare : binary function (optional, default: ``lambda a, b: a < b``)
        This function is use to compare distances to determine which vertex is
        closer to the source vertex.
    zero : int or float (optional, default: ``0``)
         Value assumed to correspond to a distance of zero by the combine and
         compare functions.
    infinity : int or float (optional, default: ``numpy.inf``)
1002 1003 1004 1005 1006
         Value assumed to correspond to a distance of infinity by the combine
         and compare functions.
    array : ``bool`` (optional, default: ``False``)
        If ``True``, a :class:`numpy.ndarray` will the edge endpoints be
        returned instead.
1007 1008 1009

    Returns
    -------
1010 1011 1012 1013
    dfs_iterator : Iterator or :class:`numpy.ndarray`
        An iterator over the edges in Dijkstra order. If ``array == True``,
        this will be a :class:`numpy.ndarray` instead, of shape ``(E,2)``,
        containing the edge endpoints.
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

    See Also
    --------
    bfs_iterator: Breadth-first search
    dfs_iterator: Depth-first search
    astar_iterator: :math:`A^*` heuristic search algorithm

    Notes
    -----

    See :func:`~graph_tool.search.dijkstra_search` for an explanation of the
    algorithm.

    The time complexity is :math:`O(1)` to create the generator and
    :math:`O(E + V\log V)` to traverse it completely.

    Examples
    --------

1033
    >>> for e in gt.dijkstra_iterator(g, weight, g.vertex(0)):
1034 1035 1036 1037 1038 1039
    ...    print(name[e.source()], "->", name[e.target()])
    Bob -> Eve
    Bob -> Chuck
    Bob -> Carlos
    Bob -> Isaac
    Eve -> Imothep
1040
    Eve -> Carol
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    Carlos -> Alice
    Alice -> Oscar
    Alice -> Dave

    References
    ----------
    .. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
        graphs", Numerische Mathematik, 1:269-271, 1959.
    .. [dijkstra-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/dijkstra_shortest_paths_no_color_map.html
    .. [dijkstra-wikipedia] http://en.wikipedia.org/wiki/Dijkstra's_algorithm
1051

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    """

    if dist_map is None:
        dist_map = g.new_vertex_property(weight.value_type())

    try:
        if dist_map.value_type() != "python::object":
            zero = _python_type(dist_map.value_type())(zero)
    except OverflowError:
        zero = (weight.a.max() + 1) * g.num_vertices()
        zero = _python_type(dist_map.value_type())(zero)

    try:
        if dist_map.value_type() != "python::object":
            infinity = _python_type(dist_map.value_type())(infinity)
    except OverflowError:
        infinity = (weight.a.max() + 1) * g.num_vertices()
        infinity = _python_type(dist_map.value_type())(infinity)

1071 1072 1073 1074
    if source is None:
        source = _get_null_vertex()
    else:
        source = int(source)
1075
    if compare is None and combine is None:
1076 1077 1078 1079 1080 1081 1082 1083
        if not array:
            return libgraph_tool_search.dijkstra_generator_fast(g._Graph__graph,
                                                                source,
                                                                _prop("v", g, dist_map),
                                                                _prop("e", g, weight),
                                                                zero, infinity)
        else:
            return libgraph_tool_search.dijkstra_array_fast(g._Graph__graph,
1084
                                                            source,
1085 1086 1087 1088 1089 1090 1091 1092
                                                            _prop("v", g, dist_map),
                                                            _prop("e", g, weight),
                                                            zero, infinity)
    else:
        if compare is None:
            compare = lambda a, b: a < b
        if combine is None:
            combine = lambda a, b: a + b
1093 1094 1095 1096 1097 1098 1099 1100 1101
        if not array:
            return libgraph_tool_search.dijkstra_generator(g._Graph__graph,
                                                           source,
                                                           _prop("v", g, dist_map),
                                                           _prop("e", g, weight),
                                                           compare, combine,
                                                           zero, infinity)
        else:
            return libgraph_tool_search.dijkstra_array(g._Graph__graph,
1102
                                                       source,
1103 1104 1105 1106 1107
                                                       _prop("v", g, dist_map),
                                                       _prop("e", g, weight),
                                                       compare, combine,
                                                       zero, infinity)

Tiago Peixoto's avatar
Tiago Peixoto committed
1108 1109 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 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

class BellmanFordVisitor(object):
    r"""A visitor object that is invoked at the event-points inside the
    :func:`~graph_tool.search.bellman_ford_search` algorithm. By default, it
    performs no action, and should be used as a base class in order to be
    useful.
    """

    def examine_edge(self, e):
        """
        This is invoked on every edge in the graph ``|V|`` times.
        """
        return

    def edge_relaxed(self, e):
        """
        This is invoked when the distance label for the target vertex is
        decreased. The edge (u,v) that participated in the last relaxation for
        vertex v is an edge in the shortest paths tree.
        """
        return

    def edge_not_relaxed(self, e):
        """
        This is invoked if the distance label for the target vertex is not
        decreased.
        """
        return

    def edge_minimized(self, e):
        """
        This is invoked during the second stage of the algorithm, during the
        test of whether each edge was minimized. If the edge is minimized then
        this function is invoked.
        """
        return

    def edge_not_minimized(self, e):
        """
        This is invoked during the second stage of the algorithm, during the
        test of whether each edge was minimized. If the edge was not minimized,
        this function is invoked. This happens when there is a negative cycle in
        the graph.
        """
        return


def bellman_ford_search(g, source, weight, visitor=BellmanFordVisitor(),
                        dist_map=None, pred_map=None,
                        combine=lambda a, b: a + b,
                        compare=lambda a, b: a < b, zero=0,
                        infinity=float('inf')):
1160
    r"""Bellman-Ford traversal of a directed or undirected graph, with negative weights.
Tiago Peixoto's avatar
Tiago Peixoto committed
1161 1162 1163 1164 1165 1166 1167 1168 1169

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex`
        Source vertex.
    weight : :class:`~graph_tool.PropertyMap`
        Edge property map with weight values.
Tiago Peixoto's avatar
Tiago Peixoto committed
1170
    visitor : :class:`~graph_tool.search.DijkstraVisitor` (optional, default: ``DijkstraVisitor()``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1171 1172 1173
        A visitor object that is invoked at the event points inside the
        algorithm. This should be a subclass of
        :class:`~graph_tool.search.DijkstraVisitor`.
Tiago Peixoto's avatar
Tiago Peixoto committed
1174
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1175 1176
        A vertex property map where the distances from the source will be
        stored.
Tiago Peixoto's avatar
Tiago Peixoto committed
1177
    pred_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1178
        A vertex property map where the predecessor map will be
1179
        stored (must have value type "int64_t").
Tiago Peixoto's avatar
Tiago Peixoto committed
1180
    combine : binary function (optional, default: ``lambda a, b: a + b``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1181 1182
        This function is used to combine distances to compute the distance of a
        path.
Tiago Peixoto's avatar
Tiago Peixoto committed
1183
    compare : binary function (optional, default: ``lambda a, b: a < b``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1184 1185
        This function is use to compare distances to determine which vertex is
        closer to the source vertex.
1186 1187 1188 1189 1190 1191
    zero : int or float (optional, default: ``0``)
         Value assumed to correspond to a distance of zero by the combine and
         compare functions.
    infinity : int or float (optional, default: ``float('inf')``)
         Value assumed to correspond to a distance of infinity by the combine and
         compare functions.
Tiago Peixoto's avatar
Tiago Peixoto committed
1192 1193 1194 1195 1196


    Returns
    -------
    minimized : bool
Tiago Peixoto's avatar
Tiago Peixoto committed
1197
        True if all edges were successfully minimized, or False if there is a
Tiago Peixoto's avatar
Tiago Peixoto committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 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
        negative loop in the graph.
    dist_map : :class:`~graph_tool.PropertyMap`
        A vertex property map with the computed distances from the source.
    pred_map : :class:`~graph_tool.PropertyMap`
        A vertex property map with the predecessor tree.

    See Also
    --------
    bfs_search: Breadth-first search
    dfs_search: Depth-first search
    dijsktra_search: Dijkstra search
    astar_search: :math:`A^*` heuristic search

    Notes
    -----

    The Bellman-Ford algorithm [bellman-ford]_ solves the single-source shortest
    paths problem for a graph with both positive and negative edge weights. If
    you only need to solve the shortest paths problem for positive edge weights,
    :func:`~graph_tool.search.dijkstra_search` provides a more efficient
    alternative. If all the edge weights are all equal, then
    :func:`~graph_tool.search.bfs_search` provides an even more efficient
    alternative.

    The Bellman-Ford algorithm proceeds by looping through all of the edges in
    the graph, applying the relaxation operation to each edge. In the following
    pseudo-code, ``v`` is a vertex adjacent to ``u``, ``w`` maps edges to their
    weight, and ``d`` is a distance map that records the length of the shortest
    path to each vertex seen so far. ``p`` is a predecessor map which records
    the parent of each vertex, which will ultimately be the parent in the
    shortest paths tree

    ::

        RELAX(u, v, w, d, p)
          if (w(u,v) + d[u] < d[v])
            d[v] := w(u,v) + d[u]       relax edge (u,v)
            p[v] := u
          else
            ...                         edge (u,v) is not relaxed


    The algorithm repeats this loop ``|V|`` times after which it is guaranteed
    that the distances to each vertex have been reduced to the minimum possible
    unless there is a negative cycle in the graph. If there is a negative cycle,
    then there will be edges in the graph that were not properly minimized. That
    is, there will be edges ``(u,v)`` such that ``w(u,v) + d[u] < d[v]``. The
    algorithm loops over the edges in the graph one final time to check if all
    the edges were minimized, returning true if they were and returning false
    otherwise.

    ::


        BELLMAN-FORD(G)
          for each vertex u in V
            d[u] := infinity
            p[u] := u
          end for
          for i := 1 to |V|-1
            for each edge (u,v) in E          examine edge (u,v)
              RELAX(u, v, w, d, p)
            end for
          end for
          for each edge (u,v) in E
            if (w(u,v) + d[u] < d[v])
              return (false, , )              edge (u,v) was not minimized
            else
              ...                             edge (u,v) was minimized
          end for
          return (true, p, d)

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

    Examples
    --------

    We must define what should be done during the search by subclassing
    :class:`~graph_tool.search.BellmanFordVisitor`, and specializing the
    appropriate methods. In the following we will keep track of the edge
    minimizations.

    .. testcode::

        class VisitorExample(gt.BellmanFordVisitor):

            def __init__(self, name):
                self.name = name

            def edge_minimized(self, e):
1288 1289
                print("edge (%s, %s) has been minimized..." % \
                      (self.name[e.source()], self.name[e.target()]))
Tiago Peixoto's avatar
Tiago Peixoto committed
1290 1291

            def edge_not_minimized(self, e):
1292 1293
                print("edge (%s, %s) has not been minimized..." % \
                      (self.name[e.source()], self.name[e.target()]))
Tiago Peixoto's avatar
Tiago Peixoto committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318


    With the above class defined, we can perform the Bellman-Ford search as
    follows.

    >>> nweight = g.copy_property(weight)
    >>> nweight.a[6] *= -1   # include negative weight in edge (Carlos, Alice)
    >>> minimized, dist, pred = gt.bellman_ford_search(g, g.vertex(0), nweight, VisitorExample(name))
    edge (Bob, Eve) has been minimized...
    edge (Bob, Chuck) has been minimized...
    edge (Bob, Carlos) has been minimized...
    edge (Bob, Isaac) has been minimized...
    edge (Alice, Oscar) has been minimized...
    edge (Alice, Dave) has been minimized...
    edge (Alice, Carlos) has been minimized...
    edge (Carol, Eve) has been minimized...
    edge (Carol, Imothep) has been minimized...
    edge (Carlos, Eve) has been minimized...
    edge (Carlos, Imothep) has been minimized...
    edge (Chuck, Eve) has been minimized...
    edge (Chuck, Isaac) has been minimized...
    edge (Chuck, Imothep) has been minimized...
    edge (Dave, Oscar) has been minimized...
    edge (Eve, Isaac) has been minimized...
    edge (Eve, Imothep) has been minimized...
1319
    >>> print(minimized)
Tiago Peixoto's avatar
Tiago Peixoto committed
1320
    True
1321
    >>> print(pred.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
1322
    [3 3 9 1 6 1 3 6 1 3]
1323
    >>> print(dist.a)
Tiago Peixoto's avatar
Tiago Peixoto committed
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    [-28.42555934 -37.34471821 -25.20438243 -41.97110592 -35.20316571
     -34.02873843 -36.58860946 -33.55645565 -35.2199616  -36.0029274 ]

    References
    ----------
    .. [bellman-ford] R. Bellman, "On a routing problem", Quarterly of Applied
       Mathematics, 16(1):87-90, 1958.
    .. [bellman-ford-bgl] http://www.boost.org/doc/libs/release/libs/graph/doc/bellman_ford_shortest.html
    .. [bellman-ford-wikipedia] http://en.wikipedia.org/wiki/Bellman-Ford_algorithm
    """

    if dist_map is None:
        dist_map = g.new_vertex_property(weight.value_type())
    if pred_map is None:
1338 1339 1340
        pred_map = g.new_vertex_property("int64_t")
    if pred_map.value_type() != "int64_t":
        raise ValueError("pred_map must be of value type 'int64_t', not '%s'." % \
Tiago Peixoto's avatar
Tiago Peixoto committed
1341
                             pred_map.value_type())
1342 1343

    try:
1344 1345
        if dist_map.value_type() != "python::object":
            zero = _python_type(dist_map.value_type())(zero)
1346 1347 1348 1349 1350
    except OverflowError:
        zero = (weight.a.max() + 1) * g.num_vertices()
        zero = _python_type(dist_map.value_type())(zero)

    try:
1351 1352
        if dist_map.value_type() != "python::object":
            infinity = _python_type(dist_map.value_type())(infinity)
1353 1354 1355 1356
    except OverflowError:
        infinity = (weight.a.max() + 1) * g.num_vertices()
        infinity = _python_type(dist_map.value_type())(infinity)

Tiago Peixoto's avatar
Tiago Peixoto committed
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    minimized = False
    try:
        minimized = \
            libgraph_tool_search.bellman_ford_search(g._Graph__graph,
                                                     int(source),
                                                     _prop("v", g, dist_map),
                                                     _prop("v", g, pred_map),
                                                     _prop("e", g, weight),
                                                     visitor, compare, combine,
                                                     zero, infinity)
    except StopSearch:
        pass

    return minimized, dist_map, pred_map


class AStarVisitor(object):
    r"""A visitor object that is invoked at the event-points inside the
    :func:`~graph_tool.search.astar_search` algorithm. By default, it
    performs no action, and should be used as a base class in order to be
    useful.
    """

    def initialize_vertex(self, u):
        """
        This is invoked on every vertex of the graph before the start of the
        graph search.
        """
        return

    def examine_vertex(self, u):
        """ This is invoked on a vertex as it is popped from the queue (i.e. it
        has the lowest cost on the ``OPEN`` list). This happens immediately
        before examine_edge() is invoked on each of the out-edges of vertex u.
        """
        return

    def examine_edge(self, e):
        """
        This is invoked on every out-edge of each vertex after it is examined.
        """
        return

    def discover_vertex(self, u):
        """
        This is invoked when a vertex is first discovered and is added to the
        ``OPEN`` list.
        """
        return

    def edge_relaxed(self, e):
        """
        Upon examination, if the following condition holds then the edge is
        relaxed (its distance is reduced), and this method is invoked.

        ::

            (u, v) = tuple(e)
            assert(compare(combine(d[u], weight[e]), d[v]))

        """
        return

    def edge_not_relaxed(self, e):
        """
        Upon examination, if the edge is not relaxed (see
        :meth:`~graph_tool.search.AStarVisitor.edge_relaxed`) then this
        method is invoked.
        """
        return

    def black_target(self, e):
        """ This is invoked when a vertex that is on the ``CLOSED`` list is
        "rediscovered" via a more efficient path, and is re-added to the
        ``OPEN`` list.
        """
        return

    def finish_vertex(self, u):
        """
        This is invoked on a vertex when it is added to the CLOSED list,
        which happens after all of its out edges have been examined.
        """
        return


def astar_search(g, source, weight, visitor=AStarVisitor(),
                 heuristic=lambda v: 1, dist_map=None, pred_map=None,
                 cost_map=None, combine=lambda a, b: a + b,
                 compare=lambda a, b: a < b, zero=0,
                 infinity=float('inf'), implicit=False):
    r"""
1449
    Heuristic :math:`A^*` search on a weighted, directed or undirected graph for the case where all edge weights are non-negative.
Tiago Peixoto's avatar
Tiago Peixoto committed
1450 1451 1452 1453 1454 1455 1456 1457 1458

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    source : :class:`~graph_tool.Vertex`
        Source vertex.
    weight : :class:`~graph_tool.PropertyMap`
        Edge property map with weight values.
Tiago Peixoto's avatar
Tiago Peixoto committed
1459
    visitor : :class:`~graph_tool.search.AStarVisitor` (optional, default: ``AStarVisitor()``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1460 1461 1462 1463 1464 1465
        A visitor object that is invoked at the event points inside the
        algorithm. This should be a subclass of
        :class:`~graph_tool.search.AStarVisitor`.
    heuristic : unary function (optional, default: ``lambda v: 1``)
        The heuristic function that guides the search. It should take a single
        argument which is a :class:`~graph_tool.Vertex`, and output an estimated
1466
        distance from the supplied vertex to the target vertex.
Tiago Peixoto's avatar
Tiago Peixoto committed
1467
    dist_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1468 1469
        A vertex property map where the distances from the source will be
        stored.
Tiago Peixoto's avatar
Tiago Peixoto committed
1470
    pred_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1471
        A vertex property map where the predecessor map will be
1472
        stored (must have value type "int64_t").
Tiago Peixoto's avatar
Tiago Peixoto committed
1473
    cost_map : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1474 1475 1476 1477 1478 1479 1480 1481 1482
        A vertex property map where the vertex costs will be stored. It must
        have the same value type as ``dist_map``. This parameter is only used if
        ``implicit`` is True.
    combine : binary function (optional, default: ``lambda a, b: a + b``)
        This function is used to combine distances to compute the distance of a
        path.
    compare : binary function (optional, default: ``lambda a, b: a < b``)
        This function is use to compare distances to determine which vertex is
        closer to the source vertex.
Tiago Peixoto's avatar
Tiago Peixoto committed
1483
    implicit : bool (optional, default: ``False``)
Tiago Peixoto's avatar
Tiago Peixoto committed
1484 1485
        If true, the underlying graph will be assumed to be implicit
        (i.e. constructed during the search).
1486 1487