Skip to main content

Error in the objective functionsyn

Answered

Comments

4 comments

  • Mario Ruthmair
    • Gurobi Staff

    Hi Bushido,

    QuadExpr does not support MVars. In particular, if x is an MVar, then x[i,j] is a 0-dimensional MVar, not a Var object. You could fix this in several ways:

    • You keep the MVar but use the item() method to get a Var object, i.e.:
    qexpr.add(x[i,j].item() * x[i,k].item(), data[k,j])
    • You use classical Vars which makes sense if you do not exploit matrix operations on variables as in your code piece, i.e.
    x = model.addVars(a, b, vtype=GRB.BINARY, name = "x")

    Independent from that, note that QuadExpr.add() sets the coefficient in the second parameter.

    Best regards,
    Mario

    0
  • Bushido Pora
    • Gurobi-versary
    • First Comment
    • First Question

    Hello, 

    Thank you for your answer.

    Indeed using Vars directly was a solution however I now have a scalar expressed as a vector Matrix vector product in the objective and cant manage to make it work.

    a  = model.addMVar((3,5), vtype=GRB.BINARY)
    b = np.ones((5,5))
    qexpr = gp.QuadExpr(0)
    qexpr.add(a[0,:] @ b @ a[1,:].transpose())

    leads to :

    GurobiError: Invalid argument to QuadExpr addition

     

    0
  • Mario Ruthmair
    • Gurobi Staff

    This is similar to before: You are working with MVars but want to store an expression in a QuadExpr. You need to use either an MQuadExpr or work with Vars instead of MVars.

    MQuadExpr are temporary objects, there is no constructor. But you can create an expression by assignment:

    qexpr = a[0, :] @ b @ a[1, :].transpose()

    and then extend it via operators "+=".

    Depending on what you want to express in your objective function, there might be a one-liner based on matrix notation instead of summing up terms.

    0
  • Bushido Pora
    • Gurobi-versary
    • First Comment
    • First Question

    Thanks a lot.

    0

Please sign in to leave a comment.