简体   繁体   English

如何在 Pyomo 中创建 OR 约束?

[英]How to create an OR constraint in Pyomo?

I am trying to build a MIP model in Pyomo and having trouble creating an Or constraint.我正在尝试在 Pyomo 中构建 MIP 模型,但在创建 Or 约束时遇到问题。 An OR constraint r = or { x1 , ..., xn } states that the binary resultant variable r should be 1 if and only if any of the operand variables x1 , ..., xn is equal to 1. I failed no such function that can create OR constraint in Pyomo, so I use my own code OR 约束r ={ x1 , ..., xn } 声明二元结果变量r应该是 1 当且仅当任何操作数变量x1 , ..., xn等于 1。我没有失败可以在 Pyomo 中创建 OR 约束的函数,所以我使用我自己的代码

m = ConcreteModel()
m.r = Var(within=Binary)
m.x1 = Var(within=Binary)
m.x2 = Var(within=Binary)
m.or_constraint = Constraint(expr=m.r==min(sum(m.x1, m.x2), 1)

Then ran the code and got the error msg that variables m.x1 and m.x2 should be initialized.然后运行代码并得到应该初始化变量 m.x1 和 m.x2 的错误消息。 I initialized them with 1 and found that m.or_constraint degraded to force mr equal to 1. In other words, m.or_constraint just used m.x1 and m.x2 initial value to build the constraint and never updated in the process of solving the MIP problem.我用 1 初始化它们,发现 m.or_constraint 退化到强制 mr 等于 1。换句话说,m.or_constraint 只是使用 m.x1 和 m.x2 初始值来构建约束,并且在解决问题的过程中从未更新MIP 问题。

I tried different expressions in Pyomo to create this constraint, like call a rule function in the constraint definition.我在 Pyomo 中尝试了不同的表达式来创建这个约束,比如在约束定义中调用一个规则函数。 However, every time I got the same result.但是,每次我都得到相同的结果。

Could you direct me to create OR constraint in Pyomo?你能指导我在 Pyomo 中创建 OR 约束吗?

The relation关系

  y = x(1) or x(2) or ... or x(n)   ( same as y = max{x(i)} )
  y, x(i) ∈ {0,1}                   ( all binary variables  )    

can be formulated as a set of n+1 linear inequalities可以表述为一组 n+1 线性不等式

 y <= sum(i, x(i))
 y >= x(i)  for all i

It is also possible to write this as just two constraints:也可以将其写为两个约束:

 y <= sum(i,x(i))
 y >= sum(i,x(i))/n

The first version is tighter, however.然而,第一个版本更紧。 That is the one I typically use.这是我通常使用的一种。

Note: the first version is so tight that we even can relax y to be continuous between 0 and 1. Whether this is advantageous for the solver, requires a bit of experimentation.注意:第一个版本非常紧凑,我们甚至可以将 y 放宽到在 0 和 1 之间连续。这是否对求解器有利,需要进行一些实验。 For the second version, it is required that y is binary.对于第二个版本,要求 y 是二进制的。

Actually, there is another way to create a 'or' statement by using Pyomo with Binary(only for two constraints).实际上,还有另一种方法可以通过将 Pyomo 与 Binary 一起使用来创建“或”语句(仅适用于两个约束)。

Obj: Min(OF)=f(x)
s.t.  x<=A or x<=B

We can add a binary Number(Y) to form this model.M is a number which great enough(100000).我们可以添加一个二进制数(Y)来形成这个模型。M是一个足够大的数字(100000)。

   Obj: Min(OF)=f(x,y)
   s.t. X<= A+M*y
        X<=B+(1-Y)M
        Y=0,1
      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM