def subgraph(self, v): """ Creates a subgraph by performing DFS in the current digraph for node v and taking any nodes and edges traversed to the subgraph. returns Digraph """ from pygraph.algorithms.traversal import NodeVisitor, dfs class Visitor(NodeVisitor): def __init__(self, result): self.result = result def visit_node(self, dg, v): self.result.add_node(v) def visit_edge(self, dg, v, w): self.result.add_edge(v, w) dg = Digraph() visitor = Visitor(dg) dfs(self, v, visitor) return dg
def acyclic_closure(digraph): """ @digraph: Digraph Generates reachability matrix for an acyclic digraph. Reachability matrix allows for constant time querying of whether node i can reach node j in a digraph. """ matrix = ByteNodeMatrix() for i in digraph.nodes_set(): for j in digraph.nodes_set(): reaches = (i == j) or traversal.dfs(digraph, i, None, lambda v: v != j) if reaches: matrix.set(i, j, 1) else: matrix.set(i, j, 0) return matrix