Skip to content
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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ jobs:
matrix:
version:
- '1.6'
- '1.10'
- '1.11'
- '1' # automatically expands to the latest stable 1.x release of Julia
- 'nightly'
os:
Expand Down
109 changes: 77 additions & 32 deletions src/InvertedIndices.jl
Original file line number Diff line number Diff line change
Expand Up @@ -177,52 +177,97 @@ uniquesort(r::AbstractRange) = step(r) > 0 ? r : step(r) == 0 ? r[end:end] : rev
uniquesort(A::Base.LogicalIndex) = A
uniquesort(x) = x

@inline function Base.to_indices(A, inds, I::Tuple{InvertedIndex, Vararg{Any}})
new_indices = to_indices(A, inds, (I[1].skip, tail(I)...))
skips = uniquesort(new_indices[1])
picks = spanned_indices(inds, skips)[1]
return (InvertedIndexIterator(skips, picks), tail(new_indices)...)
# The cartesian product of the tuple of indices, like CartesianIndices but with
# support for integers, arbitrary vectors, and heterogeneous mixtures thereof
# The vectors must be sorted for use in an InvertedIndexIterator
struct CartesianIndexArray{M,N,X} <: AbstractArray{CartesianIndex{M},N}
tup::X
end

struct ZeroDArray{T} <: AbstractArray{T,0}
x::T
@inline Base.axes(ca::CartesianIndexArray) = Base.index_shape(ca.tup...)
@inline Base.size(ca::CartesianIndexArray) = map(length, Base.index_shape(ca.tup...))
@inline function Base.getindex(ca::CartesianIndexArray{<:Any,N}, I::Vararg{Int, N}) where {N}
@boundscheck checkbounds(ca, I...)
CartesianIndex(reindex(ca.tup, I))
end
Base.size(::ZeroDArray) = ()
Base.getindex(Z::ZeroDArray) = Z.x

# Be careful with CartesianIndex as they splat out to a variable number of new indices and do not iterate
function Base.to_indices(A, inds, I::Tuple{InvertedIndex{<:CartesianIndex}, Vararg{Any}})
skips = ZeroDArray(I[1].skip)
picks, tails = spanned_indices(inds, skips)
return (InvertedIndexIterator(skips, picks), to_indices(A, tails, tail(I))...)
end
cartesian(tup) = CartesianIndexArray{length(tup), length(Base.index_shape(tup...)), typeof(tup)}(tup)
cartesian(tup::Tuple{Vararg{AbstractUnitRange}}) = CartesianIndices(tup)

# Either return a CartesianRange or an axis vector
@inline spanned_indices(inds, ::Any) = inds[1], tail(inds)
const NIdx{N} = Union{CartesianIndex{N}, AbstractArray{CartesianIndex{N}}, AbstractArray{Bool,N}}
@inline spanned_indices(inds, ::NIdx{0}) = CartesianIndices(()), inds
@inline spanned_indices(inds, ::NIdx{1}) = inds[1], tail(inds)
@inline function spanned_indices(inds, ::NIdx{N}) where N
heads, tails = Base.IteratorsMD.split(inds, Val(N))
return CartesianIndices(heads), tails
@inline reindex(tup::Tuple{<:AbstractVector, Vararg{Any}}, I) = (tup[1][I[1]], reindex(tail(tup), Base.safe_tail(I))...)
reindex(::Tuple{<:AbstractArray, Vararg{Any}}, I) = throw(AssertionError("InvertedIndex did not expect a multidimensional array within a cartesian product"))
@inline reindex(tup::Tuple{Any, Vararg{Any}}, I) = (tup[1], reindex(tail(tup), I)...)
reindex(::Tuple{}, I) = ()

@inline take_n_axes(A, inds::Tuple, n::Tuple) = take_n_axes(A, 1, inds, n)
@inline take_n_axes(A, i, inds::Tuple, n::Tuple) = (inds[1], take_n_axes(A, i, tail(inds), tail(n))...)
@inline take_n_axes(A, i, ::Tuple{}, n::Tuple) = (axes(A, ndims(A)+i), take_n_axes(A, i+1, (), tail(n))...)
take_n_axes(A, i, ::Tuple, ::Tuple{}) = ()
take_n_axes(A, i, ::Tuple{}, ::Tuple{}) = ()

function Base.to_indices(A, inds, I::Tuple{InvertedIndex, Vararg{Any}})
new_indices = to_indices(A, inds, (I[1].skip, tail(I)...))
# Now the hard part is connecting the picks (from inds) and skips (from new_indices)
# The easy one to get is the number of dimensions (axes) that the inverted index spans:
n_picks = index_ndims(A, I[1].skip)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the full indexing context for older Boolean masks

