Created
November 11, 2019 17:21
-
-
Save wpcarro/5bdaadcdd1843093262cd74d3ed6acfb to your computer and use it in GitHub Desktop.
Transform a neighbors table into GraphViz source code for visualization purposes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from graphviz import Digraph | |
| from collections import deque | |
| # There are three ways to model a graph: | |
| # 1. Edge list: [(Vertex, Vertex)] | |
| # 2. Neighbors table: Map(Vertex, [Vertex]) | |
| # 3. Adjacency matrix: [[Boolean]] | |
| # | |
| # The following graph is a neighbors table. | |
| g = { | |
| 'a': [('b', 3), ('c', 5)], | |
| 'b': [('c', 4), ('d', 2)], | |
| 'c': [('d', 2), ('e', 2), ('f', 1)], | |
| 'd': [('c', 2), ('f', 1)], | |
| 'e': [('g', 1), ('f', 2)], | |
| 'f': [('g', 6), ('e', 2)], | |
| 'g': [], | |
| } | |
| # to_graphviz :: Vertex -> Map(Vertex, [(Vertex, Weight)]) -> String | |
| def to_graphviz(start, g): | |
| """Compiles the graph into GraphViz.""" | |
| d = Digraph() | |
| q = deque() | |
| seen = set() | |
| q.append(start) | |
| while q: | |
| v = q.popleft() | |
| if v in seen: | |
| continue | |
| d.node(v, label=v) | |
| for x, w in g[v]: | |
| d.edge(v, x, label=str(w)) | |
| q.append(x) | |
| seen.add(v) | |
| return d.source | |
| with open('/tmp/test.gv', 'w') as f: | |
| src = to_graphviz('a', g) | |
| f.write(src) | |
| print('/tmp/test.gv created!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment