Reputation: 191
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!
Upvotes: 3
Views: 2701
Reputation: 7157
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.
Upvotes: 4