1.1 Knapsack example:#
Below is the knapsack problem. Which items are acquired in the optimal solution? What is the value of the selected items?
# knapsack.py
import pyomo.environ as pyo
A = ['hammer', 'wrench', 'screwdriver', 'towel']
b = {'hammer':8, 'wrench':3, 'screwdriver':6, 'towel':11}
w = {'hammer':5, 'wrench':7, 'screwdriver':4, 'towel':3}
W_max = 14
model = pyo.ConcreteModel()
model.x = pyo.Var( A, within=pyo.Binary )
model.obj = pyo.Objective(
expr = sum( b[i]*model.x[i] for i in A ),
sense = pyo.maximize )
model.weight_con = pyo.Constraint(
expr = sum( w[i]*model.x[i] for i in A ) <= W_max )
opt = pyo.SolverFactory('glpk')
opt_success = opt.solve(model)
model.pprint()
1 Var Declarations
x : Size=4, Index={hammer, wrench, screwdriver, towel}
Key : Lower : Value : Upper : Fixed : Stale : Domain
hammer : 0 : 1.0 : 1 : False : False : Binary
screwdriver : 0 : 1.0 : 1 : False : False : Binary
towel : 0 : 1.0 : 1 : False : False : Binary
wrench : 0 : 0.0 : 1 : False : False : Binary
1 Objective Declarations
obj : Size=1, Index=None, Active=True
Key : Active : Sense : Expression
None : True : maximize : 8*x[hammer] + 3*x[wrench] + 6*x[screwdriver] + 11*x[towel]
1 Constraint Declarations
weight_con : Size=1, Index=None, Active=True
Key : Lower : Body : Upper : Active
None : -Inf : 5*x[hammer] + 7*x[wrench] + 4*x[screwdriver] + 3*x[towel] : 14.0 : True
3 Declarations: x obj weight_con