PySCIPOpt  4.3.0
Python Interface for the SCIP Optimization Suite
gcp_fixed_k.py
Go to the documentation of this file.
1 
3 """
4 Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
5 """
6 
7 from pyscipopt import Model, quicksum, multidict
8 
9 def gcp_fixed_k(V,E,K):
10  """gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph
11  Parameters:
12  - V: set/list of nodes in the graph
13  - E: set/list of edges in the graph
14  - K: number of colors to be used
15  Returns a model, ready to be solved.
16  """
17  model = Model("gcp - fixed k")
18 
19  x,z = {},{}
20  for i in V:
21  for k in range(K):
22  x[i,k] = model.addVar(vtype="B", name="x(%s,%s)"%(i,k))
23  for (i,j) in E:
24  z[i,j] = model.addVar(vtype="B", name="z(%s,%s)"%(i,j))
25 
26  for i in V:
27  model.addCons(quicksum(x[i,k] for k in range(K)) == 1, "AssignColor(%s)" % i)
28 
29  for (i,j) in E:
30  for k in range(K):
31  model.addCons(x[i,k] + x[j,k] <= 1 + z[i,j], "BadEdge(%s,%s,%s)"%(i,j,k))
32 
33  model.setObjective(quicksum(z[i,j] for (i,j) in E), "minimize")
34 
35  model.data = x,z
36  return model
37 
38 
39 def solve_gcp(V,E):
40  """solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
41  Parameters:
42  - V: set/list of nodes in the graph
43  - E: set/list of edges in the graph
44  Returns tuple with number of colors used, and dictionary mapping colors to vertices
45  """
46  LB = 0
47  UB = len(V)
48  color = {}
49  while UB-LB > 1:
50  K = int((UB+LB) / 2)
51  gcp = gcp_fixed_k(V,E,K)
52  # gcp.Params.OutputFlag = 0 # silent mode
53  #gcp.Params.Cutoff = .1
54  gcp.setObjlimit(0.1)
55  gcp.optimize()
56  status = gcp.getStatus()
57  if status == "optimal":
58  x,z = gcp.data
59  for i in V:
60  for k in range(K):
61  if gcp.getVal(x[i,k]) > 0.5:
62  color[i] = k
63  break
64  # else:
65  # raise "undefined color for", i
66  UB = K
67  else:
68  LB = K
69 
70  return UB,color
71 
72 
73 import random
74 def make_data(n,prob):
75  """make_data: prepare data for a random graph
76  Parameters:
77  - n: number of vertices
78  - prob: probability of existence of an edge, for each pair of vertices
79  Returns a tuple with a list of vertices and a list edges.
80  """
81  V = range(1,n+1)
82  E = [(i,j) for i in V for j in V if i < j and random.random() < prob]
83  return V,E
84 
85 
86 if __name__ == "__main__":
87  random.seed(1)
88  V,E = make_data(75,.25)
89 
90  K,color = solve_gcp(V,E)
91  print("minimum number of colors:",K)
92  print("solution:",color)
gcp_fixed_k.make_data
def make_data(n, prob)
Definition: gcp_fixed_k.py:74
pyscipopt.expr.quicksum
def quicksum(termlist)
Definition: expr.pxi:357
gcp_fixed_k.gcp_fixed_k
def gcp_fixed_k(V, E, K)
Definition: gcp_fixed_k.py:9
gcp_fixed_k.solve_gcp
def solve_gcp(V, E)
Definition: gcp_fixed_k.py:39
gcp_fixed_k
Definition: gcp_fixed_k.py:1