index_ndims(A, I[1].skip) always calls the one-index specialization, including when Not has a following index. On Julia 1.6.7, A = reshape(collect(1:24), 4, 3, 2); mask = falses(4, 3); mask[2:3, 1:2] .= true; A[Not(mask), 1] works on main and should equal A[:, :, 1][.!mask], but this head throws BoundsError. Both BitMatrix and Matrix{Bool}, including views, regress because picks spans one axis while the converted logical index spans two. Apply the legacy one-index adjustment only when the original I actually has one index; otherwise retain the mask dimension count.

AI disclosure: This work was prepared with assistance from OpenAI Codex.

picks = take_n_axes(A, inds, n_picks)
# The hard one is the number of indices that we need to pull out of new_indices; we need
# the same `index_ndims` as the picks, but this may not be the same index _count_.
skips = spanned_indices(A, new_indices, n_picks)
_, tails = Base.IteratorsMD.split(new_indices, Val(length(skips)))
if length(picks) == length(skips) == 1
# The common case
return (InvertedIndexIterator(uniquesort(skips[1]), picks[1]), tails...)
elseif length(skips) == 1
# The picks are always tuples of AbstractUnitRanges
return (InvertedIndexIterator(uniquesort(skips[1]), CartesianIndices(picks)), tails...)
else
# But the skips might be a tuple of other index types
return (InvertedIndexIterator(cartesian(map(uniquesort, skips)), CartesianIndices(picks)), tails...)
end
end

# It's possible more indices were specified than there were axes
@inline spanned_indices(inds::Tuple{}, ::Any) = Base.OneTo(1), ()
@inline spanned_indices(inds::Tuple{}, ::NIdx{0}) = CartesianIndices(()), ()
@inline spanned_indices(inds::Tuple{}, ::NIdx{1}) = Base.OneTo(1), ()
@inline spanned_indices(inds::Tuple{}, ::NIdx{N}) where N = CartesianIndices(ntuple(i->Base.OneTo(1), N)), ()
spanned_indices(A, ::Tuple{}, n) = throw(AssertionError("Not enough indices to span the picks"))
spanned_indices(A, ::Tuple{}, ::Tuple{}) = ()
@inline function spanned_indices(A, inds, ::Tuple{})
# This is a little tricky; we need to keep pulling inds out as long as they're 0-ndim
i1 = inds[1]
dims1 = index_ndims(A, i1)
return dims1 == () ? (i1, spanned_indices(A, tail(inds), ())...) : ()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve zero-dimensional indices after the inverted index

After all axes belonging to Not are consumed, this branch also consumes zero-dimensional Cartesian indices from tail(I). Those indices can add output dimensions. For A = reshape(collect(1:12), 4, 3), main returns a 3-by-1 matrix from A[Not(1), [CartesianIndex()], 1], matching A[2:4, [CartesianIndex()], 1]; this head returns a vector instead. Reproduced on Julia 1.6.7 and 1.12.6 with scalar, range, and vector skips. Distinguish the converted entries belonging to the skipped index from entries belonging to following indices rather than collecting every subsequent zero-axis entry into skips.

AI disclosure: This work was prepared with assistance from OpenAI Codex.

end
@inline function spanned_indices(A, inds, n)
i1 = inds[1]
dims1 = index_ndims(A, i1)
(i1, spanned_indices(A, tail(inds), Base.IteratorsMD.split(n, Val(length(dims1)))[2])...)
end

# This is an interesting need — we need this because otherwise indexing with a
# single multidimensional boolean array ends up comparing a multidimensional cartesian
# index to a linear index.
const NIdx{N} = Union{CartesianIndex{N}, AbstractArray{CartesianIndex{N}}, AbstractArray{Bool,N}}
@inline Base.to_indices(A, I::Tuple{Not{<:NIdx{1}}}) = to_indices(A, (eachindex(IndexLinear(), A),), I)
@inline Base.to_indices(A, I::Tuple{Not{<:NIdx}}) = to_indices(A, axes(A), I)

