I'd like to set up an objective function in Gurobi to minimize x^2 + y^2
. I've done my best to provide an example below:
import gurobipy as gbPy
model = gbPy.Model()
A = [1, 2, 3, 4, 5]
B = [1, 2, 3]
x = model.addVars(5, lb = 0)
y = model.addVars(3, lb = 0)
for i in range(len(x)):
model.addConstr(x[i] >= A[i])
for i in range(len(y)):
model.addConstr(y[i] >= B[i])
objExp = gbPy.QuadExpr()
objExp.addTerms(???)
model.setObjective(objExp, gbPy.GRB.MINIMIZE)
But I'm not sure how to indicate the expression I want in the objExp.addTerms line. http://www.gurobi.com/documentation/8.1/refman/py_quadexpr_add.html provides an example:
expr = x * x + 2 * y * y
expr.add(z * z, 3.0)
But I don't understand if it's adding 3*z^2 or z^2 + 3 to the expression. Any help in explaining the syntax is greatly appreciated!
I will assume that -- in your example -- you want to set the objective to minimize
x[0]^2 + y[0]^2
. It should be straight-forward to adapt this if you need a different objective.There are various ways to set the objective.
You can define it directly inside
setObjective
:or
This is the easiest and unless your objective expression is very long and unwieldy this is what I would recommend.
Or you can build the expression first. This can give a performance advantage if you are lots of terms.
Note that in this example both the parts with
add
andaddTerms
do the same. You would only need one.The
add
method adds the expression in the first argument multiplied by the (optional) second argument. The example you are quoting first defines the expressionx^2 + y^2
, then adds3z^2
.