forked from scipopt/PySCIPOpt
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathtest_knapsack.py
More file actions
51 lines (38 loc) · 1.38 KB
/
test_knapsack.py
File metadata and controls
51 lines (38 loc) · 1.38 KB
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
from pyscipopt import Model, quicksum
def test_knapsack():
# create solver instance
s = Model("Knapsack")
s.hideOutput()
# setting the objective sense to maximise
s.setMaximize()
# item weights
weights = [4, 2, 6, 3, 7, 5]
# item costs
costs = [7, 2, 5, 4, 3, 4]
assert len(weights) == len(costs)
# knapsack size
knapsackSize = 15
# adding the knapsack variables
knapsackVars = []
varNames = []
varBaseName = "Item"
for i in range(len(weights)):
varNames.append(varBaseName + "_" + str(i))
knapsackVars.append(s.addVar(varNames[i], vtype='I', obj=costs[i], ub=1.0))
# adding a linear constraint for the knapsack constraint
s.addCons(quicksum(w*v for (w, v) in zip(weights, knapsackVars)) <= knapsackSize)
# solve problem
s.optimize()
s.printStatistics()
# print solution
varSolutions = []
for i in range(len(weights)):
solValue = round(s.getVal(knapsackVars[i]))
varSolutions.append(solValue)
if solValue > 0:
print (varNames[i], "Times Selected:", solValue)
print ("\tIncluded Weight:", weights[i]*solValue, "\tItem Cost:", costs[i]*solValue)
includedWeight = sum([weights[i]*varSolutions[i] for i in range(len(weights))])
assert includedWeight > 0 and includedWeight <= knapsackSize
if __name__ == "__main__":
test_knapsack()