How to express two LinExpr in equivalence in one constraint
AnsweredI have an issue that I cannot generate a constraint which describe two LinExpr to be of equal value. The code as follow.
There in the code, I would like to realize the constraints with the following meaning but the indicator or other functions cannot realize these constraints.

Thanks in advance!
import gurobipy as gp
from gurobipy import GRB
m = gp.Model("simplemodel")
num_I = 50
num_J = 50
samec = sm.addVars(num_J, num_J, vtype=GRB.BINARY, name="samec")
cluster = m.addVars(num_J, vtype=GRB.SEMIINT, lb=0, ub=num_I - 1, name="cluster")
self.m.addConstrs(((samec[j1, j2] == 1) >> (cluster[j1] == cluster[j2])
for j1 in range(num_J)
for j2 in range(num_J)), name="bc_samec.1")
-
I will omit the \(j\) indices for brevity. Please note that you define your cluster variables as semi-integer variables with a lower bound of \(0\). This means that your cluster variables are actually just integer variables and you can define their vtype as GRB.INTEGER.
You are on the right track. You already modeled the first half of the equivalence relation, namely
"if samec = 1 then cluster1 = cluster2"
Now, you "only" have to model the second half
"if cluster1 = cluster2 then samec1 = 1"
This is discussed in the stackexchange post In an integer program, how can I foce a binary variable to equal 1 if some condition holds?
You can introduce an auxiliary variable (and equality constraint) \(x = \text{cluster1} - \text{cluster2}\). Note that you have to explicitly define a negative lower bound for this variable \(\texttt{lb=-num_I+1}\). It's upper bound would be \(\texttt{ub = num_I -1}\).
You can then proceed to formulate the condition
"if x = 0 then samec = 1"
Inspired by the mentioned stackexchange post, you can formulate this condition via
\[\begin{align*}
(-num_I+1) \cdot y^- + 0\cdot y + 0.5\cdot y^+ &\leq x \leq -0.5\cdot y^- + 0\cdot y + (num_I-1)*y^+\\
y^- + y + y^+ &= 1\\
y^-, y^+, y &\in \{0,1\}
\end{align*}\]You can replace variable \(y\) by your samec variable in the above.
Note that there might be an easier way of formulating this specific condition for your model.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment