-
Notifications
You must be signed in to change notification settings - Fork 0
/
coloring.py
183 lines (134 loc) · 4.69 KB
/
coloring.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import networkx as nx
import matplotlib.pyplot as plt
from multiprocessing import Pool
#from functools import partial
import itertools
from random import choice
def countColorsUsed(graph):
d = {}
for n in graph.nodes():
currentColor = graph.node[n]['color']
if currentColor not in d:
d[currentColor] = 1
return len(d.keys())
def displayColoring(graph, name):
#drawing
minimalColoring(graph,len(graph.nodes()) + 1)
print "using {} colors".format(countColorsUsed(graph))
pos = nx.circular_layout(graph)
colorList = []
labels = {}
#matplotlib maps color integers to some range, can control
#this using a parameter to draw_networkx_nodes apparently
for n in graph.nodes():
colorList.append(graph.node[n]['color'])
labels[n] = n
nx.draw_networkx_nodes(graph, pos,
node_color=colorList,
node_size=620
)
nx.draw_networkx_edges(graph, pos, width=1.0, alpha=0.5)
nx.draw_networkx_labels(graph ,pos,labels,font_size=10, font_color='white')
plt.axis('off')
plt.savefig(name + ".png") # save as png
plt.show() # display
def colorIsSafe(graph, neighbors, color):
for n in neighbors:
if graph.node[n]['color'] == color:
return False
return True
def maxCommonColorSet(graph):
d = {}
for n in graph.nodes():
currentColor = graph.node[n]['color']
if currentColor not in d:
d[currentColor] = [n]
else:
d[currentColor].append(n)
maxCount = 0
c = -1
for color in d.keys():
if len(d[color]) > maxCount:
maxCount = len(d[color])
c = color
return d[c]
def verifyColoring(graph):
for n in graph.nodes():
neighbors = graph.neighbors(n)
for m in neighbors:
if graph.node[m]['color'] == graph.node[n]['color']:
return False
return True
#k = number of colors, n = current vertex index
def colorUtil(vertex, vertexList, graph, k, n):
#get the adjacent vertices of this vertex
neighbors = graph.neighbors(vertex)
if n == (len(graph) - 1): #we're at the last vertex
#if this vertex is colorable, we've colored all vertices
for color in xrange(1, k+1):
if colorIsSafe(graph, neighbors, color):
graph.node[vertex]['color'] = color
#if we weren't able to color this vertex, return false
if graph.node[vertex]['color'] == -1:
return False
return True
for color in xrange(1,k+1):
if colorIsSafe(graph, neighbors, color):
#this color is safe, try assigning it
graph.node[vertex]['color'] = color
if colorUtil(vertexList[n+1], vertexList, graph, k, n+1):
return True
#if this coloring didn't lead to a solution, backtrack
graph.node[vertex]['color'] = -1
return False
def colorHelper(g, k):
if colorUtil(g.nodes()[0], g.nodes(), g, k, 0):
return True
return False
def colorHelper_star(a_b):
"""Convert `f([1,2])` to `f(1,2)` call."""
return colorHelper(*a_b)
def minimalColoringMP(g):
if len(g.nodes()) == 0:
return 0
p = Pool(4)
max_degree = max([g.degree(v) for v in g.nodes()])
upper_bound = max_degree + 1
cliques = list(nx.find_cliques(g))
if len(cliques) == 0:
lower_bound = 1
else:
lower_bound = len(max(cliques))
#print "lower bound: {}, upper bound: {}".format(max_clique_size, upper_bound)
if upper_bound == lower_bound:
return upper_bound
for n in g.nodes():
g.node[n]['color'] = -1
colorings = range(lower_bound, upper_bound + 1)
chi = p.map(colorHelper_star,
itertools.izip(
itertools.repeat(g.copy()),
colorings)
).index(True) + 1
return chi
def minimalColoring(g, r):
# max_degree = max([g.degree(v) for v in g.nodes()])
# upper_bound = max_degree + 1
#lower bound
max_clique_size = len(max(list(nx.find_cliques(g)))) #max_degree = max([g.degree(v) for v in g.nodes()])
cliques = list(nx.find_cliques(g))
if len(cliques) == 0:
lower_bound = 1
else:
lower_bound = len(max(cliques))
# dont bother coloring if lower bound is more than we are
# looking for (assumes r is normalized to the power of the graph)
if lower_bound > r:
return lower_bound
for n in g.nodes():
g.node[n]['color'] = -1
for k in range(lower_bound, len(g.nodes()) + 1):
#attempt a k-coloring
if colorUtil(g.nodes()[0], g.nodes(), g, k, 0):
#print k
return k