from pyomo.environ import (ConcreteModel, Set, Param, Var, Constraint,
Objective, maximize)
from pyomo.opt import SolverFactory
# Data
T = [1, 2]
C_el = [20, 20]
P_inst = [100, 100]
P_inst_new = [200, 200]
# Model
m = ConcreteModel()
# Sets
m.T = Set(initialize=T)
# Variables
m.P = Var(m.T)
# Params
m.C_el = Param(m.T, initialize=dict(zip(T, C_el)))
m.P_inst = Param(m.T, initialize=dict(zip(T, P_inst)), mutable=True)
def inst_rule(model, t):
return(m.P[t] <= m.P_inst[t])
m.inst = Constraint(m.T, rule=inst_rule)
# Objective rules
def obj_rule(model):
return(sum(m.C_el[t]*m.P[t] for t in m.T))
m.profit = Objective(sense=maximize, rule=obj_rule)
# # ### FIRST WAY: Change upper bound as "real" upper bound
#
# # Change bound
# # This could of course be realized when instantiating the variable
# # but it is realized here manually to compare both ways
# for t in range(0, max(T)):
# m.P[t+1].setlb(0)
# m.P[t+1].setub(P_inst[t])
# m.inst.reconstruct()
#
# # Print and write model
# m.pprint()
# m.write('model.lp')
#
# # Change bound
# for t in range(0, max(T)):
# m.P[t+1].setub(P_inst_new[t])
# m.inst.reconstruct()
#
# # Print and write new model
# m.pprint()
# m.write('model_new.lp')
### SECOND WAY: Change upper bound as mutable parameter
# Print and write model
m.pprint()
m.write('model.lp')
# Change bound
for t in range(0, max(T)):
m.P_inst[t+1] = P_inst_new[t]
# Print and write new model
m.pprint()
m.write('model_new.lp')
import pyomo.environ as pe
m = pe.ConcreteModel()
m.x = pe.Var()
m.y = pe.Var()
m.z = pe.Var()
m.xl = pe.Param(initialize=-1.0, mutable=True)
m.xu = pe.Param(initialize=1.0, mutable=True)
m.yl = pe.Param(initialize=-1.0, mutable=True)
m.yu = pe.Param(initialize=1.0, mutable=True)
m.x.setlb(m.xl)
m.x.setub(m.xu)
m.y.setlb(m.yl)
m.y.setub(m.yu)
m.objective = pe.Objective(expr=m.z)
m.c1 = pe.Constraint(expr=m.z >= m.xl * m.y + m.x * m.yl - m.xl * m.yl)
m.c2 = pe.Constraint(expr=m.z >= m.xu * m.y + m.x * m.yu - m.xu * m.yu)
opt = pe.SolverFactory('gurobi')
res = opt.solve(m)
print(pe.value(m.z)) # -1
m.xl.value = -0.5
m.xu.value = 0.5
m.yl.value = 0.5
m.yu.value = 1.0
res = opt.solve(m)
print(pe.value(m.z)) # -0.5
1. I don't completely understand your example because changing the bounds on a variable will not update any constraints.
2. I would simply use a mutable param anywhere it is needed and update the value of that mutable param. I don't think there is a faster way to do this.
3. I put together a minimal example that does what I think you are trying to do.
4. If you are really concerned about performance with repeated solves (and you are using either gurobi or cplex), you may want to consider the persistent solver interfaces (https://pyomo.readthedocs.io/en/latest/advanced_topics/persistent_solvers.html). These do add complexity, but they can significantly improve performance.