From a1779d112ef11cb6ddf3dd3afd170e2c2aee56bb Mon Sep 17 00:00:00 2001 From: Guillaume Marques Date: Sat, 3 Sep 2022 10:05:57 +0200 Subject: [PATCH] =?UTF-8?q?support=20addition=20&=20subtraction=20=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/vector.jl | 19 ++++++++++++++ test/functional/functionaltests.jl | 4 ++- test/functional/math.jl | 42 ++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/vector.jl b/src/vector.jl index 4972995..2267cfc 100644 --- a/src/vector.jl +++ b/src/vector.jl @@ -82,3 +82,22 @@ end SparseArrays.nnz(v::DynamicSparseVector) = nnz(v.pma) Base.copy(::DynamicSparseVector) = error("copy of a dynamic sparse vector not implemented.") + +# to use linear algebra: +function SparseArrays.nonzeroinds(v::DynamicSparseVector{K,T}) where {K,T} + return reduce(v.pma.array; init = K[]) do collection, e + if !isnothing(e) + push!(collection, first(e)) + end + return collection + end +end + +function SparseArrays.nonzeros(v::DynamicSparseVector{K,T}) where {K,T} + return reduce(v.pma.array; init = T[]) do collection, e + if !isnothing(e) + push!(collection, last(e)) + end + return collection + end +end \ No newline at end of file diff --git a/test/functional/functionaltests.jl b/test/functional/functionaltests.jl index 781055d..07da0e0 100644 --- a/test/functional/functionaltests.jl +++ b/test/functional/functionaltests.jl @@ -38,8 +38,10 @@ function functional_tests() dynsparsematrix_fill_mode() end - @testset "spMv" begin + @testset "lin alg" begin spMv1() + addition() + subtraction() end return end diff --git a/test/functional/math.jl b/test/functional/math.jl index 9dd37ab..46b93e9 100644 --- a/test/functional/math.jl +++ b/test/functional/math.jl @@ -50,3 +50,45 @@ function spMv1() @test i == j == d end +function addition() + vec_rows1 = rand(rng, 1:100, 25) + vec_values1 = rand(rng, 1:10, 25) + + dyn_vec1 = dynamicsparsevec(vec_rows1, vec_values1, 100) + vec1 = sparsevec(vec_rows1, vec_values1, 100) + + vec_rows2 = rand(rng, 1:100, 25) + vec_values2 = rand(rng, 1:10, 25) + + dyn_vec2 = dynamicsparsevec(vec_rows2, vec_values2, 100) + vec2 = sparsevec(vec_rows2, vec_values2, 100) + + classic_sum = vec1 + vec2 + + @test dyn_vec1 + dyn_vec2 == classic_sum + @test vec1 + dyn_vec2 == classic_sum + @test dyn_vec1 + vec2 == classic_sum +end + +function subtraction() + vec_rows1 = rand(rng, 1:100, 25) + vec_values1 = rand(rng, 1:10, 25) + + dyn_vec1 = dynamicsparsevec(vec_rows1, vec_values1, 100) + vec1 = sparsevec(vec_rows1, vec_values1, 100) + + vec_rows2 = rand(rng, 1:100, 25) + vec_values2 = rand(rng, 1:10, 25) + + dyn_vec2 = dynamicsparsevec(vec_rows2, vec_values2, 100) + vec2 = sparsevec(vec_rows2, vec_values2, 100) + + classic_sub = vec1 - vec2 + + @test dyn_vec1 - dyn_vec2 == classic_sub + @test vec1 - dyn_vec2 == classic_sub + @test dyn_vec1 - vec2 == classic_sub + @test -dyn_vec1 == -vec1 + @test -dyn_vec2 == -vec2 +end +