Skip to content

Commit ca7f8d9

Browse files
committed
entities: Avoid voiding coefficients in LinExpr creation from Var overrides (coin-or#396)
1 parent e76f1e0 commit ca7f8d9

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

mip/entities.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ class LinExpr:
6565
a = 10*x1 + 7*x4
6666
print(a.x)
6767
68+
.. warning::
69+
Do not pass identical objects in the ``variables`` argument when constructing
70+
a LinExpr manually.
6871
"""
6972

7073
__slots__ = ["__const", "__expr", "__sense"]
@@ -542,6 +545,8 @@ def __add__(
542545
self, other: Union["mip.Var", LinExpr, numbers.Real]
543546
) -> Union["mip.Var", LinExpr]:
544547
if isinstance(other, Var):
548+
if id(self) == id(other):
549+
return LinExpr([self], [2])
545550
return LinExpr([self, other], [1, 1])
546551
if isinstance(other, LinExpr):
547552
return other.__add__(self)
@@ -561,6 +566,8 @@ def __sub__(
561566
self, other: Union["mip.Var", LinExpr, numbers.Real]
562567
) -> Union["mip.Var", LinExpr]:
563568
if isinstance(other, Var):
569+
if id(self) == id(other):
570+
return LinExpr([self], [0])
564571
return LinExpr([self, other], [1, -1])
565572
if isinstance(other, LinExpr):
566573
return (-other).__add__(self)
@@ -575,6 +582,8 @@ def __rsub__(
575582
self, other: Union["mip.Var", LinExpr, numbers.Real]
576583
) -> Union["mip.Var", LinExpr]:
577584
if isinstance(other, Var):
585+
if id(self) == id(other):
586+
return LinExpr([self], [0])
578587
return LinExpr([self, other], [-1, 1])
579588
if isinstance(other, LinExpr):
580589
return other.__sub__(self)
@@ -603,6 +612,8 @@ def __neg__(self) -> LinExpr:
603612

604613
def __eq__(self, other) -> LinExpr:
605614
if isinstance(other, Var):
615+
if id(self) == id(other):
616+
return LinExpr([self], [0], sense="=")
606617
return LinExpr([self, other], [1, -1], sense="=")
607618
if isinstance(other, LinExpr):
608619
return LinExpr([self], [1]) == other
@@ -613,6 +624,8 @@ def __eq__(self, other) -> LinExpr:
613624

614625
def __le__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:
615626
if isinstance(other, Var):
627+
if id(self) == id(other):
628+
return LinExpr([self], [0], sense="<")
616629
return LinExpr([self, other], [1, -1], sense="<")
617630
if isinstance(other, LinExpr):
618631
return LinExpr([self], [1]) <= other
@@ -623,6 +636,8 @@ def __le__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:
623636

624637
def __ge__(self, other: Union["mip.Var", LinExpr, numbers.Real]) -> LinExpr:
625638
if isinstance(other, Var):
639+
if id(self) == id(other):
640+
return LinExpr([self], [0], sense=">")
626641
return LinExpr([self, other], [1, -1], sense=">")
627642
if isinstance(other, LinExpr):
628643
return LinExpr([self], [1]) >= other

0 commit comments

Comments
 (0)