【发布时间】:2019-02-02 16:55:17
【问题描述】:
有没有办法在求解器运行时更改约束值?
基本上,我有一个取决于变量值的约束。问题是约束是根据变量的初始值评估的,但不会随着变量的变化而更新。
这是一个简单的例子:
from pyomo.environ import *
from pyomo.opt import SolverFactory
import numpy as np
# Setup
model = ConcreteModel()
model.A = Set(initialize = [0,1,2])
model.B = Set(initialize = [0,1,2])
model.x = Var(model.A, model.B, initialize=0)
# A constraint that I'd like to keep updating, based on the value of x
def changing_constraint_rule(model, a):
x_values = list((model.x[a, b].value for b in model.B))
if np.max(x_values) == 0:
return Constraint.Skip
else:
# Not really important what goes here, just as long as it updates the constraint list
if a == 1 : return sum(model.x[a,b] for b in model.B) == 0
else: return sum(model.x[a,b] for b in model.B) == 1
model.changing_constraint = Constraint(model.A, rule = changing_constraint_rule)
# Another constraint that changes the value of x
def bounding_constraint_rule(model, a):
return sum(model.x[a, b] for b in model.B) == 1
model.bounding_constraint = Constraint(
model.A,
rule = bounding_constraint_rule)
# Some objective function
def obj_rule(model):
return(sum(model.x[a,b] for a in model.A for b in model.B))
model.objective = Objective(rule=obj_rule)
# Results
opt = SolverFactory("glpk")
results = opt.solve(model)
results.write()
model.x.display()
如果我运行model.changing_constraint.pprint(),我可以看到没有进行任何约束,因为变量model.x 的初始值设置为0。
如果在求解时无法更改约束值,我该如何以不同的方式表述这个问题以实现我想要的?我已经阅读了this other post,但无法从说明中弄清楚。
【问题讨论】:
标签: pyomo