Skip to content

Instantly share code, notes, and snippets.

@slotrans
Created February 17, 2018 20:55
Show Gist options
  • Save slotrans/d28efd3a09d39230f2f2d33a17a4355d to your computer and use it in GitHub Desktop.
Save slotrans/d28efd3a09d39230f2f2d33a17a4355d to your computer and use it in GitHub Desktop.
This is a small script which can be used to filter a DOT-language (Graphviz) graph file describing a DAG.
import sys
import argparse
import networkx
# pydot is also required
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Tool for filtering Graphviz/DOT directed graphs. Pass the source graph on STDIN, the filtered graph will be sent to STDOUT.')
parser.add_argument('nodes', metavar='node', nargs='+', help='One or more nodes to use for filtering, according to the chosen mode')
parser.add_argument('--mode', choices=['source','target','through'], default='through', help='Output only that part of the graph that flows out from (source), into (target), or through the specified nodes')
args = parser.parse_args()
##########################
input_graph = networkx.nx_pydot.read_dot(sys.stdin)
selected = set()
for node in args.nodes:
selected.add(node)
if args.mode in ('source','through'):
selected = selected.union(networkx.descendants(input_graph, node))
if args.mode in ('target','through'):
selected = selected.union(networkx.ancestors(input_graph, node))
filtered_graph = input_graph.subgraph(selected)
networkx.nx_pydot.write_dot(filtered_graph, sys.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment