Skip to content

Commit

Permalink
add test / fix for lpdot (#769)
Browse files Browse the repository at this point in the history
* add test / fix for lpdot

* add tests, clean up implementation
  • Loading branch information
frrad authored Aug 31, 2024
1 parent e20a405 commit b5a445f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 12 deletions.
9 changes: 0 additions & 9 deletions pulp/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,6 @@
LpCplexLPLineSize = 78


def isiterable(obj):
try:
obj = iter(obj)
except:
return False
else:
return True


class PulpError(Exception):
"""
Pulp Exception Class
Expand Down
10 changes: 7 additions & 3 deletions pulp/pulp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2264,13 +2264,17 @@ def lpSum(vector):
return LpAffineExpression().addInPlace(vector)


def _vector_like(obj):
return isinstance(obj, Iterable) and not isinstance(obj, LpAffineExpression)


def lpDot(v1, v2):
"""Calculate the dot product of two lists of linear expressions"""
if not const.isiterable(v1) and not const.isiterable(v2):
if not _vector_like(v1) and not _vector_like(v2):
return v1 * v2
elif not const.isiterable(v1):
elif not _vector_like(v1):
return lpDot([v1] * len(v2), v2)
elif not const.isiterable(v2):
elif not _vector_like(v2):
return lpDot(v1, [v2] * len(v1))
else:
return lpSum([lpDot(e1, e2) for e1, e2 in zip(v1, v2)])
22 changes: 22 additions & 0 deletions pulp/tests/test_lpdot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from pulp import lpDot, LpVariable


def test_lpdot():
x = LpVariable(name="x")

product = lpDot(1, 2 * x)
assert product.toDict() == [{"name": "x", "value": 2}]


def test_pulp_002():
"""
Test the lpDot operation
"""
x = LpVariable("x")
y = LpVariable("y")
z = LpVariable("z")
a = [1, 2, 3]
assert dict(lpDot([x, y, z], a)) == {x: 1, y: 2, z: 3}
assert dict(lpDot([2 * x, 2 * y, 2 * z], a)) == {x: 2, y: 4, z: 6}
assert dict(lpDot([x + y, y + z, z], a)) == {x: 1, y: 3, z: 5}
assert dict(lpDot(a, [x + y, y + z, z])) == {x: 1, y: 3, z: 5}

0 comments on commit b5a445f

Please sign in to comment.