QuadExpr


QuadExpr

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, ifxis aVar对象,然后x * xis aQuadExprobject. 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, orexpr3 = expr1 + 2 * expr2). You can also modify existing expressions (e.g.,expr += x * x, orexpr2 -= expr1).

The full list of overloaded operators onQuadExprobjects is as follows:+,+=,-,-=,*,*=, and/. In Python parlance, we've defined the followingQuadExprfunctions:__add__,__radd__,__iadd__,__sub__,__rsub__,__isub__,__mul__,__rmul__,__imul__, and__div__.

We've also overloaded the comparison operators (==,<=, and>=), to make it easier to build constraints from quadratic expressions.

You can usequicksumto build quadratic expressions; it is a more efficient version of the Pythonsumfunction. You can also useaddaddTermsto modify expressions. Terms can be removed from an expression usingremove.

请注意,建筑表达的成本sions 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:

  • While the Pythonsumfunction can be used to build expressions, it should be avoided. Its cost is quadratic in the length of the expression.
  • For similar reasons, you should avoid usingexpr = expr + x*xin a loop. Building large expressions in this way also leads to quadratic runtimes.
  • Thequicksumfunction is much quicker thansum, as are loops overexpr += x*xexpr.add(x*x). These approaches are fast enough for most programs, but they may still be expensive for very large expressions.
  • The most efficient way to build a large quadratic expression is with a single call toaddTerms.

Individual quadratic terms in a quadratic expression can be queried using thegetVar1,getVar2, andgetCoeffmethods. You can query the number of quadratic terms in the expression using thesizemethod. To query the constant and linear terms associated with a quadratic expression, usegetLinExprto obtain the linear portion of the quadratic expression, and then use thegetVar,getCoeff, andgetConstantmethods on thisLinExprobject. 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 usinggetVar1andgetVar2).



Subsections