exact gurobi solver for chromatic number of coloring problem [error in the objective]
I'm trying to solve the coloring problem by using gurobi in a lp setting. However, I do something wrong, but don't what exactly.
`!pip install gurobipy'
import networkx as nx
import gurobipy as gp
from gurobipy import *
import networkx as nx
# create test graph
n = 70
p = 0.6
G = nx.erdos_renyi_graph(n, p)
nx.draw(G, with_labels = True)
# compute chromatic number -- ILP solve
m = gp.Model('chrom_num', env =e)
# get maximum number of variables necessary
k = max(dict(nx.degree(G)).values()) + 1
TEST= range(k)
# create k binary variables, y_0 ... y_{k-1} to indicate whether color k is used
y = []
for j in range(k):
y.append(m.addVar(vtype=gp.GRB.BINARY, name='y_%d' % j, obj=1))
# create n * k binary variables, x_{l,j} that is 1 if node l is colored with j
x = []
for l in range(n):
x.append([])
for j in range(k):
x[-1].append(m.addVar(vtype=gp.GRB.BINARY, name='x_%d_%d' % (l, j), obj=0))
# objective function is minimize colors used --> sum of y_0 ... y_{k-1}
m.setObjective(gp.quicksum(y[j] for j in TEST), gp.GRB.MINIMIZE)
m.update()
# add constraint -- each node gets exactly one color (sum of colors used is 1)
for u in range(n):
m.addConstr(gp.quicksum(x[u]) == 1, name='NC_%d')
# add constraint -- keep track of colors used (y_j is set high if any time j is used)
for l in range(n):
for j in range(k):
m.addConstr(x[u][j] <= y[j], name='SH_%d_%d')
# add constraint -- adjacent nodes have different colors
for u in range(n):
for v in G[u]:
if v > u:
for j in range(k):
m.addConstr(x[u][j] + x[v][j] <= 1, name='ADJ_%d_%d_COL_%d')
# update model, solve, return the chromatic number
m.update()
m.optimize()
chrom_num = m.objVal
Comments
Post a Comment