Skip to main content

how to make absolut value in python model

Answered

Comments

1 comment

  • Jaromił Najman
    • Gurobi Staff Gurobi Staff

    You can use the addGenConstrAbs method to do that. You will have to formulate

    \[\begin{align*}
    z_{ij} &= X_i - X_j\\
    G_{ij} &= |z_{ij}|
    \end{align*}\]

    or in Python (pseudo code)

    # add a free auxiliary variable to the model
    z[i,j] = model.addVar(lb=-GRB.INFINITY, name="z"+str(i)+str(j))
    # add constraint z_ij = X_i - X_j
    model.addConstr(X[i] - X[j] == z[i,j], name="aux_constr_"+str(i)+str(j))
    # add constraint G_ij = |z_ij|
    model.addGenConstrAbs(G[i,j], z[i,j], "absconstr_"+str(i)+str(j))

    Note that it is necessary to introduce an auxiliary variable \(z_{ij}\) because the addGenConstrAbs method accepts only single optimization variables as input arguments. Moreover, it is necessary to define the lower bound of \(z_{ij}\) as \(-\infty\) because the default variable lower bound in Gurobi is \(0\).

    Best regards, 
    Jaromił

    0

Please sign in to leave a comment.