Debian Codegraph @

rpython/tool/algo/graphlib.py

raw symbols SCIP
1 """
2 Utilities to manipulate graphs (vertices and edges, not control flow graphs).
3
4 Convention:
5 'vertices' is a set of vertices (or a dict with vertices as keys);
6 'edges' is a dict mapping vertices to a list of edges with its source.
7 Note that we can usually use 'edges' as the set of 'vertices' too.
8 """
9 from rpython.tool.ansi_print import AnsiLogger
10 from rpython.tool.identity_dict import identity_dict
11
12 log = AnsiLogger('graphlib')
13
14 class Edge:
15 def __init__(self, source, target):
16 self.source = source
17 self.target = target
18 def __repr__(self):
19 return '%r -> %r' % (self.source, self.target)
20
21 def make_edge_dict(edge_list):
22 "Put a list of edges in the official dict format."
23 edges = {}
24 for edge in edge_list:
25 edges.setdefault(edge.source, []).append(edge)
26 edges.setdefault(edge.target, [])
27 return edges
28
29 def depth_first_search(root, vertices, edges):
30 seen = set([root])
31 result = []
32 stack = []
33 while True:
34 result.append(('start', root))
35 stack.append((root, iter(edges[root])))
36 while True:
37 vertex, iterator = stack[-1]
38 try:
39 edge = next(iterator)
40 except StopIteration:
41 stack.pop()
42 result.append(('stop', vertex))
43 if not stack:
44 return result
45 else:
46 w = edge.target
47 if w in vertices and w not in seen:
48 seen.add(w)
49 root = w
50 break
51
52 def vertices_reachable_from(root, vertices, edges):
53 for event, v in depth_first_search(root, vertices, edges):
54 if event == 'start':
55 yield v
56
57 def strong_components(vertices, edges):
58 """Enumerates the strongly connected components of a graph. Each one is
59 a set of vertices where any vertex can be reached from any other vertex by
60 following the edges. In a tree, all strongly connected components are
61 sets of size 1; larger sets are unions of cycles.
62 """
63 component_root = {}
64 discovery_time = {}
65 remaining = vertices.copy()
66 stack = []
67
68 for root in vertices:
69 if root in remaining:
70
71 for event, v in depth_first_search(root, remaining, edges):
72 if event == 'start':
73 del remaining[v]
74 discovery_time[v] = len(discovery_time)
75 component_root[v] = v
76 stack.append(v)
77
78 else: # event == 'stop'
79 vroot = v
80 for edge in edges[v]:
81 w = edge.target
82 if w in component_root:
83 wroot = component_root[w]
84 if discovery_time[wroot] < discovery_time[vroot]:
85 vroot = wroot
86 if vroot == v:
87 component = {}
88 while True:
89 w = stack.pop()
90 del component_root[w]
91 component[w] = True
92 if w == v:
93 break
94 yield component
95 else:
96 component_root[v] = vroot
97
98 def all_cycles(root, vertices, edges):
99 """Enumerates cycles. Each cycle is a list of edges.
100 This may not give stricly all cycles if they are many intermixed cycles.
101 """
102 stackpos = {}
103 edgestack = []
104 result = []
105 def visit(v):
106 if v not in stackpos:
107 stackpos[v] = len(edgestack)
108 for edge in edges[v]:
109 if edge.target in vertices:
110 edgestack.append(edge)
111 yield visit(edge.target)
112 edgestack.pop()
113 stackpos[v] = None
114 else:
115 if stackpos[v] is not None: # back-edge
116 result.append(edgestack[stackpos[v]:])
117
118 pending = [visit(root)]
119 while pending:
120 generator = pending[-1]
121 try:
122 pending.append(next(generator))
123 except StopIteration:
124 pending.pop()
125 return result
126
127
128 def find_roots(vertices, edges):
129 """Find roots, i.e. a minimal set of vertices such that all other
130 vertices are reachable from them."""
131
132 rep = {} # maps all vertices to a random representing vertex
133 # from the same strongly connected component
134 for component in strong_components(vertices, edges):
135 random_vertex, _ = component.popitem()
136 rep[random_vertex] = random_vertex
137 for v in component:
138 rep[v] = random_vertex
139
140 roots = set(rep.values())
141 for v in vertices:
142 v1 = rep[v]
143 for edge in edges[v]:
144 try:
145 v2 = rep[edge.target]
146 if v1 is not v2: # cross-component edge: no root is needed
147 roots.remove(v2) # in the target component
148 except KeyError:
149 pass
150
151 return roots
152
153
154 def compute_depths(roots, vertices, edges):
155 """The 'depth' of a vertex is its minimal distance from any root."""
156 depths = {}
157 curdepth = 0
158 for v in roots:
159 depths[v] = 0
160 pending = list(roots)
161 while pending:
162 curdepth += 1
163 prev_generation = pending
164 pending = []
165 for v in prev_generation:
166 for edge in edges[v]:
167 v2 = edge.target
168 if v2 in vertices and v2 not in depths:
169 depths[v2] = curdepth
170 pending.append(v2)
171 return depths
172
173
174 def is_acyclic(vertices, edges):
175 class CycleFound(Exception):
176 pass
177 def visit(vertex):
178 visiting[vertex] = True
179 for edge in edges[vertex]:
180 w = edge.target
181 if w in visiting:
182 raise CycleFound
183 if w in unvisited:
184 del unvisited[w]
185 yield visit(w)
186 del visiting[vertex]
187 try:
188 unvisited = vertices.copy()
189 while unvisited:
190 visiting = {}
191 root = unvisited.popitem()[0]
192 pending = [visit(root)]
193 while pending:
194 generator = pending[-1]
195 try:
196 pending.append(next(generator))
197 except StopIteration:
198 pending.pop()
199 except CycleFound:
200 return False
201 else:
202 return True
203
204
205 def break_cycles(vertices, edges):
206 """Enumerates a reasonably minimal set of edges that must be removed to
207 make the graph acyclic."""
208
209 import py; py.test.skip("break_cycles() is not used any more")
210
211 # the approach is as follows: starting from each root, find some set
212 # of cycles using a simple depth-first search. Then break the
213 # edge that is part of the most cycles. Repeat.
214
215 remaining_edges = edges.copy()
216 progress = True
217 roots_finished = set()
218 while progress:
219 roots = list(find_roots(vertices, remaining_edges))
220 #print '%d inital roots' % (len(roots,))
221 progress = False
222 for root in roots:
223 if root in roots_finished:
224 continue
225 cycles = all_cycles(root, vertices, remaining_edges)
226 if not cycles:
227 roots_finished.add(root)
228 continue
229 #print 'from root %r: %d cycles' % (root, len(cycles))
230 allcycles = identity_dict()
231 edge2cycles = {}
232 for cycle in cycles:
233 allcycles[cycle] = cycle
234 for edge in cycle:
235 edge2cycles.setdefault(edge, []).append(cycle)
236 edge_weights = {}
237 for edge, cycle in edge2cycles.iteritems():
238 edge_weights[edge] = len(cycle)
239 while allcycles:
240 max_weight = 0
241 max_edge = None
242 for edge, weight in edge_weights.iteritems():
243 if weight > max_weight:
244 max_edge = edge
245 max_weight = weight
246 if max_edge is None:
247 break
248 # kill this edge
249 yield max_edge
250 progress = True
251 # unregister all cycles that have just been broken
252 for broken_cycle in edge2cycles[max_edge]:
253 broken_cycle = allcycles.pop(broken_cycle, ())
254 for edge in broken_cycle:
255 edge_weights[edge] -= 1
256
257 lst = remaining_edges[max_edge.source][:]
258 lst.remove(max_edge)
259 remaining_edges[max_edge.source] = lst
260 assert is_acyclic(vertices, remaining_edges)
261
262 def compute_predecessors(vertices, edgedict):
263 result = {}
264 for node, edges in edgedict.iteritems():
265 for edge in edges:
266 result.setdefault(edge.target, set()).add(edge.source)
267 return result
268
269 def remove_leaves(vertices, edgedict):
270 """ recursively remove all leaves in the graph, ie nodes that have no
271 outgoing edges. """
272 incoming = compute_predecessors(vertices, edgedict)
273 return remove_leaves_incoming(vertices, edgedict, incoming)
274
275 def remove_leaves_incoming(vertices, edgedict, incoming, leaves=None):
276 """ helper function for remove_leaves, but useful on its own: incoming is
277 the result of compute_predecessors on the graph, can be re-used when
278 removing many leaves from the same graph, many times. when the optional
279 argument leaves is given, start removing things from those nodes. """
280 if leaves is None:
281 leaves = {source for source, edges in edgedict.iteritems()
282 if len(edges) == 0}
283 for leave in leaves:
284 del edgedict[leave]
285 del vertices[leave]
286 while 1:
287 if not leaves:
288 break
289
290 new_leaves = set()
291 to_update = set()
292 to_update.update(*[incoming.get(leave, set()) for leave in leaves])
293 for vertex in to_update:
294 if vertex not in edgedict:
295 continue
296 edges = edgedict[vertex]
297 i = 0
298 while i < len(edges):
299 edge = edges[i]
300 if edge.target in leaves:
301 del edges[i]
302 else:
303 i += 1
304 if not edges:
305 new_leaves.add(vertex)
306 leaves = new_leaves
307
308 for leave in leaves:
309 del edgedict[leave]
310 del vertices[leave]
311
312
313 def copy_edges(edges):
314 """ make a deep copy of edges """
315 result = {}
316 for key, value in edges.items():
317 result[key] = value[:]
318 return result
319
320
321 def break_cycles_v(vertices, edges):
322 """Enumerates a reasonably minimal set of vertices that must be removed to
323 make the graph acyclic."""
324
325 # Consider where each cycle should be broken -- we go for the idea
326 # that it is often better to break it as far as possible from the
327 # cycle's entry point, so that the stack check occurs as late as
328 # possible. For the distance we use a global "depth" computed as
329 # the distance from the roots. The algo below is:
330 # - get a list of cycles
331 # - let maxdepth(cycle) = max(depth(vertex) for vertex in cycle)
332 # - sort the list of cycles by their maxdepth, nearest first
333 # - for each cycle in the list, if the cycle is not broken yet,
334 # remove the vertex with the largest depth
335 # - repeat the whole procedure until no more cycles are found.
336 # Ordering the cycles themselves nearest first maximizes the chances
337 # that when breaking a nearby cycle - which must be broken in any
338 # case - we remove a vertex and break some further cycles by chance.
339 edges = copy_edges(edges) # we mutate it
340 incoming = compute_predecessors(vertices, edges)
341
342 v_depths = vertices
343 progress = True
344 roots_finished = set()
345 while progress:
346 roots = list(find_roots(v_depths, edges))
347 if v_depths is vertices: # first time only
348 v_depths = compute_depths(roots, vertices, edges)
349 assert len(v_depths) == len(vertices) # ...so far. We remove
350 # from v_depths the vertices at which we choose to break cycles
351
352 # now that we computed the depths, we can remove all leaves,
353 # recursively. those won't contribute to cycles, but the all_cycles
354 # calls below otherwise try to walk into them repeatedly
355 remove_leaves_incoming(v_depths, edges, incoming)
356 #print '%d inital roots' % (len(roots,))
357 progress = False
358 for root in roots:
359 if root in roots_finished or root not in v_depths:
360 continue
361 cycles = all_cycles(root, v_depths, edges)
362 log.dot()
363 if not cycles:
364 roots_finished.add(root)
365 continue
366 #print 'from root %r: %d cycles' % (root, len(cycles))
367 # compute the "depth" of each cycles: how far it goes from any root
368 allcycles = []
369 for cycle in cycles:
370 cycledepth = max([v_depths[edge.source] for edge in cycle])
371 allcycles.append((cycledepth, cycle))
372 allcycles.sort()
373 # consider all cycles starting from the ones with smallest depth
374 removed = set()
375 for _, cycle in allcycles:
376 try:
377 choices = [(v_depths[edge.source], edge.source)
378 for edge in cycle]
379 except KeyError:
380 pass # this cycle was already broken
381 else:
382 # break this cycle by removing the furthest vertex
383 max_depth, max_vertex = max(choices)
384 del v_depths[max_vertex]
385 del edges[max_vertex]
386 yield max_vertex
387 removed.add(max_vertex)
388 progress = True
389
390 # early exit when were done. it's quite fast if there are cycles
391 if is_acyclic(v_depths, edges):
392 return
393 # remove leaves, now that we have removed many cycles
394 # start removing leaves from the nodes that we just removed
395 remove_leaves_incoming(v_depths, edges, incoming, removed)
396
397
398 def show_graph(vertices, edges):
399 from rpython.translator.tool.graphpage import GraphPage, DotGen
400 class MathGraphPage(GraphPage):
401 def compute(self):
402 dotgen = DotGen('mathgraph')
403 names = {}
404 for i, v in enumerate(vertices):
405 names[v] = 'node%d' % i
406 for i, v in enumerate(vertices):
407 dotgen.emit_node(names[v], label=str(v))
408 for edge in edges[v]:
409 dotgen.emit_edge(names[edge.source], names[edge.target])
410 self.source = dotgen.generate(target=None)
411 MathGraphPage().display()