transitive_closure

transitive_closure#

graph_tool.structure.transitive_closure(g, reflexive=False)[git][source]#

Return the transitive closure graph of g.

Parameters:
gGraph

Directed graph to be used.

reflexivebool or None (optional, default: False)

If True, every vertex gets a self-loop; if None, no vertex does; if False, only the vertices on a cycle do.

Returns:
tcGraph

The transitive closure graph.

See also

transitive_reduction

Inverse operation for directed acyclic graphs

count_reachable

Number of vertices reachable from every vertex

label_out_component

Vertices reachable from a given vertex

Notes

The transitive closure of a graph G = (V,E) is a graph G* = (V,E*) such that E* contains an edge (u,v) if and only if G contains a path (of at least one edge) from u to v. The transitive_closure() function transforms the input graph g into the transitive closure graph tc. Hence, a vertex has a self-loop in tc if and only if it lies on a cycle, unless reflexive is True (the reflexive transitive closure, where every vertex has a self-loop) or None (where none has).

The time complexity (worst-case) is \(O(VE)\).

References

Examples

>>> g = gt.random_graph(30, lambda: (3, 3))
>>> tc = gt.transitive_closure(g)
>>> print(tc.num_edges(), gt.transitive_closure(g, reflexive=None).num_edges())
900 870

For a small directed acyclic graph, the edges added by the closure can be shown in a drawing:

>>> g = gt.Graph([(0, 1), (1, 2), (2, 3), (1, 4), (4, 3)])
>>> tc = gt.transitive_closure(g, reflexive=None)
>>> new = tc.new_ep("bool")
>>> for e in tc.edges():
...     new[e] = g.edge(e.source(), e.target()) is None
>>> ecolor = tc.new_ep("string", vals=np.where(new.a, "#e41a1c",
...                                            "#999999"))
>>> pos = tc.new_vp("vector<double>", vals=[(0, 0), (1, 1), (2.5, 1.5),
...                                         (3, 0), (1.5, -1)])
>>> gt.graph_draw(tc, pos, vertex_text=tc.vertex_index,
...               vertex_fill_color="#cccccc", edge_color=ecolor,
...               vertex_size=25, edge_pen_width=2,
...               output="transitive_closure-dag.pdf")
<...>
../_images/transitive_closure-dag.png

Transitive closure of a directed acyclic graph of five vertices. The edges of the original graph are shown in gray, and those added by the closure in red.#