Skip to main content

how to add a max constr? General expressions can only be equal to a single var

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three 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 why not try our AI Gurobot?.
  • Jaromił Najman
    • Gurobi Staff

    Hi Scott,

    The addGenConstrMax function only accepts a list of variable objects as its second argument. You tried to provide a list of QuadExpr objects.

    In order to work with Gurobi's \(\max\) function, you will have to introduce auxiliary variables and construct the appropriate variable list which you then provide to the addGenConstrMax function. Here is a simplified example

    import gurobipy as gp
    from gurobipy import GRB

    m = gp.Model('test')

    N = 2
    P1 = m.addVars(1, N, vtype=GRB.CONTINUOUS, name='P1')
    x = m.addVars(N, N, vtype=GRB.CONTINUOUS, name='x')
    p = m.addVars(1, N, vtype=GRB.CONTINUOUS, name='p')
    # auxiliary variables for the multiplications of p*x
    aux_mult = m.addVars(N,N, vtype=GRB.CONTINUOUS, name='aux_mult')

    for b in range(N):
    for j in range(N):
    # add auxiliary constraint for every multiplication p*x
    m.addConstr(aux_mult[b,j] == p[0,j]*x[b,j], name='aux_mult_constr_'+str(b)+'_'+str(j))

    # get all corresponding auxiliary variables into a list
    maxVarsList = [aux_mult[b,j] for j in range(N)]
    # add constraint P[0,b] == max(aux_mult[b,0], aux_mult[b,1], ...)
    m.addGenConstrMax(P1[0,b], maxVarsList, name='maxconstr_'+str(b))

    # write LP file to analyze whether the model looks as expected
    m.write("myLP.lp")

    Best regards,
    Jaromił

    0

Post is closed for comments.