How Gurobi implements judgment(if) and assignment(=)
回答済みHey everyone,
I have a question described as follows.
I want to realize the following code.
But in Gurobi, I cannot find any grammar that can implements the following function.
flag_chosedPoint_each_set is a 2D numpy and its value can be 0 or 1.
Could you give me a support?
x = self.model.addVars(len(A), vtype=GRB.BINARY, name='x')
for i in range(Len(B)): # count the elements
t = [x[j] * flag_chosedPoint_each_set[j][i] for j in range(len(A))]
t = sum(t)
if t > 0:
selected[i]=1
else:
selected [i]= 0
-
Hi Victor,
It seems to me that you would like to implement the following two constraints:
\[\mbox{if}~~ \sum_j c_{ij} x_j > 0 \rightarrow s_i = 1, ~~\forall i\]
\[\mbox{if}~~ \sum_j c_{ij} x_j \leq 0 \rightarrow s_i = 0, ~~\forall i\]
In Gurobi Python API, you can use the Model.addGenConstrIndicator() method to implement these indicator constraints. Since the indicator variable in this method should be a binary variable and not a linear expression, you can implement their equivalent contrapositives:
\[\mbox{if}~~ s_i \neq 1 \rightarrow \sum_j c_{ij} x_j \ngtr 0, ~~\forall i ~~\mbox{which equals} ~~ \mbox{if}~~ s_i = 0 \rightarrow \sum_j c_{ij} x_j \leq 0, ~~\forall i \]
\[\mbox{if}~~ s_i \neq 0 \rightarrow \sum_j c_{ij} x_j \nleq 0, ~~\forall i ~~\mbox{which equals} ~~ \mbox{if}~~ s_i = 1 \rightarrow \sum_j c_{ij} x_j \geq 1, ~~\forall i \]
The last inequality \(\sum_j c_{ij} x_j \geq 1\) holds true because all \(c_{ij}\) coefficients and \(x_j\) variables are either 0 or 1.
See an example implementation below:
n, m = 10, 20
c = np.random.randint(low=0, high=2, size=(n, m))
model = gp.Model()
x = model.addVars(m, vtype=GRB.BINARY, name="x")
s = model.addVars(n, vtype=GRB.BINARY, name="s")
for i in range(n):
expr = gp.quicksum(c[i][j] * x[j] for j in range(m))
model.addGenConstrIndicator(s[i], 0, expr <= 0, name=f"ind0_{i}")
model.addGenConstrIndicator(s[i], 1, expr >= 1, name=f"ind1_{i}")
# Instead of using addGenConstrIndicator, you can use the overloaded form too
# model.addConstr((s[i] == 0) >> (expr <= 0))
# model.addConstr((s[i] == 1) >> (expr >= 1))Best regards,
Maliheh
0 -
Hey Maliheh @Maliheh Aramon ,
Thank you for your reply. The first method work.
But the 2nd doesn't works and give me feedback:
gurobipy.GurobiError: Constraint comparison not implemented
Thank you again.
Victor
0 -
My bad, I am sorry. I was missing parentheses around the linear expression. I edited the implementation.
Thanks for noticing this.
Maliheh
0 -
Hey Maliheh,
Thank you for your suggestion.
Have a nice day,
Victor
0
サインインしてコメントを残してください。
コメント
4件のコメント