Search code examples
pythonpython-3.xgraphgraphvizpygraphviz

Comparing two graphviz.Digraph objects


I have two digraphs in the form:

dot1 = graphviz.Digraph(format='svg')
dot1.attr('node', shape = 'box')


dot2 = graphviz.Digraph(format='svg')
dot2.attr('node', shape = 'box')

How can I compare these two digraphs? By comparing I mean I find the uncommon nodes and uncommon edges between similar nodes?

The nodes of these graphs have names, ie. "add".

I would appreciate any suggestions or thoughts on this problem. Thanks!


Solution

  • You won't be able to do that using the graphviz module by itself; this module is primarily concerned with generating dot output, rather than parsing dot syntax and providing a structured API.

    TThe pygraphviz can probably do what you want. With this in place, we can do this:

    >>> import graphviz
    >>> import pygraphviz as pgv
    >>> dot1 = graphviz.Digraph(format='svg')
    >>> dot1.node('node1')
    >>> dot1.node('node2')
    >>> dot1.edge('node1', 'node2')
    >>> g = pgv.AGraph(string=str(dot1))
    

    And now that we've parsed the dot syntax, we can ask for a list of nodes:

    >>> g.nodes()
    ['node1', 'node2']
    

    Or a list of edges:

    >>> g.edges()
    [('node1', 'node2')]
    

    And that should be sufficient for you to perform the comparison you were asking about.