PySCIPOpt  5.1.1
Python Interface for the SCIP Optimization Suite
mkp.py
Go to the documentation of this file.
1 
3 """
4 Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
5 """
6 from pyscipopt import Model, quicksum, multidict
7 
8 
9 def mkp(I, J, v, a, b):
10  """mkp -- model for solving the multi-constrained knapsack
11  Parameters:
12  - I: set of dimensions
13  - J: set of items
14  - v[j]: value of item j
15  - a[i,j]: weight of item j on dimension i
16  - b[i]: capacity of knapsack on dimension i
17  Returns a model, ready to be solved.
18  """
19  model = Model("mkp")
20 
21  # Create Variables
22  x = {}
23  for j in J:
24  x[j] = model.addVar(vtype="B", name="x(%s)" % j)
25 
26  # Create constraints
27  for i in I:
28  model.addCons(quicksum(a[i, j] * x[j] for j in J) <= b[i], "Capacity(%s)" % i)
29 
30  # Objective
31  model.setObjective(quicksum(v[j] * x[j] for j in J), "maximize")
32  model.data = x
33 
34  return model
35 
36 
37 def example():
38  """creates example data set"""
39  J, v = multidict({1: 16, 2: 19, 3: 23, 4: 28})
40  a = {(1, 1): 2, (1, 2): 3, (1, 3): 4, (1, 4): 5,
41  (2, 1): 3000, (2, 2): 3500, (2, 3): 5100, (2, 4): 7200,
42  }
43  I, b = multidict({1: 7, 2: 10000})
44  return I, J, v, a, b
45 
46 
47 if __name__ == "__main__":
48  I, J, v, a, b = example()
49  model = mkp(I, J, v, a, b)
50  x = model.data
51  model.optimize()
52 
53  print("Optimal value:", model.getObjVal())
54 
55  EPS = 1.e-6
56 
57  for i in x:
58  v = x[i]
59  if model.getVal(v) > EPS:
60  print(v.name, "=", model.getVal(v))
pyscipopt.expr.quicksum
def quicksum(termlist)
Definition: expr.pxi:357
mkp
Definition: mkp.py:1
mkp.example
def example()
Definition: mkp.py:37
pyscipopt.Multidict.multidict
def multidict(D)
Definition: Multidict.py:3
mkp.mkp
def mkp(I, J, v, a, b)
Definition: mkp.py:9