Gurobi linear expression object. A linear expression consists of a constant term, plus a list of coefficient-variable pairs that capture the linear terms. Linear expressions are used to build linear objective and constraints. They are temporary objects that typically have short lifespans.
You generally build linear expressions using overloaded operators.
For example, if
x is a Var
x + 1 is a
LinExpr object. Expressions
can be built from constants (e.g.,
expr = 0), variables (e.g.,
expr = 1 * x + 2 * y), or from other expressions (e.g.,
expr2 = 2 * expr1 + x, or
expr3 = expr1 + 2 * expr2).
You can also modify existing expressions (e.g.,
expr += x, or
expr2 -= expr1).
The full list of overloaded operators on
LinExpr objects is as follows:
In Python parlance, we've defined the following
You can also use add or
addTerms to modify
expressions. The LinExpr()
constructor can be used to build expressions. Another option is
quicksum; it is a more
efficient version of the Python
sum function. Terms can be
removed from an expression using
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:
- While the Python
sumfunction 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 using
expr = expr + xin a loop. Building large expressions in this way also leads to quadratic runtimes.
- The quicksum function is
much quicker than
sum, as are loops over
expr += xor expr.add(x). These approaches are fast enough for most programs, but they may still be expensive for very large expressions.
- The two most efficient ways to build large linear expressions are addTerms or the LinExpr() constructor.
Note that a linear expression may contain multiple terms that involve the same variable. 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 getVar).