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

add gather(src, IJK...) #449

Merged
merged 3 commits into from
Dec 26, 2022
Merged
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
36 changes: 35 additions & 1 deletion src/gather.jl
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ or multiple `dst` columns.
See [`gather!`](@ref) for an in-place version.

# Examples

```jldoctest
julia> NNlib.gather([1,20,300,4000], [2,4,2])
3-element Vector{Int64}:
Expand Down Expand Up @@ -83,5 +84,38 @@ function rrule(::typeof(gather!), dst::AbstractArray, src::AbstractArray, idx::A
y = gather!(dst, src, idx)
src_size = size(src)
gather!_pullback(Δ) = (NoTangent(), NoTangent(), ∇gather_src(unthunk(Δ), src_size, idx), NoTangent())
y, gather!_pullback
return y, gather!_pullback
end

"""
gather(src, IJK...)

Convert the tuple of integer vectors `IJK` to a tuple of `CartesianIndex` and
call `gather` on it: `gather(src, CartesianIndex.(IJK...))`.

# Examples

```jldoctest
julia> src = reshape([1:15;], 3, 5)
3×5 Matrix{Int64}:
1 4 7 10 13
2 5 8 11 14
3 6 9 12 15

julia> NNlib.gather(src, [1, 2], [2, 4])
2-element Vector{Int64}:
4
11
```
"""
function gather(src::AbstractArray{Tsrc, Nsrc},
I::AbstractVector{<:Integer},
J::AbstractVector{<:Integer},
Ks::AbstractVector{<:Integer}...) where {Nsrc, Tsrc}

return gather(src, to_cartesian_index(I, J, Ks...))
end

to_cartesian_index(IJK...) = CartesianIndex.(IJK...)

@non_differentiable to_cartesian_index(::Any...)
11 changes: 11 additions & 0 deletions test/gather.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,14 @@ end
gradtest(xs -> gather!(dst, xs, index), src)
gradtest(xs -> gather(xs, index), src)
end

@testset "gather(src, IJK...)" begin
x = reshape([1:15;], 3, 5)

y = gather(x, [1,2], [2,4])
@test y == [4, 11]

@test gather(x, [1, 2]) == [1 4
2 5
3 6]
end