# The number of dimensions that an index spans is tricky due to historical bad behavior of
# logical indices. In Julias 1.10 and before, the behavior of a logical index depends upon
# three things: (1) if it's the only index and (2) the IndexStyle of the parent and (3) the index type
# After 1.10, the behaviors no longer depend on (1) and (2), and we could remove the A argument
index_ndims(A, indices...) = _index_ndims(indices...)
_index_ndims() = ()
_index_ndims(i1::NIdx{N}, I...) where {N} = (ntuple(x->true, Val(N))..., _index_ndims(I...)...)
_index_ndims(i1, I...) = (true, _index_ndims(I...)...)
if VERSION < v"1.11.0-DEV.1157"
# Arrays of Bool are even more confusing as they're sometimes linear and sometimes not
# Arrays of Bool are even more confusing as they're sometimes linear and sometimes not...
# and worse, it depends upon the _parent_ being indexed into
# This was addressed in Base with JuliaLang/julia#45869.
@inline Base.to_indices(A, I::Tuple{Not{<:AbstractArray{Bool, 1}}}) = to_indices(A, (eachindex(IndexLinear(), A),), I)
@inline Base.to_indices(A, I::Tuple{Not{<:Union{Array{Bool}, BitArray}}}) = to_indices(A, (eachindex(A),), I)
@inline Base.to_indices(A, I::Tuple{Not{<:AbstractArray{Bool, 1}}}) =
to_indices(A, (eachindex(IndexLinear(), A),), I)
@inline Base.to_indices(A, I::Tuple{Not{<:Union{Array{Bool}, BitArray}}}) =
to_indices(A, (IndexStyle(A) isa IndexLinear ? (eachindex(A),) : axes(A)), I)
# This also affects the _number_ of dimensions that these logical indices span, but only
# when it's the only index
index_ndims(A, i1::AbstractArray{Bool, 1}) = (true,)
index_ndims(A, i1::Union{Array{Bool}, BitArray}) =
IndexStyle(A) isa IndexLinear ? (true,) : ntuple(x->true, Val(ndims(i1)))
end

# a cleaner implementation is nt[filter(∉(I.skip), keys(nt))] instead of Base.structdiff, but this would only work on Julia 1.7+
Expand Down
9 changes: 5 additions & 4 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ using InvertedIndices
using Test
using OffsetArrays

@testset "0-d" begin
A = fill(1)
@testset "0-d" for A in (fill(1), view([1], fill(1)), reshape(view([1], 1), ()))
@test A[Not(fill(A.==1))] == []
@test A[Not(CartesianIndex())] == []
@test A[Not(CartesianIndices(()))] == []
@test A[Not(fill(A.==2))] == [1]
A[Not(fill(A.==2))] = fill(0)
@test A[] == 0
Expand All @@ -22,7 +22,7 @@ end
@test @views A[Not(end)] == A[Not(end:end)] == A[Not(A.==13)] == collect(-10:12)
@test A[Not(iseven.(A))] == A[isodd.(A)] == collect(-9:2:13)
@test A[Not([])] == A[collect(1:end)] == collect(-10:13)
@test A[Not(1:end)] == A[Not(:)] == A[[]] == []
@test A[Not(1:end)] == A[Not(CartesianIndices(A))] == A[Not(:)] == A[[]] == []
@test A[Not([1,1,1,2,2])] == A[3:end]
@test A[Not([end,end,end,end-1,end-1])] == A[1:end-2]
@test A[Not(3,2,1)] == A[Not(3,2,3,1,2,1)] == A[4:end]
Expand Down Expand Up @@ -74,6 +74,7 @@ end
@test A[:, Not(2)] == (@view A[:, Not(2)]) == A[:,[1;3:end]]
@test A[Not(2), Not(2)] == (@view A[Not(2), Not(2)]) == A[[1;3:end],[1;3:end]]
R = collect(CartesianIndices(size(A)))
@test A[Not(R)] == A[Not(CartesianIndices(axes(A)))] == []
@test A[Not(first(R))] == (@view A[Not(first(R))]) == A[2:end]
@test A[Not(R[1:2])] == (@view A[Not(R[1:2])]) == A[3:end]
@test A[Not(iseven.(A))] == (@view A[Not(iseven.(A))]) == A[isodd.(A)] == collect(-9:2:13)
Expand All @@ -86,13 +87,13 @@ end
inds = axes(A)
f₁, l₁ = first(inds[1]), last(inds[1])
f₂, l₂ = first(inds[2]), last(inds[2])
# TODO: Re-enable these tests for 3-d after PLI deprecation
if ndims(A) == 2
@test A[Not(f₁+1), f₂:l₂] == (@view A[Not(f₁+1), f₂:l₂]) == A[[f₁,l₁],f₂:l₂]
@test A[f₁:l₁, Not(f₂+1)] == (@view A[f₁:l₁, Not(f₂+1)]) == A[f₁:l₁,[f₂;f₂+2:l₂]]
@test A[Not(f₁+1), Not(f₂+1)] == (@view A[Not(f₁+1), Not(f₂+1)]) == A[[f₁,l₁],[f₂;f₂+2:l₂]]
end
R = collect(CartesianIndices(axes(A)))
@test A[Not(R)] == A[Not(CartesianIndices(axes(A)))] == []
@test A[Not(first(R))] == (@view A[Not(first(R))]) == A[LinearIndices(A)[2:end]]
@test A[Not(R[1:2])] == (@view A[Not(R[1:2])]) == A[LinearIndices(A)[3:end]]
@test A[Not(iseven.(A))] == (@view A[Not(iseven.(A))]) == A[isodd.(A)] == collect(-9:2:13)
Expand Down
Loading