如何在 Pyomo 中对变量设置简单的双域约束?



我正在使用 Pyomo 解决供应链优化问题,我需要对模型中的特定变量设置约束。约束是变量应该在集合 (0,1( 或 (200,到无穷大(内。但是,当我尝试设置该约束时,我收到一个TypeError,这是我的代码:

def rail_rule(model):
for route in routes:
if "rail" in route[0].lower():
dest = route[0]
dg = route[1]
sg = route[2]
site = route[3]
return model.x[dest, dg, sg, site]>=200 or model.x[dest, dg, sg, site]<=1
model.railconst = Constraint(rule = rail_rule)

运行它时出现此错误:

TypeError: Relational expression used in an unexpected Boolean context.
The inequality expression:
200.0  <=  x[RAIL - KENSINGTON,8,8,BROCKLESBY]
contains non-constant terms (variables) that were evaluated in an
unexpected Boolean context at
File '<ipython-input-168-901363ebc86f>', line 8:
return model.x[dest, dg, sg, site]>=200 or model.x[dest, dg, sg, site]<=1
Evaluating Pyomo variables in a Boolean context, e.g.
if expression <= 5:
is generally invalid.  If you want to obtain the Boolean value of the
expression based on the current variable values, explicitly evaluate the
expression using the value() function:
if value(expression) <= 5:
or
if value(expression <= 5):

所以我的理解是,我不能给 Pyomo 一个布尔表达式作为约束,但我对 Pyomo 很陌生,不太确定这是否是我的问题所在,或者我是否正确。

这个约束也可以在变量初始化中作为边界实现,但我找不到一种方法在 Pyomo 中的单个变量上设置两个边界。

谢谢!

有不同的方法可以处理这个问题:

(1( 使用二进制变量。假设你在 x 上有一个很好的上限,即 x ∈ [0, U]。然后制定约束

x ≤ 1 + (U-1) δ
x ≥ 200 δ
δ ∈ {0,1}  (binary variable)

这是最简单的方法。

(2(如果你在x上没有一个好的上限,你可以使用SOS1集合。(SOS1 表示类型 1 的特殊有序集(。假设 x,s1,s2 ≥ 0。

x ≤ 1 + s1
x ≥ 200 - s2
s1,s2 ∈ SOS1   (s1,s2 form a SOS1 set)

(3(使用析取编程。

最新更新