提问者:小点点

Pyomo中基于变量值的约束变更


有没有一种方法可以在求解器运行时更改约束的值?

基本上,我有一个依赖于变量值的约束。问题是约束是基于变量的初始值计算的,但是不会随着变量的变化而更新。

这里有一个简单的例子:

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()

如果我运行模型。更改_约束。pprint()我可以看到,由于变量模型的初始值不正确,因此没有进行任何约束。x已设置为0。

如果在求解时无法更改约束值,我如何以不同的方式表述此问题以实现我所寻找的目标?我读过另一篇文章,但从说明书上看不出来。


共1个答案

匿名用户

我在@Gabe的另一个问题中给了你同样的答案:

在规则内部使用的任何if逻辑都不应涉及变量的值(除非它基于变量的初始值,在这种情况下,只要在返回的主表达式之外使用变量,就将变量包装在value()中)。

例如:模型。x[a,b]。值应为型号。x[a,b]。value()

但这仍然可能不会给你你正在寻找的解决方案。