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

provide type-inferred length #139

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions src/axis.jl
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,11 @@ const NotShapedOrPartitionedAxis = Union{Axis{IdxMap}, FlatAxis, NullAxis} where

Base.merge(axs::Axis...) = Axis(merge(indexmap.(axs)...))

# TODO: broken for FlatAxis
Base.firstindex(ax::AbstractAxis) = first(viewindex(first(indexmap(ax))))
Base.lastindex(ax::AbstractAxis) = last(viewindex(last(indexmap(ax))))
Base.length(ax::AbstractAxis) = lastindex(ax) - firstindex(ax) + 1
Base.length(ax::NullorFlatAxis) = error("NullorFlatAxis has no length")

Base.keys(ax::AbstractAxis) = keys(indexmap(ax))

Expand Down
13 changes: 13 additions & 0 deletions src/componentarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,19 @@ last_index(x) = last(x)
last_index(x::ViewAxis) = last_index(viewindex(x))
last_index(x::AbstractAxis) = last_index(last(indexmap(x)))

# length information is in Axis, use it to make SVector creation type stable
@inline _hasNullOrFlatAxis(ca) = any(map(ax -> ax isa NullorFlatAxis, getaxes(ca)))
function Base.length(ca::ComponentArray)
# vca2 = vcat(ca2', ca2') #has not length - is it a valid ComponentVector
# or rather a Vector<ComponentVector>
_hasNullOrFlatAxis(ca) && return(length(getdata(ca)))
prod(length.(getaxes(ca)))
end
function Base.size(ca::ComponentArray)
_hasNullOrFlatAxis(ca) && return(size(getdata(ca)))
map(length, getaxes(ca))
end

# Reduce singleton dimensions
remove_nulls() = ()
remove_nulls(x1, args...) = (x1, remove_nulls(args...)...)
Expand Down
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,14 @@ end
@test convert(Cholesky{Float32,Matrix{Float32}}, chol).factors isa Matrix{Float32}
end

@testset "length typestable" begin
# function boundary, so that cv is type-inferred
test_create_svector = (cv) -> SVector{length(cv)}(cv)
@inferred test_create_svector(ComponentVector(a=1:3));
test_create_smatrix = (cmat) -> SMatrix{size(cmat)...}(cmat)
@test (@inferred test_create_smatrix(cmat)) isa SMatrix
end;

@testset "Autodiff" begin
include("autodiff_tests.jl")
end