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.
You generally build quadratic expressions using overloaded operators.
For example, if
x is a Var
x * x is a
QuadExpr 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 full list of overloaded operators
on QuadExpr objects
is as follows:
In Python parlance, we've defined the following
You can use quicksum to build
quadratic expressions; it is a more efficient version of the Python
sum function. You can also use
addTerms to modify
expressions. Terms can be removed from an expression using
Given all these options for building expressions, you may wonder which is fastest. For small expressions, you won't need to worry about performance differences between them. If you are building lots of very large expressions (100s of terms), you will find that a single call to addTerms is fastest. Next would be a call to quicksum, followed by a series of calls to expr.add(x*x).
To add a quadratic constraint to your model, you generally build one
or two quadratic expression objects (
qexpr2) and then use
an overloaded comparison operator to build an argument for
To give a few examples:
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, use getLinExpr to obtain the linear portion of the quadratic expression, and then use the getVar, getCoeff, and getConstant methods on this LinExpr object. Note that a quadratic expression may contain multiple terms that involve the same variable pair. These duplicate terms are merged when creating a constraint from an expression, but they may be visible when inspecting individual terms in the expression (e.g., when using getVar1 and getVar2).