Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue when not adding a constraint directly to a model #145

Open
sdementen opened this issue Jan 28, 2022 · 0 comments
Open

issue when not adding a constraint directly to a model #145

sdementen opened this issue Jan 28, 2022 · 0 comments

Comments

@sdementen
Copy link
Contributor

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

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

model = CyLPModel()

y = model.addVariable("y", 1)
z = model.addVariable("z", 1)

model += z - y == 0
model += z >= -5

Indeed, in

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant