Search code examples
pythonmodelgurobiobjective-function

Quadratic objective function in Gurobi


I am building a model with a quadratic objective function. But I am having trouble on how to code it.

v is a matrix of coefficients.

This is the original objective:

 x = m.addMVar(shape=n, vtype=GRB.BINARY, name="x")  # binary var
 m.setObjective(v @ x, GRB.MAXIMIZE)

And I need to transform it in : max [(v*x)^2] I tried this, but it gives an error:

 x = m.addMVar(shape=n, vtype=GRB.BINARY, name="x")  # binary var
 m.setObjective(x @ v @ x, GRB.MAXIMIZE)

Could someone help me with this? Thank you!


Solution

  • x @ v @ x requires v to be a matrix (2-dimensional numpy.ndarray); my guess is that v is a vector (1-dimensional numpy.ndarray). If you really mean the expression x1^2 * v1 + ... + xn^2 * vn, then you can write:

    m.setObjective(x @ np.diag(v) @ x, GRB.MAXIMIZE)