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

Implement nzvalview and use it to fix nnz for longer buffers. #20

Merged
merged 1 commit into from
Nov 6, 2024
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
2 changes: 1 addition & 1 deletion src/SparseMatricesCSR.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ using SuiteSparse

import Base: convert, copy, size, getindex, setindex!, show, count, *, IndexStyle
import LinearAlgebra: mul!, lu, lu!
import SparseArrays: nnz, getnzval, nonzeros, nzrange
import SparseArrays: nnz, getnzval, nonzeros, nzvalview, nzrange
import SparseArrays: findnz, rowvals, getnzval, issparse

export SparseMatrixCSR
Expand Down
8 changes: 5 additions & 3 deletions src/SparseMatrixCSR.jl
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ issparse(S::SparseMatrixCSR) = true

Returns the number of stored (filled) elements in a sparse array.
"""
nnz(S::SparseMatrixCSR) = length(nonzeros(S))
nnz(S::SparseMatrixCSR) = Int(getrowptr(S)[size(S, 1) + 1]) - 1

"""
nonzeros(S::SparseMatrixCSR)
Expand All @@ -231,6 +231,8 @@ and any modifications to the returned vector will mutate S as well.
"""
nonzeros(S::SparseMatrixCSR) = S.nzval

nzvalview(S::SparseMatrixCSR) = view(nonzeros(S), 1:nnz(S))

"""
colvals(S::SparseMatrixCSR{Bi}) where {Bi}

Expand Down Expand Up @@ -285,8 +287,8 @@ end
Count the number of elements in `nonzeros(S)` for which predicate `pred` returns `true`.
If `pred` not given, it counts the number of `true` values.
"""
count(pred, S::SparseMatrixCSR) = count(pred, nonzeros(S))
count(S::SparseMatrixCSR) = count(i->true, nonzeros(S))
count(pred, S::SparseMatrixCSR) = count(pred, nzvalview(S))
count(S::SparseMatrixCSR) = count(i->true, nzvalview(S))

function mul!(y::AbstractVector,A::SparseMatrixCSR,v::AbstractVector, α::Number, β::Number)
A.n == size(v, 1) || throw(DimensionMismatch())
Expand Down
7 changes: 7 additions & 0 deletions test/SparseMatrixCSR.jl
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ function test_csr(Bi,Tv,Ti)
@test out === CSR
@test _CSR ≈ -1*CSR

# Test overlong buffers
let A = sparsecsr([1, 2, 3], [1, 2, 3], [4., 5, 6])
push!(A.nzval, 4.0)
push!(A.rowptr, -1)
@test nnz(A) == length(SparseArrays.nzvalview(A)) == 3
@test SparseArrays.nzvalview(A) == [4., 5, 6]
end
end

function test_lu(Bi,I,J,V)
Expand Down