1

I am using Gurobi and in one part of my code I am defining a constraint which can accept two different value. for example 1 or 2. in the blow is a semi code of my implementation:

m = Model("mip1")
Edges = tuplelist([(1,2),(1,3),(3,4),(3,5),(3,6),(5,6),(6,7),
                   (1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),
                   (1,8),(2,8),(3,8),(4,8),(5,8),(6,8),(7,8),
                   (8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),
                   ])

x = m.addVars(Edges, lb=0.0, ub=1.0, name = "x")

m.setObjective(quicksum(x[w,s] for w,s in Edges), GRB.MAXIMIZE)

m.addConstr(quicksum(x.select(8,'*')) ==1 or 2 , "constraint1")

But I don't know how to define 'or' in constraint in Gurobi!

samie
  • 169
  • 15
  • I don't know gurobi, but the expression `quicksum(x.select(8,'*')) ==1 or 2` does not work how you think it works. Read [this](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value). – timgeb Aug 25 '18 at 12:52
  • @timgeb, I haven't done that, as I said this is a semi code !!! I want something like this – samie Aug 26 '18 at 17:39

1 Answers1

3

Let's add two binary variables y_0 and y_1:

y = m.addVars(2, vtype=GRB.BINARY, name="y")

Now you can add two indicator constraints:

# If y[0] == 1, then quicksum(x.select(8, '*')) == 2
m.addConstr((y[0] == 1) >> (quicksum(x.select(8, '*')) == 2))
# If y[1] == 1, then quicksum(x.select(8, '*')) == 3
m.addConstr((y[1] == 1) >> (quicksum(x.select(8, '*')) == 3))

Next you add the constraint

m.addConstr(y[0] + y[1] == 1)

This ensures that only one of these two variables can be 1 and thus the sum is either 2 or 3.

joni
  • 6,840
  • 2
  • 13
  • 20
  • couldn't the 2nd constraint be `(y[0] == 0) >> (quicksum(x.select(8, '*')) == 3)`, effectively making the 2nd binary variable and with it the last constraint unnecessary? Wouldn't work with more than 2 variables though.. – N4ppeL May 12 '20 at 13:10
  • Yeah, you're right. But the approach posted in the answer can be easily expanded for the case of more than two possible values the constraint should be equal to. – joni May 12 '20 at 15:28