# How to use condition in cplex?

I want to use conditions to my variable.

dvar boolean x[I][J][K][L]
dvar in h[i]


my code is

forall(i in IP, j in J)
sum(k in K, l in L)
x[i][j][k][l] - 7 == h[i];


The following condition must be satisfied:

if x[i][j][k][l] - 7 <=0, h[i] must be zero.
if x[i][j][k][l] - 7 >=0, h[i] must be calculated


How do we formulate it in the integer programming formulation on CPLEX?

• Are you missing a sum in each of your two “if” conditions? Commented Apr 29, 2022 at 12:51

In OPL CPLEX you can use if then logical constraints.

For instance

range I=1..2;
range J=1..3;
range K=1..4;
range L=1..5;

dvar boolean x[I][J][K][L];
dvar int h[I];

subject to
{

forall(i in I, j in J,k in K,l in L)
{
(x[i][j][k][l] - 7 >=0)
=> (sum(k2 in K, l2 in L) (x[i][j][k2][l2] - 7) == h[i]);

(x[i][j][k][l] - 7 <=0)
=> (0 == h[i]);
}
}


works

• thank u so much!
– MIN
Commented May 27, 2022 at 6:57

It looks like you want to enforce $$h_i = \max(\sum_{k,l} x_{i,j,k,l}-7, 0)$$. Some solvers will automatically linearize this. Depending on where $$h_i$$ appears elsewhere in the problem, you might be able to get by with enforcing instead $$h_i \ge \max(\sum_{k,l} x_{i,j,k,l}-7, 0),$$ which you can do without introducing new variables, by imposing \begin{align} h_i &\ge \sum_{k,l} x_{i,j,k,l}-7 \tag1\\ h_i &\ge 0 \tag2 \end{align} If necessary, you can also enforce $$h_i \le \max(\sum_{k,l} x_{i,j,k,l}-7, 0)$$ by introducing binary variable $$\delta_{i,j}$$ (as in the proposed formulation by @anjikum) and imposing \begin{align} h_i &\le \sum_{k,l} x_{i,j,k,l} - 7\delta_{i,j} \tag3\\ h_i &\le (M_{i,j}-7)\delta_{i,j} \tag4 \end{align} Here, $$M_{i,j}$$ is a small constant upper bound on $$\sum_{k,l} x_{i,j,k,l}$$.

• thank u so much!
– MIN
Commented May 27, 2022 at 6:57

Below is one way to formulate it. Need to introduce another binary variable ($$\delta_{i,j}$$). $$M$$ depends on bounds of $$h_{i}$$ and $$x_{i,j,k,l}$$ : \begin{align} \sum_{k,l} x_{i,j,k,l}-7 &\le h_{i} + M \cdot (1-\delta_{i,j})\\ \sum_{k,l} x_{i,j,k,l}-7 &\ge h_{i} - M \cdot (1-\delta_{i,j}) \\ \sum_{k,l} x_{i,j,k,l}-7 &\le M \cdot \delta_{i,j}\\ \sum_{k,l} x_{i,j,k,l}-7 &\ge -M \cdot (1-\delta_{i,j}) \end{align} Regarding CPLEX code, you need to add these constraints similar to declaration in your code (provided in question).

• This formulation doesn’t enforce the desired behavior when the sum is $7$. In that case, $\delta_{i,j}$ can take either value, and $\delta_{i,j}=0$ allows $h_i$ to be free. Commented Apr 29, 2022 at 13:07
• thank u so much!
– MIN
Commented May 27, 2022 at 6:57