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 12d82a6 commit 3ba5244
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
6 changes: 3 additions & 3 deletions 04_modelling.md
Original file line number Diff line number Diff line change
Expand Up @@ -447,9 +447,9 @@ 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.
> 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)]
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,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
3 changes: 1 addition & 2 deletions tests/test_lin_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ 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():
Expand Down

0 comments on commit 3ba5244

Please sign in to comment.