shortest_path

Contents

shortest_path#

graph_tool.structure.shortest_path(g, source, target, weights=None, negative_weights=False, pred_map=None, dag=False, ch=None)[git][source]#

Return the shortest path from source to target.

Parameters:
gGraph

Graph to be used.

sourceVertex

Source vertex of the search.

targetVertex

Target vertex of the search.

weightsEdgePropertyMap (optional, default: None)

The edge weights.

negative_weightsbool (optional, default: False)

If True, this will trigger the use of the Bellman-Ford algorithm.

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

dagbool (optional, default: False)

If True, assume that the graph is a Directed Acyclic Graph (DAG), which will be faster if weights are given, in which case they are also allowed to contain negative values (irrespective of the parameter negative_weights).

chContractionHierarchy (optional, default: None)

Contraction hierarchy of the graph, built with the same weights, with which the path is found. It is ignored if pred_map is given, or if negative_weights or dag is True. A ValueError is raised if the hierarchy was built for a different graph, view, or weights, or if the graph has since gained or lost vertices or edges.

Returns:
vertex_listlist of Vertex

List of vertices from source to target in the shortest path.

edge_listlist of Edge

List of edges from source to target in the shortest path.

See also

shortest_distance

Distances from a source vertex

all_shortest_paths

All shortest paths between two vertices

random_shortest_path

Uniformly random shortest path

k_shortest_paths

The k shortest simple paths between two vertices

widest_path

Widest path between two vertices

Notes

The paths are computed with a breadth-first search (BFS) or Dijkstra’s algorithm [dijkstra], if weights are given. Unless negative_weights or dag is True, the search proceeds alternately from the source and, along the reversed edges, from the target, until both searches meet [pohl-bidirectional]. If negative_weights == True, the Bellman-Ford algorithm is used [bellman-ford], which accepts negative weights, as long as there are no negative loops.

If a contraction hierarchy is given with parameter ch (see ContractionHierarchy), the path is found by a bidirectional search on the hierarchy, and its shortcuts are replaced by the vertices and edges of the graph they bypass. Between parallel edges, the one with the smallest weight is chosen, as in the other cases.

The algorithm runs in \(O(V + E)\) time, or \(O(V \log V)\) if weights are given (if dag == True this improves to \(O(V+E)\)).

References

[bfs]

Edward Moore, “The shortest path through a maze”, International Symposium on the Theory of Switching (1959), Harvard University Press

[dijkstra]

E. Dijkstra, “A note on two problems in connexion with graphs.” Numerische Mathematik, 1:269-271, 1959.

[pohl-bidirectional]

Ira Pohl, “Bi-directional search”, Machine Intelligence 6, 127-140 (1971).

Examples

>>> from numpy.random import poisson
>>> g = gt.random_graph(300, lambda: (poisson(4), poisson(4)))
>>> vlist, elist = gt.shortest_path(g, g.vertex(10), g.vertex(11))
>>> print([str(v) for v in vlist])
['10', '114', '96', '97', '11']
>>> print([str(e) for e in elist])
['(10, 114)', '(114, 96)', '(96, 97)', '(97, 11)']

A shortest path can be highlighted in a drawing of a network with stored positions:

>>> g = gt.collection.data["polbooks"]
>>> d, (s, t) = gt.pseudo_diameter(g)
>>> vlist, elist = gt.shortest_path(g, s, t)
>>> onpath = g.new_ep("bool")
>>> for e in elist:
...     onpath[e] = True
>>> inpath = g.new_vp("bool")
>>> for v in vlist:
...     inpath[v] = True
>>> vcolor = g.new_vp("string", vals=np.where(inpath.a, "#f28c8e",
...                                           "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(onpath.a, "#e41a1c",
...                                           "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(onpath.a, 3, 1))

The path is drawn on top of all other vertices and edges by giving its edges and vertices larger values of zorder:

>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
...               edge_color=ecolor, edge_pen_width=ewidth,
...               edge_zorder=onpath.copy("double"),
...               vertex_zorder=g.new_vp("double", vals=2 * inpath.a),
...               output="shortest_path-polbooks.pdf")
<...>
../_images/shortest_path-polbooks.png

Shortest path between the endpoints of a pseudo-diameter of the network of books about US politics, with its vertices and edges shown in red.#