【问题标题】:Change constraints based on variable value in Pyomo根据 Pyomo 中的变量值更改约束
【发布时间】: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


    【解决方案1】:

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

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

    例如: model.x[a, b].value 应该是 model.x[a, b].value()

    但这仍然可能无法为您提供所需的解决方案。

    【讨论】:

    • 唉,我认为不会。还是谢谢你的回复
    猜你喜欢
    • 2021-09-12
    • 2022-11-27
    • 2018-07-09
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2021-03-06
    相关资源
    最近更新 更多