Skip to content

Commit

Permalink
Merge pull request scipy#16035 from v0dro/sparse-matmul
Browse files Browse the repository at this point in the history
BUG: allow scalar input to the `.dot` method of sparse matrices

This was a regression in 1.8.0. Closes scipygh-15258.
  • Loading branch information
rgommers authored Apr 26, 2022
2 parents b2a1535 + 89c2eb2 commit 895f29d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
5 changes: 4 additions & 1 deletion scipy/sparse/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,10 @@ def dot(self, other):
array([ 1, -3, -1], dtype=int64)
"""
return self @ other
if np.isscalar(other):
return self * other
else:
return self @ other

def power(self, n, dtype=None):
"""Element-wise power."""
Expand Down
10 changes: 9 additions & 1 deletion scipy/sparse/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1629,6 +1629,14 @@ def test_binop_custom_type_with_shape(self):
assert_equal(eval('A @ B'), "matrix on the left")
assert_equal(eval('B @ A'), "matrix on the right")

def test_dot_scalar(self):
M = self.spmatrix(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
scalar = 10
actual = M.dot(scalar)
expected = M * scalar

assert_allclose(actual.toarray(), expected.toarray())

def test_matmul(self):
M = self.spmatrix(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
B = self.spmatrix(array([[0,1],[1,0],[0,2]],'d'))
Expand Down Expand Up @@ -3620,7 +3628,7 @@ def test_constructor4(self):
ij = vstack((row,col))
csr = csr_matrix((data,ij),(4,3))
assert_array_equal(arange(12).reshape(4, 3), csr.toarray())

# using Python lists and a specified dtype
csr = csr_matrix(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64)
dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64)
Expand Down

0 comments on commit 895f29d

Please sign in to comment.