Skip to content

Commit

Permalink
entities: Avoid voiding coefficients in LinExpr creation from Var ove…
Browse files Browse the repository at this point in the history
…rrides (coin-or#396)
  • Loading branch information
ItsNiklas committed Nov 11, 2024
1 parent e76f1e0 commit ca7f8d9
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions mip/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ class LinExpr:
a = 10*x1 + 7*x4
print(a.x)
.. warning::
Do not pass identical objects in the ``variables`` argument when constructing
a LinExpr manually.
"""

__slots__ = ["__const", "__expr", "__sense"]
Expand Down Expand Up @@ -542,6 +545,8 @@ def __add__(
self, other: Union["mip.Var", LinExpr, numbers.Real]
) -> Union["mip.Var", LinExpr]:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [2])
return LinExpr([self, other], [1, 1])
if isinstance(other, LinExpr):
return other.__add__(self)
Expand All @@ -561,6 +566,8 @@ def __sub__(
self, other: Union["mip.Var", LinExpr, numbers.Real]
) -> Union["mip.Var", LinExpr]:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [0])
return LinExpr([self, other], [1, -1])
if isinstance(other, LinExpr):
return (-other).__add__(self)
Expand All @@ -575,6 +582,8 @@ def __rsub__(
self, other: Union["mip.Var", LinExpr, numbers.Real]
) -> Union["mip.Var", LinExpr]:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [0])
return LinExpr([self, other], [-1, 1])
if isinstance(other, LinExpr):
return other.__sub__(self)
Expand Down Expand Up @@ -603,6 +612,8 @@ def __neg__(self) -> LinExpr:

def __eq__(self, other) -> LinExpr:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [0], sense="=")
return LinExpr([self, other], [1, -1], sense="=")
if isinstance(other, LinExpr):
return LinExpr([self], [1]) == other
Expand All @@ -613,6 +624,8 @@ def __eq__(self, other) -> LinExpr:

def __le__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [0], sense="<")
return LinExpr([self, other], [1, -1], sense="<")
if isinstance(other, LinExpr):
return LinExpr([self], [1]) <= other
Expand All @@ -623,6 +636,8 @@ def __le__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:

def __ge__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:
if isinstance(other, Var):
if id(self) == id(other):
return LinExpr([self], [0], sense=">")
return LinExpr([self, other], [1, -1], sense=">")
if isinstance(other, LinExpr):
return LinExpr([self], [1]) >= other
Expand Down

0 comments on commit ca7f8d9

Please sign in to comment.