Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix -, conj, and conj! for sparse matrices with invalid entries in nzval #31187

Merged
merged 1 commit into from
Mar 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions stdlib/SparseArrays/src/sparsematrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1503,12 +1503,22 @@ sparse(s::UniformScaling, dims::Dims{2}) = SparseMatrixCSC(s, dims)
sparse(s::UniformScaling, m::Integer, n::Integer) = sparse(s, Dims((m, n)))

# TODO: More appropriate location?
conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A)
(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval))
function conj!(A::SparseMatrixCSC)
map!(conj, nzvalview(A), nzvalview(A))
return A
end
function (-)(A::SparseMatrixCSC)
nzval = similar(A.nzval)
map!(-, view(nzval, 1:nnz(A)), nzvalview(A))
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
end

# the rest of real, conj, imag are handled correctly via AbstractArray methods
conj(A::SparseMatrixCSC{<:Complex}) =
SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval))
function conj(A::SparseMatrixCSC{<:Complex})
nzval = similar(A.nzval)
map!(conj, view(nzval, 1:nnz(A)), nzvalview(A))
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
end
imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n)

## Binary arithmetic and boolean operators
Expand Down
12 changes: 12 additions & 0 deletions stdlib/SparseArrays/test/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2518,4 +2518,16 @@ end
@test_throws ArgumentError sparse(I1, J1, zero(length(I1)zero(length(I1))))
end

@testset "unary operations on matrices where length(nzval)>nnz" begin
# this should create a sparse matrix with length(nzval)>nnz
A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]
# ...ensure it does! If necessary, the test needs to be updated to use
# another mechanism to create a suitable A.
@assert length(A.nzval) > nnz(A)
@test -A == fill(-2-2im, 1, 1)
@test conj(A) == fill(2-2im, 1, 1)
conj!(A)
@test A == fill(2-2im, 1, 1)
end

end # module