-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
123 lines (76 loc) · 2.61 KB
/
graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
""" Plotting VPP graph """
__author__ = "Mani Amoozadeh"
import os
import re
import argparse
import pydot
import networkx as nx
def read_file(file_path):
with open(file_path, 'r') as file:
return file.read()
def parse_data(data):
nodes = {}
pattern = re.compile(r'^(?P<node>\S+)?\s*((?P<child>\S+)\s*\[\d+\])?\s*(?P<parent>\S+)?\s*$')
node_name_last = ""
node_child_list = []
node_parent_list = []
lines = data.splitlines()
for line in lines:
if not line and node_name_last:
if node_name_last in nodes:
print(f"WARNING: node name {node_name_last} has been encountered before.")
nodes[node_name_last] = {
'children': node_child_list,
'parents': node_parent_list
}
node_name_last = ""
node_child_list = []
node_parent_list = []
continue
match = pattern.match(line)
if not match:
continue
parts = match.groupdict()
node_name = parts["node"]
child_name = parts["child"]
parent_name = parts["parent"]
if node_name:
node_name_last = node_name
if child_name:
node_child_list.append(child_name)
if parent_name:
node_parent_list.append(parent_name)
if node_name_last:
nodes[node_name_last] = {
'children': node_child_list,
'parents': node_parent_list
}
return nodes
def create_graph(nodes):
G = nx.DiGraph()
for node, relations in nodes.items():
for child in relations['children']:
G.add_edge(node, child)
for parent in relations['parents']:
G.add_edge(parent, node)
return G
def plot_graph(G, plot_dir):
filename = "vpp"
file_dot = os.path.join(plot_dir, f"{filename}.dot")
file_png = os.path.join(plot_dir, f"{filename}.png")
nx.drawing.nx_pydot.write_dot(G, file_dot)
(graph,) = pydot.graph_from_dot_file(file_dot)
graph.write_png(file_png)
if __name__ == "__main__":
main_parser = argparse.ArgumentParser(description="Utility to plot VPP graph")
##########
group_vpp = main_parser.add_argument_group('vpp_graph', 'VPP')
group_vpp.add_argument('--input', help='path to VPP graph text file')
group_vpp.add_argument('--output_dir', help='directory to save VPP plot', default=os.getcwd())
args = main_parser.parse_args()
##########
data = read_file(args.input)
nodes = parse_data(data)
G = create_graph(nodes)
plot_graph(G, args.output_dir)