conditional constraint in Gurobi
AnsweredI am trying to model a conditional constraint in Guuobi python:
if a>= b then c == 1, otherwise c == 0
a and c are both model variables and c is binary
[assume a = I, b = safetystock, and c = X]
I have the following code based on https://support.gurobi.com/hc/en-us/articles/4414392016529-How-do-I-model-conditional-statements-in-Gurobi- but something is not correct as I cannot obtain the optimal answer. My code is:
Constraint4 = LP.addConstrs((I[months[a],item] >= safety_stock[item] + eps - M * (1 - X[months[a],item])
for item in items
for month in months
if month == months[a]), name="BigM1")
Constraint5 = LP.addConstrs((I[months[a],item] <= safety_stock[item] + M * X[months[a],item]
for item in items
for month in months
if month == months[a]), name="BigM2")
-
Official comment
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. -
Since your condition is \(a\geq b\), your have to use the \(\epsilon\) in your second big-M constraint, i.e.,
\[\begin{align*}
a &\geq b - M \cdot (1 - c)\\
a &\leq b - \epsilon + M \cdot c
\end{align*}\]You could alternatively try using Gurobi's indicator constraints
\[\begin{align*}
c = 1 &\rightarrow a \geq b\\
c = 0 &\rightarrow a \leq b - \epsilon
\end{align*}\]If none of the above works, could you please elaborate further what exactly does not work in your case?
Best regards,
Jaromił0 -
Thanks, this works.
0 -
Hi Oscar,
it is possible to define conditional statements like the one from this post using java?
Yes, is is possible. You can use the addGenConstrIndicator method. An example of its usage can be found at Genconstr.java.
In your particular case, you will have to model
\[\begin{align*}
z_{uv} &= PC_{uv} + PC_{vu}\\
w_{uv} &= PC_{uu} + PC_{vv} - 2\\
z_{uv} &= 1 \rightarrow T_{uv} = 0\\
w_{uv} &= 0 \rightarrow T_{uv} = \alpha\\
z_{uv}, &w_{uv} \in \{0,1\}
\end{align*}\]The reason for introducing the auxiliary binary variables \(z,w\) is that the addGenConstrIndicator method only accepts single optimization variables as input.
Best regards,
Jaromił0 -
Hi Oscar,
it is possible to use the variable T_{uv} as an upper bound for another variable?
You can define an inequality constraint \(\text{some variable} \leq T_{uv}\).
Best regards,
Jaromił0
Post is closed for comments.
Comments
5 comments