Skip to main content

how to make absolut value in python model

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Jaromił Najman
    • 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

Post is closed for comments.