メインコンテンツへスキップ

How Gurobi implements judgment(if) and assignment(=)

回答済み

コメント

4件のコメント

  • Maliheh Aramon
    • Gurobi Staff

    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
  • Victor
    • Gurobi-versary
    • Conversationalist
    • First Question

    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
  • Maliheh Aramon
    • Gurobi Staff

    My bad, I am sorry. I was missing parentheses around the linear expression. I edited the implementation. 

    Thanks for noticing this.

    Maliheh

    0
  • Victor
    • Gurobi-versary
    • Conversationalist
    • First Question

    Hey Maliheh

    Thank you for your suggestion.

     

    Have a nice day,

    Victor

    0

サインインしてコメントを残してください。