Skip to main content

How to add such an indicator constraints? if a=b then c<d  else c>d

Answered

Comments

4 comments

  • Official comment
    Simranjit Kaur
    • 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 try Gurobot, our chatbot interface offering instant, expert-level support.
  • David Torres Sanchez
    • Gurobi Staff

    Hi Yu,

    For this purpose, you need several auxiliary variables. Edit: I missed one side of the implication.

    1. A continuous variable to represent the difference \(\texttt{y} =\texttt{a}-\texttt{b}\);
    2. A non-negative variable to represent the absolute value of this difference: \(\texttt{yabs} = |y|\);
    3. And a binary variable to indicate whether \(\texttt{yabs}>=0\).

    In Python, using addGenConstrIndicator (overloaded version) you can write

    from gurobipy import *

    m = Model()

    a = m.addVar(name="a", obj=10)
    b = m.addVar(name="b", obj=1)
    c = m.addVar(name="c", obj=1)
    d = m.addVar(name="d", obj=10)

    # Some auxiliary variables
    x = m.addVar(vtype=GRB.BINARY, name="x")
    y = m.addVar(name="y")  # difference a-b
    yabs = m.addVar(lb=0, name="yabs")  # absolute difference

    eps = 1.0e-3
    m.addConstr(y == a - b)
    m.addConstr(yabs == abs_(y))
    m.addConstr((x == 1) >> (yabs == 0))
    m.addConstr((x == 0) >> (yabs >= eps))

    m.addConstr((x == 1) >> (c <= d - eps))
    m.addConstr((x == 0) >> (d <= c - eps))

    m.optimize()

    Where the \(\texttt{eps}\) is a small number used to write strict inequalities.

    Cheers, 
    David

    0
  • Yu yue
    • Gurobi-versary
    • Conversationalist
    • First Question

    Hi David,

    Thank you very much,it worked!

    I have one more question, if a is not a decision variable(a∈[1,10]), b is a decision variable.

    Can it still be solved in this way?

    Best regards,

    Yu

    0
  • David Torres Sanchez
    • Gurobi Staff

    Hi Yu,

    This also works! Just replace \(\texttt{a}\) with your value.
     
    Best,
    David

    0

Post is closed for comments.