Skip to content

Commit

Permalink
LinearExpr.sum
Browse files Browse the repository at this point in the history
  • Loading branch information
d-krupke committed Sep 10, 2024
1 parent 74c0283 commit 12d82a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions 04_modelling.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,19 @@ multiplying all terms by 3. However, this requires manual intervention, which
undermines the idea of using a solver. These limitations are important to
consider, although such scenarios are rare in practical applications.

> [!TIP]
>
> If you have long sums of variables and coefficients, it can be more efficient to
> use the sum-methods of LinearExpr than to use Python's sum-function. Note that
> this function does currently not support generators.
>
> ```python
> xs = [model.NewIntVar(0, 10, f"x{i}") for i in range(5)]
> weights = [i for i in range(5)]
> model.add(cp_model.LinearExpr.sum(xs) >= 1)
> model.minimize(cp_model.LinearExpr.weighted_sum(xs, weights))
> ```
If you have a lower and an upper bound for a linear expression, you can also use
the `add_linear_constraint`-method, which allows you to specify both bounds in
one go.
Expand Down
9 changes: 9 additions & 0 deletions tests/test_lin_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ def test_lin_constraints():
model.add(x < y + z)
model.add(y > 300 - 4 * z)

def test_lin_constraint_sum():
model = cp_model.CpModel()
vars = [model.NewIntVar(0, 10, f"x{i}") for i in range(5)]
weights = [i for i in range(5)]
model.add(cp_model.LinearExpr.sum(vars) >= 1)
model.minimize(cp_model.LinearExpr.weighted_sum(vars, weights))




def test_infeasible_intersection():
model = cp_model.CpModel()
Expand Down

0 comments on commit 12d82a6

Please sign in to comment.