-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_theory.py
157 lines (128 loc) · 4.37 KB
/
graph_theory.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pydot
class Tree(object):
def __init__(self, name, parent, weight=1):
# name: str
# parent: Optional[Tree]
self.name = name
self.parent = parent
# children: Tuple[Tree]
self.children = ()
# weight: int
self.weight = 1
@property
def size(self):
# Returns: int
result = 1 # Count self.
for child in self.children:
result += child.size
return result
def get(self, name):
# name: str
# Returns: Optional[Tree]
# Raises: RuntimeError
if name == self.name:
return self
matches = []
for child in self.children:
match = child.get(name)
if match is not None:
matches.append(match)
if len(matches) == 0:
return None
elif len(matches) == 1:
return matches[0]
else:
raise RuntimeError('Too many matches', matches)
def add_child(self, name):
# name: str
new_node = Tree(name, self)
self.children += (new_node,)
def is_same(self, node):
# node: Tree
name1 = clean_name(self.name)
name2 = clean_name(node.name)
if name1 != name2:
return False
if len(self.children) != len(node.children):
return False
for child1, child2 in zip(self.children, node.children):
if not child1.is_same(child2):
return False
return True
def collapse(self):
uniques = []
for child in self.children:
matched = []
for existing in uniques:
if child.is_same(existing):
matched.append(existing)
if len(matched) == 0:
uniques.append(child)
elif len(matched) == 1:
matched[0].weight += 1
else:
raise RuntimeError('Too many matches', matches)
self.children = tuple(uniques)
for child in self.children:
child.collapse()
def pydot(self, names=None):
if names is None:
names = set()
if self.parent is None:
graph = pydot.Dot()
else:
graph = pydot.Subgraph()
subgraphs = []
edges = []
for child in self.children:
subgraphs.append(child.pydot(names=names))
names.update((self.name, child.name))
edge = pydot.Edge(
self.name,
child.name,
)
if child.weight != 1:
edge.obj_dict['attributes']['label'] = str(child.weight)
edges.append(edge)
for subgraph in subgraphs:
graph.add_subgraph(subgraph)
for edge in edges:
graph.add_edge(edge)
if self.parent is None:
graph.obj_dict['attributes']['rankdir'] = 'LR'
for name in names:
stripped_name = clean_name(name)
if stripped_name != name:
node = pydot.Node(name)
node.obj_dict['attributes']['label'] = stripped_name
graph.add_node(node)
return graph
def save_graphviz(self, filename_base):
self.collapse()
graph = self.pydot()
filename_dot = '{}.dot'.format(filename_base)
with open(filename_dot, 'w') as file_obj:
file_obj.write(graph.to_string())
print('Created {}'.format(filename_dot))
filename_svg = '{}.svg'.format(filename_base)
with open(filename_svg, 'wb') as file_obj:
file_obj.write(graph.create_svg())
print('Created {}'.format(filename_svg))
def clean_name(name):
result = name.rstrip('+')
if result[:7] == 'Thread-':
result = result[7:]
return result