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

Repeated names #148

Open
wants to merge 1 commit into
base: master
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
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,3 @@ end

You can do this to your own functions in your own packages, to add `NamedDimsArray` support.
If you implement it for any functions in a standard library, a PR would be very appreciated.

### Caveats

If multiple dimensions have the same names, indexing by name is considered undefined behaviour and should not be relied upon.
3 changes: 3 additions & 0 deletions src/name_core.jl
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,11 @@ order_named_inds(val::Val{L}; kw...) where {L} = order_named_inds(val, kw.data)

@generated function order_named_inds(val::Val{L}, ni::NamedTuple{K}) where {L,K}
tuple_issubset(K, L) || throw(DimensionMismatch("Expected subset of $L, got $K"))
seen = []
exs = map(L) do n
if Base.sym_in(n, K)
n in seen && throw(ArgumentError("Can't index with :$n as this is repeated in $L"))
push!(seen, n)
qn = QuoteNode(n)
:(getfield(ni, $qn))
else
Expand Down
7 changes: 7 additions & 0 deletions test/functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ using Statistics
end
end

@testset "repeated names" begin
ndt = NamedDimsArray(reshape(1:12, 2,3,2), (:x, :y, :x))
@test sum(ndt, dims=:y) == sum(ndt, dims=2)
@test sum(ndt, dims=:x) == sum(ndt, dims=1) # chooses the first
@test dropdims(sum(ndt, dims=:x), dims=:x) == dropdims(sum(ndt, dims=1), dims=:x)
end

@testset "sort!" begin
a = [1 9; 7 3]
nda = NamedDimsArray(a, (:x, :y))
Expand Down
6 changes: 6 additions & 0 deletions test/wrapper_array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ end
@test nda[findall(iseven, nda)] isa Vector
@test dimnames(ndv[findall(iseven, ndv)]) == (:x,)
end

@testset "repeated names" begin
ndt = NamedDimsArray(rand(2,3,2), (:x, :y, :x))
@test ndt[y=1] == ndt[:, 1, :]
@test_throws ArgumentError ndt[x=1]
end
end


Expand Down