Adding Multiple Quadratic Terms To Objective Function In Gurobi Python
Solution 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
.
Post a Comment for "Adding Multiple Quadratic Terms To Objective Function In Gurobi Python"