如何将 pyomo 约束转换为规则表达式?

How to translate a pyomo constraint to an rule expression?

我正在学习 pyomo 并使用玩具示例,更具体地说,我想了解如何使用 Pyomo 构建表达式约束规则并最终将它们转换为装饰器形式 - 我有以下工作模型产生预期的输出。

from pyomo.environ import *

L = {"s": 3, "j": 5, "f": 8}
B = {"s": 2, "j": 5, "f": 8}
C = {"s": 2, "j": 3, "f": 4}
P = {"s": 3, "j": 5, "f": 7}

limit_b = 325
limit_l = 400

model = ConcreteModel()

model.PACKAGES = Set(initialize=L.keys())

model.x = Var(model.PACKAGES, within=NonNegativeIntegers)

model.value = Objective(
    expr=sum((P[i] - C[i]) * model.x[i] for i in model.PACKAGES), sense=maximize
)

model.L_cst = Constraint(
    expr=sum(L[i] * model.x[i] for i in model.PACKAGES) <= limit_l
)

model.ballon_cst = Constraint(
    expr=sum(B[i] * model.x[i] for i in model.PACKAGES) <= limit_b
)

opt = SolverFactory("cbc")
results = opt.solve(model, tee=True)
model.pprint()
print("Objective value:", model.value())

从这段代码中,我想使用表达式和 pyomo Sets 但是我无法以正确的方式转换代码。

from pyomo.environ import *

model = ConcreteModel(name="Profit")

# Define sets
model.k = Set(initialize=["s", "j", "f"], doc="Types of package")
model.b = Set(initialize=[2, 5, 8], doc="B")
model.l = Set(initialize=[3, 5, 8], doc="L")
model.c = Set(initialize=[2, 3, 4], doc="C")
model.p = Set(initialize=[3, 5, 7], doc="P")


limit_B = 325
limit_L = 400

model.x = Var(model.k, within=NonNegativeIntegers)


def obj_rule(model):
    return sum((model.p[i] - model.c[i]) * model.x[i] for i in model.k)


model.object = Objective(rule=obj_rule, sense=maximize)


def max_L_per_month_rule(model):
    return sum(model.l[i] * model.x[i] for i in model.k) <= limit_L


model.max_L_per_month = Constraint(model, rule=max_L_per_month_rule)


def max_B_per_month_rule(model):
    return sum(model.b[i] * model.x[i] for i in model.k) <= limit_B


model.max_B_per_month = Constraint(
    model, rule=max_B_per_month_rule
)

opt = SolverFactory("cbc")
results = opt.solve(model, tee=True)
model.pprint()
print("Objective value:", model.value())

谁能帮我解释一下过程?

约束中的问题是您将模型作为第一个参数传递。 Constraint 组件中的位置参数被假定为索引集。您的约束未编入索引,因此使用规则声明它的正确方法是:

model.max_L_per_month = Constraint(rule=max_L_per_month_rule)

我建议查看 online documentation for examples of declaring constraints using rules and the Pyomo workshop slides 以了解装饰器符号的概述