Skip to content

Commit

Permalink
feat: vector helper functions
Browse files Browse the repository at this point in the history
Signed-off-by: Anirudh <[email protected]>
  • Loading branch information
anirudh2 committed Apr 4, 2023
1 parent 529a2f5 commit ad7f787
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SemioticOpt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ using Zygote

abstract type OptAlgorithm end

include("vector.jl")
include("hook/core.jl")
include("hook/stop.jl")
include("hook/postiteration.jl")
Expand Down
18 changes: 18 additions & 0 deletions src/vector.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright 2022-, Semiotic AI, Inc.
# SPDX-License-Identifier: Apache-2.0

export nonzeroixs, klargestixs

"""
nonzeroixs(x::AbstractVector{T}) where {T<:Real}
Returns the indices of the non-zero elements of `x`.
"""
nonzeroixs(x::AbstractVector{T}) where {T<:Real} = findall(!iszero, x)

"""
klargestixs(x::AbstractVector{T}, k::I) where {T<:Real, I<:Integer}
Returns the indices of the `k` largest elements of `x`.
"""
klargestixs(x::AbstractVector{T}, k::I) where {T<:Real, I<:Integer} = partialsortperm(x, 1:k; rev=true)
1 change: 1 addition & 0 deletions test/testgroups
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
vector
hook
project
gradientdescent
Expand Down
12 changes: 12 additions & 0 deletions test/vector.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copyright 2022-, Semiotic AI, Inc.
# SPDX-License-Identifier: Apache-2.0

@testset "vector" begin
@testset "nonzerosixs" begin
@test nonzeroixs([1.0, 0.0, 2.0, 0.0, 3.0]) == [1, 3, 5]
end

@testset "klargestixs" begin
@test klargestixs([1.0, 0.0, 2.0, 0.0, 3.0], 2) == [5, 3]
end
end

0 comments on commit ad7f787

Please sign in to comment.