Debian Codegraph @

rpython/tool/algo/color.py

raw symbols SCIP
1
2 class DependencyGraph(object):
3
4 def __init__(self):
5 self._all_nodes = []
6 self.neighbours = {}
7
8 def add_node(self, v):
9 if v not in self.neighbours:
10 self._all_nodes.append(v)
11 self.neighbours[v] = set()
12
13 def add_edge(self, v1, v2):
14 assert v1 != v2
15 self.neighbours[v1].add(v2)
16 self.neighbours[v2].add(v1)
17
18 def coalesce(self, vold, vnew):
19 """Remove vold from the graph, and attach all its edges to vnew."""
20 for n in self.neighbours.pop(vold):
21 self.neighbours[n].remove(vold)
22 assert vnew != n
23 self.neighbours[n].add(vnew)
24 self.neighbours[vnew].add(n)
25 # we should remove vold from self._all_nodes, but it's too costly
26 # so we rely on getnodes() to filter self._all_nodes.
27
28 def getnodes(self):
29 return [v for v in self._all_nodes if v in self.neighbours]
30
31 def lexicographic_order(self):
32 """Enumerate a lexicographic breadth-first ordering of the nodes."""
33 sigma = [self.getnodes()[::-1]]
34 if not sigma[0]:
35 return
36 while sigma:
37 v = sigma[0].pop()
38 yield v
39 newsigma = []
40 neighb = self.neighbours[v]
41 for s in sigma:
42 s1 = []
43 s2 = []
44 for x in s:
45 if x in neighb:
46 s1.append(x)
47 else:
48 s2.append(x)
49 if s1:
50 newsigma.append(s1)
51 if s2:
52 newsigma.append(s2)
53 sigma = newsigma
54
55 def size_of_largest_clique(self):
56 """Assuming that the graph is chordal, compute the size of
57 the largest clique in it."""
58 result = 0
59 seen = set()
60 for v in self.lexicographic_order():
61 num = 1
62 for n in self.neighbours[v]:
63 if n in seen:
64 num += 1
65 if num > result:
66 result = num
67 seen.add(v)
68 return result
69
70 def find_node_coloring(self):
71 """Return a random minimal node coloring, assuming that
72 the graph is chordal. For non-chordal graphs this is just
73 an approximately good answer (but still a valid one)."""
74 result = {}
75 for v in self.lexicographic_order():
76 forbidden = 0 # bitset
77 for n in self.neighbours[v]:
78 if n in result:
79 forbidden |= (1 << result[n])
80 # find the lowest 0 bit
81 num = 0
82 while forbidden & (1 << num):
83 num += 1
84 result[v] = num
85 return result