3.2 Changing Parameter values:#
In the tutorial slides, we saw that a parameter could be specified to be mutable. This tells Pyomo that the value of the parameter may change in the future, and allows the user to change the parameter value and resolve the problem without the need to rebuild the entire model each time. We will use this functionality to find a better solution to an earlier exercise. Considering again the knapsack problem, we would like to find when the wrench becomes valuable enough to be a part of the optimal solution. Below we create a Pyomo Parameter for the value of the items, make it mutable, and then write a loop that prints the solution for different wrench values.
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.item_benefit = pyo.Param( A, within=pyo.NonNegativeReals, initialize=b, mutable=True)
def obj_rule(m):
return sum( m.item_benefit[i]*m.x[i] for i in A )
model.obj = pyo.Objective(rule=obj_rule, sense = pyo.maximize )
def weight_rule(m):
return sum( w[i]*m.x[i] for i in A ) <= W_max
model.weight = pyo.Constraint(rule=weight_rule)
opt = pyo.SolverFactory('glpk')
for wrench_benefit in range(1,11):
model.item_benefit['wrench'] = wrench_benefit
result_obj = opt.solve(model)
print('Wrench benefit:', wrench_benefit, "x['wrench']:", pyo.value(model.x['wrench']))
Wrench benefit: 1 x['wrench']: 0.0
Wrench benefit: 2 x['wrench']: 0.0
Wrench benefit: 3 x['wrench']: 0.0
Wrench benefit: 4 x['wrench']: 0.0
Wrench benefit: 5 x['wrench']: 0.0
Wrench benefit: 6 x['wrench']: 0.0
Wrench benefit: 7 x['wrench']: 0.0
Wrench benefit: 8 x['wrench']: 1.0
Wrench benefit: 9 x['wrench']: 1.0
Wrench benefit: 10 x['wrench']: 1.0