7

Given are two integer variables $L_x \leq x \leq U_x$ and $L_y \leq y \leq U_y$. I'd like to formulate the constraint

$$ \text{If} \;\; x = k, \;\; \text{ then } \;\; y = c, $$

where $k$ and $c$ are given integer constants. Any help is highly appreciated!

hanhu
  • 81
  • 3
  • 1
    Just to share; If you are using a commercial solver, e.g. CPLEX: cplex.IfThen(cplex.Eq(x, k), cplex.Eq(y, c)); – alamaranka Sep 06 '21 at 10:29

3 Answers3

10

By introducing the binary helper variables $z_1,z_2,z_3,w_1,w_2,w_3$, you can use the constraints

$$ \begin{align} L_y z_1 + c z_2 + (c+1)z_3 &\leq y \leq (c-1)z_1 + c z_2 + U_y z_3, \tag{1} \\ L_x w_1 + k w_2 + (k+1)w_3 &\leq x \leq (k-1)w_1 + k w_2 + U_x w_3, \tag{2}\\ z_1 + z_2 + z_3 &= 1, \tag{3}\\ w_1 + w_2 + w_3 &= 1, \tag{4}\\ z_1 + z_3 &\leq w_1 + w_3 \tag{5}. \end{align} $$


Explanation: The constraint $x = k \implies y = c$ is equivalent to the contraposition $y \neq c \implies x \neq k$. Hence, we want to formulate

$$ y \leq c - 1 \;\vee\; y \geq c+1 \implies x \leq k-1 \; \vee \; x \geq k+1. \tag{*} $$

Then, (1) and (2) model the constraints

$$ \begin{align} z_1 = 1 &\implies y \leq c - 1, \\ z_2 = 1 &\implies y = c, \\ z_3 = 1 &\implies y \geq c + 1, \\ w_1 = 1 &\implies x \leq k - 1, \\ w_2 = 1 &\implies x = k, \\ w_3 = 1 &\implies x \geq k + 1, \\ \end{align} $$

while (3) and (4) guarantee that only one of the three cases for $x$ and $y$ can appear. Finally, (5) expresses constraint (*) by means of the binary helper variables.

joni
  • 1,572
  • 7
  • 14
5

In OPL CPLEX this is very easy to read and write.

Let me change https://github.com/AlexFleischerParis/zooopl/blob/master/zooifthen.mod to your exact question:

(nbBus40==6)=>(nbBus30==3);

means nbBus40==6 implies nbBus30==3

int nbKids=300;
float costBus40=500;
float costBus30=400;

dvar int+ nbBus40; dvar int+ nbBus30; minimize costBus40nbBus40 +nbBus30costBus30;

subject to { 40nbBus40+nbBus3030>=nbKids;

// with if nb buses 40 is 6 then nb buses 30 is 3

(nbBus40==6)=>(nbBus30==3);

}

Alex Fleischer
  • 4,000
  • 5
  • 11
3

Introduce binary variable $\delta$ and we can write following constraints $$ \begin{align} k \cdot \delta + L_{x} \cdot (1-\delta) &\le x \le k \cdot \delta + U_{x} \cdot (1-\delta) \\ c \cdot \delta + L_{y} \cdot (1-\delta) &\le y \le c \cdot \delta + U_{y} \cdot (1-\delta) \\ \end{align} $$ The way it works is when $\delta$ equals $1$, $x = k$ and $y = c$ and when $\delta$ equals 0, they take feasible bounds.

anjikum
  • 984
  • 4
  • 8