issue when not adding a constraint directly to a model
- Dominant language
- JetBrains MPS
- Stars
- 192
- Forks
- 70
- PR merge metrics
- No merged PRs in 30d
Description
If one wants to build constraints without adding the directly to a model, the CyLPExpr is "corrupted".
Indeed, each operation on a CyLPExpr has the strong side effect of modifying in place the `CyLPExpr.expr` (for instance https://github.com/coin-or/CyLP/blob/master/cylp/py/modeling/CyLPModel.py#L191). It is only at the end of the `CyLPExpr.evaluate` (called from the `CyLPModel.addConstraint`) that the `CyLPExpr.expr` is reset.
This side effect is most probably there to support the `a <= x <= b` notation which is translated by python in `(a <= x) and (x <= b)` requiring the last element `(x <= b)` to evaluate to the `CyLPExpr.expr` representing `a <= x <= b`.
However, it introduces the quite non pythonic behavior that a CyLPExpr cannot be instantiated without directly assigning to a model.
i.e, the following
```python
model = CyLPModel()
y = model.addVariable("y", 1)
z = model.addVariable("z", 1)
constraints = [
z - y == 0,
z >= -5,
]
for c in constraints:
model += c
```
is not equivalent to
```python
model = CyLPModel()
y = model.addVariable("y", 1)
z = model.addVariable("z", 1)
model += z - y == 0
model += z >= -5
```
Indeed, in
```python
constraints = [
z - y == 0,
z >= -5,
]
```
when the second constraint `z >= -5` is evaluated, the CyLPVar.expr of z has been changed when the first constraint `z - y == 0` was defined and is equal now to ´z - y´ leading to the wrongly evaluated expression `z - y >= -5`
This bug has bitten me hard ;-) and forces the user to assign the constraint directly to the model to avoid the bug.
In other LP modeling framework using python syntax, the alternative solutions to express `a <= x <= b` are:
- either to disallow the ability to see both bounds at once (the user should go with `a <= x` and `x <= b`)
- use the notation `x == (a,b)` to mean `a <= x <= b` (my preferred option)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.