Skip to main content

Writing constraints in Gurobi

Answered

Comments

6 comments

  • Official comment
    Simranjit Kaur
    Gurobi Staff Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?.
  • Silke Horn
    Gurobi Staff Gurobi Staff

    You can use indicator constraints for this.

    For example, in Python, this could be achieved as follows:

    model.addConstr((y==1) >> (x==1))
    0
  • Upasana Chakraborty
    Gurobi-versary
    Conversationalist
    First Question

    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
  • Elisabeth Rodríguez Heck
    Gurobi Staff Gurobi Staff

    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
  • Upasana Chakraborty
    Gurobi-versary
    Conversationalist
    First Question

    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
  • Elisabeth Rodríguez Heck
    Gurobi Staff Gurobi Staff

    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

Post is closed for comments.