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.
GRBQuadExpr class is a sub-class of the abstract base
In .NET languages that support operator overloading, you generally
build quadratic expressions using overloaded operators. For example,
x is a GRBVar object,
x * x is a
Expressions can be built from constants (e.g.,
expr = 0),
expr = 1 * x * x + 2 * x * y), or from other
expr2 = 2 * expr1 + x, or
expr3 = expr1 + 2 * expr2). You can also modify existing expressions
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 or MultAdd). Terms can also be removed from an expression (using Remove).
Note that the cost of building expressions depends heavily on the approach you use. While you can generally ignore this issue when building small expressions, you should be aware of a few efficiency issues when building large expressions:
- You should avoid using
expr = expr + x*xor
expr += x*xin a loop. It will lead to runtimes that are quadratic in the number of terms in the expression.
- Using AddTerm in a loop is reasonably efficient, but it isn't the most efficient approach.
- The most efficient way to build a large expression is to make a single call to AddTerms.
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
give a few examples:
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 property. To query the constant and linear terms associated with a quadratic expression, first obtain the linear portion of the quadratic expression using LinExpr, and then use the Constant, 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 quadratic terms in the expression (e.g., when using GetVar1 and GetVar2).