Gurobi quadratic expression object. A quadratic expression consists of a linear expression, plus a list of coefficient-variable-variable triples that capture the quadratic terms. Quadratic expressions are used to build quadratic objective functions and quadratic constraints. They are temporary objects that typically have short lifespans.

The GRBQuadExpr class is a sub-class of the abstract base class GRBExpr.

You generally build quadratic expressions by starting with an empty expression (using the GRBQuadExpr constructor), and then adding terms. Terms can be added individually, using addTerm, or in groups, using addTerms, or multAdd. Quadratic terms can be removed from a quadratic expression using remove.

To add a quadratic constraint to your model, you generally build one or two quadratic expression objects (qexpr1 and qexpr2) and then use an overloaded comparison operator to build an argument for GRBModel.addQConstr. To give a few examples:

<span>$</span>\displaystyle \begin{array}{l}
\mathrm{model.addQConstr}(qexpr1, GRB.LESS\_EQUAL, qexpr2) \
\mathrm{model.addQConstr}(qexpr1, GRB.EQUAL, 1) \
Once you add a constraint to your model, subsequent changes to the expression object you used to build the constraint will have no effect on that constraint.

Individual quadratic terms in a quadratic expression can be queried using the getVar1, getVar2, and getCoeff methods. You can query the number of quadratic terms in the expression using the size method. To query the constant and linear terms associated with a quadratic expression, first obtain the linear portion of the quadratic expression using getLinExpr, and then use the getConstant, getCoeff, and getVar methods on the resulting GRBLinExpr object.

Note that a quadratic expression may contain multiple terms that involve the same variable pair. These duplicate terms are merged when creating the model objective from an expression, but they may be visible when inspecting individual quadratic terms in the expression (e.g., when using getVar1 and getVar2).