Graph coloring¶
Give each vertex of a graph a color so that no two neighbors share one, and use as few colors as possible. The smallest number of colors that works is the graph's chromatic number. Timetables (exams that share students need different time slots), frequency assignment (nearby transmitters need different channels) and register allocation in compilers all reduce to this problem.
This example colors two queen graphs from the DIMACS coloring benchmarks. The vertices are the squares of an n by n chessboard, and two squares are neighbors when a queen on one attacks the other: same row, same column or same diagonal. The graphs are generated by a few lines of code, so no data file is needed.
| Instance | Vertices | Edges | Chromatic number |
|---|---|---|---|
| queen6_6 | 36 | 290 | 7 |
| queen8_8 | 64 | 728 | 9 |
The chromatic numbers are from the DIMACS graph coloring instances (M. Trick) and OEIS A088202.
The model¶
The number of colors k is fixed, and the variable is the color of each vertex: one Integer vector with a value from 0 to k - 1 per vertex. The objective is the number of conflicts, the edges whose two ends have the same color. A coloring with 0 conflicts is a valid coloring with k colors, so the target is 0 and the run stops when it gets there. To find the fewest colors, start with the k of a quick greedy coloring and lower it while the search still reaches 0 conflicts.
This is the model of the classic tabu search for coloring, TabuCol (Hertz and de Werra, 1987). A move gives one vertex another color (the reset move of integers, see neighborhoods), and the tabu list keeps the vertex from going straight back to its old color. A Partition into k groups describes the same colorings, but its solutions decode to lists of groups, so the objective could not count the conflicts of a whole batch at once. The objective here is vectorized: it counts the conflicts of all candidate colorings in one NumPy call.
import numpy as np
import ypea
n = 6 # queen6_6: a 6 by 6 board, 36 squares
k = 7 # the number of colors
# two squares are neighbors when a queen on one attacks the other
edges = []
for a in range(n * n):
for b in range(a + 1, n * n):
row_a, col_a = divmod(a, n)
row_b, col_b = divmod(b, n)
if row_a == row_b or col_a == col_b or abs(row_a - row_b) == abs(col_a - col_b):
edges.append((a, b))
edges = np.array(edges)
def conflicts(sol):
color = sol.color # (batch, 36): the color of each square in a batch of colorings
same = color[..., edges[:, 0]] == color[..., edges[:, 1]]
return np.sum(same, axis=-1)
problem = ypea.Problem(
ypea.Integer("color", n * n, lb=0, ub=k - 1),
conflicts,
vectorized=True,
name="queen6_6, 7 colors",
optimum=0,
)
alg = ypea.TabuSearch(
moves={"color": ["reset"]}, # a move gives one square another color
tenure=(2, 10),
max_nfe=200_000,
target=0, # stop at the first coloring without conflicts
)
result = alg.solve(problem, seed=1)
print(result.summary())
print(result.best.solution.color.reshape(n, n) + 1)
TS on queen6_6, 7 colors
best objective value: 0
error: 0
feasible: True (violation 0)
evaluations: 163297, iterations: 756, time: 0.798 s, stopped by: target
[[5 2 4 1 3 7]
[7 1 3 2 6 4]
[2 4 6 5 1 3]
[6 7 2 3 4 5]
[4 3 5 6 7 1]
[1 6 7 4 5 2]]
Differs from Python: MATLAB draws its own random numbers, so the results differ from Python's. Colors run from 1 to 7, and moves is a struct keyed by the variable name.
n = 6; % queen6_6: a 6 by 6 board, 36 squares
k = 7; % the number of colors
% two squares are neighbors when a queen on one attacks the other
edges = zeros(0, 2);
for a = 1:n * n
for b = a + 1:n * n
row_a = floor((a - 1) / n);
col_a = mod(a - 1, n);
row_b = floor((b - 1) / n);
col_b = mod(b - 1, n);
if row_a == row_b || col_a == col_b || abs(row_a - row_b) == abs(col_a - col_b)
edges(end + 1, :) = [a, b];
end
end
end
problem = ypea.Problem( ...
vars=ypea.Integer("color", shape=n * n, lb=1, ub=k), ...
objective=@(sol) conflicts(sol, edges), ...
vectorized=true, ...
name="queen6_6, 7 colors", ...
optimum=0);
alg = ypea.TabuSearch( ...
moves=struct("color", "reset"), ... % a move gives one square another color
tenure=[2 10], ...
max_nfe=200000, ...
target=0); % stop at the first coloring without conflicts
result = alg.solve(problem, seed=1);
disp(result.summary())
disp(reshape(result.best.solution.color, n, n)') % squares are numbered row by row
function count = conflicts(sol, edges)
color = sol.color; % (batch, 36): the color of each square in a batch of colorings
same = color(:, edges(:, 1)) == color(:, edges(:, 2));
count = sum(same, 2);
end
TS on queen6_6, 7 colors
best objective value: 0
error: 0
feasible: true (violation 0)
evaluations: 36289, iterations: 168, time: 0.923 s, stopped by: target
2 1 7 4 5 6
3 5 6 1 7 2
6 7 3 2 4 1
1 2 4 7 3 5
4 3 1 5 6 7
5 6 2 3 1 4
Tabu search colors queen6_6 with 7 colors, the chromatic number, in under a second. The tabu tenure of 2 to 10 iterations is shorter than the default of 7 to 20. On queen8_8 it finds valid colorings much more often (see the results). The full script, examples/applications/graph_coloring.py, also colors queen8_8 and lowers k step by step from the greedy coloring.
Why not a classical method¶
The classic quick method is DSATUR (Brélaz, 1979), a greedy rule: color next the vertex whose neighbors already use the most distinct colors, with the lowest color that fits. It is fast and often good, but not on queen graphs:
n = 6
n_vertices = n * n
neighbors = []
for a in range(n_vertices):
neighbors.append([])
for a in range(n_vertices):
for b in range(n_vertices):
row_a, col_a = divmod(a, n)
row_b, col_b = divmod(b, n)
attack = row_a == row_b or col_a == col_b or abs(row_a - row_b) == abs(col_a - col_b)
if a != b and attack:
neighbors[a].append(b)
def neighbor_colors(v, color):
"""The colors already given to the neighbors of v."""
used = set()
for u in neighbors[v]:
if color[u] is not None:
used.add(color[u])
return used
# DSATUR: color next the square whose neighbors use the most distinct colors
color = [None] * n_vertices
for _ in range(n_vertices):
best, best_key = None, None
for v in range(n_vertices):
if color[v] is None:
key = (len(neighbor_colors(v, color)), len(neighbors[v])) # ties: more neighbors first
if best is None or key > best_key:
best, best_key = v, key
used = neighbor_colors(best, color)
c = 0
while c in used: # the lowest color no neighbor has
c += 1
color[best] = c
print("DSATUR uses", max(color) + 1, "colors")
DSATUR uses 9 colors
Differs from Python: Squares and colors are numbered from 1.
n = 6;
n_vertices = n * n;
neighbors = cell(1, n_vertices);
for a = 1:n_vertices
neighbors{a} = [];
for b = 1:n_vertices
row_a = floor((a - 1) / n);
col_a = mod(a - 1, n);
row_b = floor((b - 1) / n);
col_b = mod(b - 1, n);
attack = row_a == row_b || col_a == col_b || abs(row_a - row_b) == abs(col_a - col_b);
if a ~= b && attack
neighbors{a}(end + 1) = b;
end
end
end
% DSATUR: color next the square whose neighbors use the most distinct colors
color = zeros(1, n_vertices); % 0: not colored yet
for step = 1:n_vertices
best = 0;
best_key = [0 0];
for v = 1:n_vertices
if color(v) == 0
key = [numel(neighbor_colors(v, color, neighbors)), numel(neighbors{v})]; % ties: more neighbors first
larger = key(1) > best_key(1) || (key(1) == best_key(1) && key(2) > best_key(2));
if best == 0 || larger
best = v;
best_key = key;
end
end
end
used = neighbor_colors(best, color, neighbors);
c = 1;
while ismember(c, used) % the lowest color no neighbor has
c = c + 1;
end
color(best) = c;
end
fprintf("DSATUR uses %d colors\n", max(color))
function used = neighbor_colors(v, color, neighbors)
% The colors already given to the neighbors of v.
used = unique(color(neighbors{v}));
used = used(used > 0);
end
DSATUR uses 9 colors
DSATUR uses 9 colors on queen6_6 and 12 on queen8_8, against 7 and 9. Exact methods prove the chromatic number, but their effort grows very fast with the size of the graph. A simple exact search (DSATUR with backtracking) finds and proves 7 colors for queen6_6 in a fraction of a second, so for a graph this small it is the better tool. On queen8_8 the same search was still at 10 colors after 10 minutes. An integer programming model (one binary variable per vertex and color, solved with HiGHS) had 10 colors after 2 minutes and 9 after 5 minutes, still without a proof that 9 is optimal. Tabu search finds a coloring with 9 colors in 7 of 10 runs, and a run that fails takes about 20 seconds.
Results¶
Five algorithms, each with 10 seeded runs with the chromatic number of colors: 200 000 evaluations on queen6_6 and 1 000 000 on queen8_8. Each run stops at its first valid coloring. Tabu search, ILS and VNS use the recolor move (moves={"color": ["reset"]}). SA and GA use the native integer operators (space="native"), and SA a low temperature (initial_temp=2, final_temp=0.05, mutation_rate=0.01), because the number of conflicts changes by small whole numbers.
| Instance | Algorithm | Valid colorings | Mean conflicts | Mean evaluations to a valid coloring |
|---|---|---|---|---|
| queen6_6, 7 colors | TS | 8 of 10 | 0.2 | 51 814 |
| queen6_6, 7 colors | ILS | 2 of 10 | 0.9 | 66 046 |
| queen6_6, 7 colors | VNS | 1 of 10 | 1.5 | 197 271 |
| queen6_6, 7 colors | SA | 0 of 10 | 1.1 | none |
| queen6_6, 7 colors | GA | 0 of 10 | 4.1 | none |
| queen8_8, 9 colors | TS | 7 of 10 | 0.3 | 458 899 |
| queen8_8, 9 colors | ILS | 0 of 10 | 2.3 | none |
| queen8_8, 9 colors | VNS | 0 of 10 | 3.4 | none |
| queen8_8, 9 colors | SA | 0 of 10 | 2.2 | none |
| queen8_8, 9 colors | GA | 0 of 10 | 13.0 | none |
Only tabu search finds valid colorings reliably: 8 of 10 runs on queen6_6 and 7 of 10 on queen8_8. ILS, VNS and SA come close, with 0.9 to 3.4 conflicts left on average, but reach 0 in only 3 of their 60 runs. Near a valid coloring almost every move makes things worse. Tabu search still takes the least bad move, and its tabu list keeps it from walking straight back, so it can cross the plateaus between colorings. GA stays far away: color 3 in one parent and color 3 in another usually mean different groups of squares, so a crossover child mixes them and gets many conflicts. Tabu search here uses a tenure of 2 to 10 iterations. With the default of 7 to 20 it also succeeds in 8 and 7 of 10 runs, but needs about twice the evaluations on queen6_6 (97 174 on average).
How close does the generic tabu search get to TabuCol? It uses the same move and the same tabu rule, and it reaches the chromatic number on both graphs, but with more work. It evaluates every recoloring in each iteration (64 vertices times 8 other colors, 512 colorings on queen8_8), while a dedicated TabuCol code looks only at the vertices in conflict and updates the count of conflicts move by move, so it is much faster per iteration. With ypea the model takes about twenty lines, and it works for any graph.
Try it on your own graph¶
Replace the queen graph with your own list of edges, one pair of vertex numbers (from 0) per edge, and set k. Then:
- Start with the colors of a greedy rule such as DSATUR (
dsaturin the full script) and lower k one color at a time while a run still reaches 0 conflicts. - A run that stops above 0 does not prove that k colors are too few. Try other seeds or a larger budget first. The largest group of vertices that are all neighbors of each other (a clique, here one row of the board) is a lower bound: you never need to try fewer colors than that.
- Rules such as "this exam cannot go in slot 3" fit the same model: count each broken rule as one more conflict in the objective.
- On large graphs the neighborhood has n (k - 1) moves. Above 1000 moves tabu search evaluates a random sample of 1000 (
candidate_size) in each iteration.