topological_sort#
- graph_tool.structure.topological_sort(g, lexicographic=False, key=None)[git][source]#
Return the topological sort of the given graph. It is returned as an array of vertex indices, in the sort order.
- Parameters:
- g
Graph Graph to be used. It must be a directed acyclic graph (DAG).
- lexicographic
bool(optional, default:False) If
True, the lexicographically smallest topological sort is returned (see below).- key
VertexPropertyMap(optional, default:None) Scalar vertex priorities for the lexicographic sort, which is implied if this is given. If not given, the vertex indices are used.
- g
- Returns:
- sort
numpy.ndarray Array of vertex indices in topological order.
- sort
See also
all_topological_sortsAll topological orderings
topological_generationsTopological generation of every vertex
is_DAGTest for directed acyclic graphs
dag_longest_pathLongest path of a directed acyclic graph
Notes
The topological sort algorithm creates a linear ordering of the vertices such that if edge (u,v) appears in the graph, then u comes before v in the ordering. The graph must be a directed acyclic graph (DAG).
The time complexity is \(O(V + E)\).
With
lexicographic == True, the sort is obtained with Kahn’s algorithm [kahn-topological-1962], where among the vertices whose predecessors have all been placed the one with the smallest key (and the smallest index among equal keys) is placed next. This takes time \(O((V + E)\log V)\).References
[kahn-topological-1962]Arthur B. Kahn, “Topological sorting of large networks”, Communications of the ACM 5, 558-562 (1962), DOI: 10.1145/368996.369025 [sci-hub, @tor]
[topological-boost][topological-wiki]Examples
>>> g = gt.random_graph(30, lambda: (3, 3)) >>> tree = gt.minimum_spanning_tree(g) >>> g.set_edge_filter(tree) >>> sort = gt.topological_sort(g) >>> print(sort) [28 27 29 26 25 24 22 21 20 19 18 16 15 14 13 11 9 8 7 3 2 10 4 17 5 1 0 12 23 6] >>> print(gt.topological_sort(g, lexicographic=True)) [20 15 25 0 8 13 23 6 26 2 10 4 17 5 21 28 7 11 27 14 3 29 12 22 1 19 16 18 9 24]
A topological ordering can be visualized by placing the vertices of a directed acyclic graph along the horizontal axis in its order, and along the vertical axis in their topological generations (see
topological_generations()), so that every edge points to the right:>>> es = [(i, j) for i in range(12) for j in range(i + 1, 12) ... if np.random.random() < .25] >>> g = gt.Graph(es) >>> sort = gt.topological_sort(g) >>> rank = g.new_vp("int") >>> rank.a[sort] = np.arange(g.num_vertices()) >>> gen = gt.topological_generations(g) >>> pos = g.new_vp("vector<double>", ... vals=np.array([rank.a, 3 * gen.a]).T) >>> gt.graph_draw(g, pos, vertex_text=g.vertex_index, ... vertex_fill_color="#cccccc", edge_color="#999999", ... vertex_size=30, output="topological_sort-dag.pdf") <...>
Topological ordering of a random directed acyclic graph, with the vertices placed horizontally in the order and vertically by their topological generation.#