如何在 Pyomo 中对变量设置简单的两个域约束?
How to set up simple two domain constraint on a variable in Pyomo?
我正在使用 Pyomo 解决供应链优化问题,我需要对模型中的特定变量设置约束。约束是变量应该在集合 (0,1) 或 (200, to infinity) 内。但是,当我尝试设置该约束时出现类型错误,这是我的代码:
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) 使用析取编程。
我正在使用 Pyomo 解决供应链优化问题,我需要对模型中的特定变量设置约束。约束是变量应该在集合 (0,1) 或 (200, to infinity) 内。但是,当我尝试设置该约束时出现类型错误,这是我的代码:
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) 使用析取编程。