Skip to main content

Trouble in implementing `if` conditionals in Gurobi Python Objective Function




  • Maliheh Aramon
    Gurobi Staff Gurobi Staff

    Hi Somreeta, 

    If \(\mbox{erf}(z)\) is a linear function of \(z\) decision variable, you can define an auxiliary binary variable \(x\) where:

    \[\mbox{if}~~ z \leq 0 \rightarrow x = 1\] \[\mbox{if}~~ z \geq 1 \rightarrow x = 0\]

    The objective function can then be implemented as \(U = x \big(1-\mbox{erf}(z)\big) + (1-x) \mbox{erf}(z)\) which is quadratic. 

    Using contraposition, the conditional statements are equivalent to:

    \[\mbox{if}~~ x \neq 1  \rightarrow z \nleq 0 \mbox{, which implies: if} ~~ x = 0  \rightarrow z \geq 1\]

    \[\mbox{if}~~ x \neq 0  \rightarrow z \ngeq 1 \mbox{, which implies: if} ~~ x = 1  \rightarrow z \leq 0\]

    These constraints can be implemented using the Gurobi's API for indicator constraints.

    If \(\mbox{erf}(z)\) is a higher order function of \(z\), you can model it as a piecewise-linear objective. For more details, please check out the documentation on piecewise-linear objectives and the python example

    Best regards,


  • Somreeta Pramanik
    First Comment
    First Question

    Thank you for the help. 

    I have a related question. As addGenConstrPow accepts a constant exponent, it does not accept k, which is an iterator variable.

    Is there an alternative way of doing it?

    Following is the code snippet,

    myAuxVar= m.addVar(vtype=GRB.CONTINUOUS, name="myAuxVar")
    m.addConstr(myAuxVar==Lambda * w)
    powconstr1= m.addGenConstrPow(myAuxVar, v, k, "pow2", "FuncPieces=1000")

    where k is an iterator variable

    I receive the following error message- Encountered an attribute error




Please sign in to leave a comment.