Search code examples
pythoncvxpy

In CVXPY, How to create an OR constraint like x == 1 OR x == 2?


In CVXPY, How to constract an 'OR' constraint like this ?

The constraint I am looking for is that x can be 1 or 2. The optimizer minimizes x and obtains the optimal x = 1.

For example, [x == 1 or x == 2] is invalid, and [x == 1, x == 2] means x == 1 AND x == 2 and does not work.

I am looking for a constraint that restricts x to be 1 or 2: x == 1 OR x == 2. Is it possible to create a CVXPY constraint like this?

import cvxpy as cp
x = cp.Variable(name='x')
## x is 1 or 2
## constraints = [ x...]  # x is 1 or 2; for example, 'constraints = [x == 1 or x == 2]' does not work

objective = cp.Minimize(x)
problem = cp.Problem(objective, constraints)
problem.solve()
print("x.value = " , x.value)

Solution

  • For the sake of generality here is code that restricts x values to 1,3,5:

    x = cp.Variable()
    z = cp.Variable(3, boolean=True)
    constraints = [cp.sum(z)==1, [1,3,5] @ z == x]
    

    In your case things could be simplified, for instance

    x = cp.Variable()
    z = cp.Variable(boolean=True)
    constraints = [x == 1 + z]
    

    or even

    x = cp.Variable(integer=True)
    constraints = [1 <= x, x <= 2]
    

    Of course you will need a mixed-integer solver, otherwise it is not possible. See the Mosek modeling cookbook for some math.