Generate adjacency matrix in graphviz

Viewed 2620

I would like to know if I could use graphviz to generate an image of an adjacency matrix. For example from this file:

digraph { 
    A -> B; 
    B -> C; 
    A -> C; 
    D -> C; 
    E -> C; 
    E -> A; 
}

The result should be something like this:

enter image description here

If it is not possible, is there any other software I could use?

1 Answers

Here are some ideas:

I'm not aware of a functionality that allows graphviz to print the matrix, however, if the input graphviz code is relatively clean (free of attributes or weird nodes), I don't see how it would be hard to write a simple parser to produce the desired output.

you may do something simple, like the following example (python):

import pprint
# Example input file with "digraph g {" elided for simplicity:
s = """A -> B; 
    B -> C; 
    A -> C; 
    D -> C; 
    E -> C; 
    E -> A; """
lines = s.split("\n")
all_edges = []
pairs = []
for line in lines:
    edge = line.replace(";", "").replace(" ", "").split("->")
    if len(edge) == 2:
        all_edges.append(edge[0])
        all_edges.append(edge[1])
        pairs.append(edge)

unique_edges = set(all_edges)

matrix = {origin: {dest: 0 for dest in all_edges} for origin in all_edges}
for p in pairs:
    matrix[p[0]][p[1]] += 1
pprint.pprint(matrix)

Once all is done, this is what the output looks like, you may write a bit more code to output html or any tabular format of your choosing:

"""
Output:
{'A': {'A': 0, 'B': 1, 'C': 1, 'D': 0, 'E': 0},
 'B': {'A': 0, 'B': 0, 'C': 1, 'D': 0, 'E': 0},
 'C': {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0},
 'D': {'A': 0, 'B': 0, 'C': 1, 'D': 0, 'E': 0},
 'E': {'A': 1, 'B': 0, 'C': 1, 'D': 0, 'E': 0}}
 """

I hope this helps!

Related