Skip to main content

Absolute value modelling

Answered

Comments

3 comments

  • Peter Tawiah-Mensah
    • Gurobi-versary
    • First Comment
    • First Question

    The error is for constraints2 and constraints3. Sorry for not including that

    0
  • Riley Clement
    • Gurobi Staff

    Hi Peter,

    I think there are several things we can look at here:

    1) \(\texttt{y = np.zeros(n1)}\) : you will need these to be variables also, as their value depends on x variables.

    2) \(\texttt{for i in range(n1-1)}\) : you will want to use \(\texttt{for i in range(n1)}\) instead.  For example, run \(\texttt{print(range(3))}\) and look at the result.

    3) \(\texttt{objective = model.setObjective(sum, GRB.MINIMIZE)}\) this line is indented when it should not be and you are overwriting \(\texttt{objective}\) each time in the for-loop.

    4)  \(\texttt{if x[i] >= 0:}\) : you will not know the value of the variables until the model is optimized and so you cannot use them in this way.  You need to encode this "if .. then .." logic using mathematics.

    Below I have rewritten your code to help your understanding

    model = gp.Model()
    model.reset()

    m,n = A.shape

    x = model.addVars(range(n),lb=-1,ub=1)
    y = model.addVars(range(n),lb=0,ub=1)

    objective = model.setObjective(y.sum(), gp.GRB.MINIMIZE)

    for i in range(n):
        model.addConstr(y[i] >= x[i])
        model.addConstr(y[i] >= -x[i])

    for j in range(m):
        model.addConstr(gp.quicksum(A[j][i]*x[i] for i in range(n)) == b[j])

    model.optimize()


    However my instinct tells me that this formulation does not accurately model your problem, but I cannot address this without knowing your exact problem.

    I think it will be worth your time to start with some modeling basics, and this webinar is a good place to start.

    Let me know if you need any clarification on what I've written above, and good luck!  I hope you enjoy learning to use Gurobi.

    - Riley

    0
  • Peter Tawiah-Mensah
    • Gurobi-versary
    • First Comment
    • First Question

    Thanks a lot!

    This was extremely helpful.

    0

Please sign in to leave a comment.