Skip to content

Commit

Permalink
Reshape for a OneElement (#365)
Browse files Browse the repository at this point in the history
* Reshape for a OneElement

* Tests for 0D
  • Loading branch information
jishnub authored May 9, 2024
1 parent 5d88772 commit 4f8a966
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/oneelement.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2215,6 +2215,18 @@ 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
O = OneElement(2, (), ())
@test reshape(O, ()) === O
end

@testset "isassigned" begin
f = OneElement(2, (3,3), (4,4))
@test !isassigned(f, 0, 0)
Expand Down

0 comments on commit 4f8a966

Please sign in to comment.