问题
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!
回答1:
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
:
model.setObjective(x[0] * x[0] + y[0] * y[0])
or
model.setObjective(x[0] * x[0] + y[0] * y[0], gbPy.GRB.MINIZE) # minimize is the default; so it is optional
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.
# define the quadratic expression object
objExp = gbPy.QuadExpr()
# add single terms using add
objExp.add(x[0] * x[0])
objExp.add(y[0] * y[0])
# you could also do this in one line adding x[0]*x[0] + y[0]*y[0]
# or add multiple terms at once using addTerms
#objExp.addTerms([1, 1], [x[0], y[0]], [x[0], y[0]])
# set the objective
model.setObjective(objExp, gbPy.GRB.MINIMIZE)
Note that in this example both the parts with add
and addTerms
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 expression x^2 + y^2
, then adds 3z^2
.
来源:https://stackoverflow.com/questions/55362487/adding-multiple-quadratic-terms-to-objective-function-in-gurobi-python