Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __neg__(self):
return LinExpr({v:-c for v,c in self.terms.items()})
def __mul__(self, other):
if _is_number(other):
f = float(other)
return LinExpr({v:f*c for v,c in self.terms.items()})
elif isinstance(other, LinExpr):
terms = {}
for v1, c1 in self.terms.items():
for v2, c2 in other.terms.items():
v = tuple(sorted(v1 + v2))
terms[v] = terms.get(v, 0.0) + c1 * c2
return LinExpr(terms)
else:
raise NotImplementedError
def __add__(self, other):
terms = self.terms.copy()
if isinstance(other, LinExpr):
# merge the terms by component-wise addition
for v,c in other.terms.items():
terms[v] = terms.get(v, 0.0) + c
elif _is_number(other):
c = float(other)
terms[CONST] = terms.get(CONST, 0.0) + c
else:
raise NotImplementedError
return LinExpr(terms)
def quicksum(termlist):
'''add linear expressions and constants much faster than Python's sum
by avoiding intermediate data structures and adding terms inplace
'''
result = LinExpr()
for term in termlist:
result += term
return result
def __le__(self, other):
'''turn it into a constraint'''
if isinstance(other, LinExpr):
return (self - other) <= 0.0
elif _is_number(other):
return LinCons(self, ub=float(other))
else:
raise NotImplementedError
def __mul__(self, other):
if _is_number(other):
f = float(other)
return LinExpr({v:f*c for v,c in self.terms.items()})
elif isinstance(other, LinExpr):
terms = {}
for v1, c1 in self.terms.items():
for v2, c2 in other.terms.items():
v = tuple(sorted(v1 + v2))
terms[v] = terms.get(v, 0.0) + c1 * c2
return LinExpr(terms)
else:
raise NotImplementedError