Writing constraints in Gurobi
AnsweredHow can one write a constraint using implication in Gurobi? For example, If variable y is 1 then it implies that variable x is also equal to 1.

You can use indicator constraints for this.
For example, in Python, this could be achieved as follows:
model.addConstr((y==1) >> (x==1))
0 
When i try the same :
model.addConstrs((y[(i,j)]==1 for (i,j) in arc_cost.keys()) >> (arc_cost[(i,j)] <= 5014 for (i,j) in arc_cost.keys()))
i get an error saying :
TypeError: unsupported operand type(s) for >>: 'generator' and 'generator'
0 
Hi Upasana,
You are getting this error because the expressions that you compare with >> are 'generator' expressions.
The following line of code should work:
model.addConstrs((y[(i,j)]==1) >> (arc_cost[(i,j)] <= 5014) for (i,j) in arc_cost.keys())
Best regards,
Elisabeth
0 
Hi Elizabeth,
Than you for your response. I had tried that before but i was getting this error:
TypeError: unsupported operand type(s) for =: 'NoneType' and 'float'
I guess the issue here is that y is a variable whereas arc_cost is a parameter. How can i get rid of the error?
Thanks,
Upasana
0 
Hi Upasana,
The issue comes indeed from the fact that arc_cost is a parameter.
Quoting the description of indicator constraints from Silke's link above:
INDICATOR constraints: An indicator constraint y = f > a^T x <= b states that if the binary indicator variable y is equal to f in a given solution, where f \in {0,1}, then the linear constraint a^T x <= b has to be satisfied.
So the second term of the operand >> has to be a constraint, but if arc_cost is a parameter (which takes a fixed value in advance), then the operation (arc_cost[(i,j)] <= 5014) will not return a constraint but a True or False value depending on whether the inequality is satisfied or not.
Best regards,
Elisabeth
0
Please sign in to leave a comment.
Comments
5 comments