Zekun Yang
Zekun Yang

Reputation: 11

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. 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

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. I initialized them with 1 and found that m.or_constraint degraded to force m.r 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.

I tried different expressions in Pyomo to create this constraint, like call a rule function in the constraint definition. However, every time I got the same result.

Could you direct me to create OR constraint in Pyomo?

Upvotes: 1

Views: 1511

Answers (2)

Erwin Kalvelagen
Erwin Kalvelagen

Reputation: 16714

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

 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. For the second version, it is required that y is binary.

Upvotes: 3

ViviAaron
ViviAaron

Reputation: 108

Actually, there is another way to create a 'or' statement by using Pyomo with Binary(only for two constraints).

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).

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

Upvotes: 0

Related Questions