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 using overloaded operators. For example, if x is a GRBVar object, then x * x is a GRBQuadExpr object. Expressions can be built from constants (e.g., expr = 0), variables (e.g., expr = 1 * x *x + 2 * x * y), or from other expressions (e.g., expr2 = 2 * expr1 + x * x, or expr3 = expr1 + 2 * expr2). You can also modify existing expressions (e.g., expr += x * x, or expr2 -= expr1).
The other option for building expressions is to start with an empty expression (using the GRBQuadExpr constructor), and then add terms. Terms can be added individually (using addTerm) or in groups (using addTerms). Terms can also be removed from an expression (using remove).
Note that it is much more efficient to build large quadratic expressions by extending existing expressions (using += or -=), rather than by repeatedly creating new expressions. The statement expr = expr + x * x creates a new copy of expr, for example, while expr += x * x just appends a new term.
Individual 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, or getVar 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 terms in the expression (e.g., when using getVar1 and getVar2).