From 70fb0384cf465a2cbe64c0ba8b532e85ca12080b Mon Sep 17 00:00:00 2001 From: Jishnu Bhattacharya Date: Wed, 8 May 2024 23:10:46 +0530 Subject: [PATCH 1/2] Reshape for a OneElement --- src/oneelement.jl | 10 ++++++++++ test/runtests.jl | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/oneelement.jl b/src/oneelement.jl index f6204abb..c72bcd2d 100644 --- a/src/oneelement.jl +++ b/src/oneelement.jl @@ -372,6 +372,16 @@ function broadcasted(::DefaultArrayStyle{N}, ::typeof(\), x::Number, r::OneEleme OneElement(x \ r.val, r.ind, axes(r)) end +# reshape + +function Base.reshape(A::OneElement, shape::Tuple{Vararg{Int}}) + prod(shape) == length(A) || throw(DimensionMismatch("new dimension $shape must be consistent with array size $(length(A))")) + # we use the fact that the linear index of the non-zero value is preserved + oldlinind = LinearIndices(A)[A.ind...] + newcartind = CartesianIndices(shape)[oldlinind] + OneElement(A.val, Tuple(newcartind), shape) +end + # show _maybesize(t::Tuple{Base.OneTo{Int}, Vararg{Base.OneTo{Int}}}) = size.(t,1) _maybesize(t) = t diff --git a/test/runtests.jl b/test/runtests.jl index 2e2aba22..463a4b40 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -2215,6 +2215,16 @@ end @test adjoint(A) == OneElement(3, (1,2), (1,4)) end + @testset "reshape" begin + for O in (OneElement(2, (2,3), (4,5)), OneElement(2, (2,), (20,)), + OneElement(2, (1,2,2), (2,2,5))) + A = Array(O) + for shp in ((2,5,2), (5,1,4), (20,), (2,2,5,1,1)) + @test reshape(O, shp) == reshape(A, shp) + end + end + end + @testset "isassigned" begin f = OneElement(2, (3,3), (4,4)) @test !isassigned(f, 0, 0) From b4a19a791e3b2e129b577fd3e7d6f9b0534b4524 Mon Sep 17 00:00:00 2001 From: Jishnu Bhattacharya Date: Wed, 8 May 2024 23:14:22 +0530 Subject: [PATCH 2/2] Tests for 0D --- test/runtests.jl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/runtests.jl b/test/runtests.jl index 463a4b40..d4b2bb95 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -2223,6 +2223,8 @@ end @test reshape(O, shp) == reshape(A, shp) end end + O = OneElement(2, (), ()) + @test reshape(O, ()) === O end @testset "isassigned" begin