SparseArrays.jl icon indicating copy to clipboard operation
SparseArrays.jl copied to clipboard

Error with SparseArrays broadcast operation

Open btmit opened this issue 4 years ago • 4 comments
trafficstars

I have a function that is broadcasting a multiplication between a vector and a vector of vectors. This works as expected on dense vectors. If I pass a sparse vector as first argument, I get an unexpected error.

Minimum example to reproduce:

using SparseArrays
x = [1,0]
xs = sparse(x)
y = [[1, 2], [3, 4]]
julia> x .* y
2-element Vector{Vector{Int64}}:
 [1, 2]
 [0, 0]
julia> xs .* y
ERROR: MethodError: no method matching zero(::Type{Vector{Int64}})

btmit avatar May 13 '21 00:05 btmit

this is not unexpected IMO: operations that need access to non-stored zero values (e.g. linear operations or broadcast) on a sparse array can only be reasonably implemented for value types Tv for which zero(::Type{Tv}) is defined. Vector is not one of them. You can use StaticArrays or define your own type for this.

abraunst avatar May 14 '21 07:05 abraunst

I understand why zero(::Type{Tv}) is needed for the variable xs (which is sparse), but I'm missing why it is being evaluated for y. If y were sparse and xs were not, I would understand the error and fully agree with your comment.

btmit avatar May 17 '21 13:05 btmit

You're right. Digging a bit, the problem seems to be that arrays are first converted to sparse in broadcast (_sparsifystructured in SparseArrays/src/higherorderfns.jl)

abraunst avatar May 23 '21 10:05 abraunst

However, note that the result is a SparseVector{Vector{Int}}, so in principle zero could still be needed (e.g. to show the matrix on some displays). So I'm still not sure if this is a bug...

abraunst avatar May 23 '21 10:05 abraunst