Skip to content

Commit

Permalink
Fix #42670 - error in sparsevec outer product with stored zeros (#42671)
Browse files Browse the repository at this point in the history
The SparseMatrixCSC constructor checks that the passed in buffers
have length matching the expected number of non-zeros, but the
_outer constructor allocated buffers of the number of structural
non-zeros, not actual non-zeros. Fix this by shrinking the buffers
once the outer product is fully computed.
  • Loading branch information
Keno authored Oct 18, 2021
1 parent 4c8c515 commit d885fc2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions stdlib/SparseArrays/src/higherorderfns.jl
Original file line number Diff line number Diff line change
Expand Up @@ -840,20 +840,28 @@ function _outer(trans::Tf, x, y) where Tf
@inbounds colptrC[1] = 1
@inbounds for jj = 1:nnzy
yval = nzvalsy[jj]
iszero(yval) && continue
if iszero(yval)
nnzC -= nnzx
continue
end
col = rowvaly[jj]
yval = trans(yval)

for ii = 1:nnzx
xval = nzvalsx[ii]
iszero(xval) && continue
if iszero(xval)
nnzC -= 1
continue
end
idx += 1
colptrC[col+1] += 1
rowvalC[idx] = rowvalx[ii]
nzvalsC[idx] = xval * yval
end
end
cumsum!(colptrC, colptrC)
resize!(rowvalC, nnzC)
resize!(nzvalsC, nnzC)

return SparseMatrixCSC(nx, ny, colptrC, rowvalC, nzvalsC)
end
Expand Down
9 changes: 9 additions & 0 deletions stdlib/SparseArrays/test/higherorderfns.jl
Original file line number Diff line number Diff line change
Expand Up @@ -726,4 +726,13 @@ end
@test extrema(x; dims=[]) == extrema(y; dims=[])
end

@testset "issue #42670 - error in sparsevec outer product" begin
A = spzeros(Int, 4)
B = copy(A)
C = sparsevec([0 0 1 1 0 0])'
A[2] = 1
A[2] = 0
@test A * C == B * C == spzeros(Int, 4, 6)
end

end # module

0 comments on commit d885fc2

Please sign in to comment.