Skip to content

Commit

Permalink
add tests, clean up implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
frrad committed Aug 22, 2024
1 parent fa9df4e commit 90f7a86
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 15 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
13 changes: 7 additions & 6 deletions pulp/pulp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2233,16 +2233,17 @@ def lpSum(vector):
return LpAffineExpression().addInPlace(vector)


def lpDot(v1, v2):
v1_iterable = const.isiterable(v1) and not isinstance(v1, LpAffineExpression)
v2_iterable = const.isiterable(v2) and not isinstance(v2, LpAffineExpression)
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 v1_iterable and not v2_iterable:
if not _vector_like(v1) and not _vector_like(v2):
return v1 * v2
elif not v1_iterable:
elif not _vector_like(v1):
return lpDot([v1] * len(v2), v2)
elif not v2_iterable:
elif not _vector_like(v2):
return lpDot(v1, [v2] * len(v1))
else:
return lpSum([lpDot(e1, e2) for e1, e2 in zip(v1, v2)])
14 changes: 14 additions & 0 deletions pulp/tests/test_lpdot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,17 @@ def test_lpdot():

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 90f7a86

Please sign in to comment.