Skip to content

Commit

Permalink
Improve speed of shannon and ginisimpson (#135)
Browse files Browse the repository at this point in the history
This commit improves the speed of `shannon` and `ginisimpsons` by
avoiding creation of temporary arrays. The `shannon` function is also
simplified a little.
  • Loading branch information
barucden authored Aug 19, 2022
1 parent 4779e0e commit ada4530
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/diversity.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ See also [`shannon!`](@ref).
"""
function shannon(v::Union{AbstractVector{T}, AbstractSparseMatrix{T}}) where T<:Real
total = sum(v)
relab = map(x-> x/total, v)
return -sum([log(x^x) for x in relab])
logtotal = log(total)
# The iszero condition is necessary to prevent log(0)
return logtotal - sum(x -> iszero(x) ? x : x * log(x), v) / total
end

function shannon(abt::AbstractAbundanceTable)
Expand Down Expand Up @@ -49,8 +50,7 @@ See also [`ginisimpson!`](@ref).
"""
function ginisimpson(v::Union{AbstractVector{T}, AbstractSparseMatrix{T}}) where T<:Real
total = sum(v)
relab = map(x-> x/total, v)
return 1 - sum([x^2 for x in relab])
return 1 - sum(x -> x^2, v) / (total^2)
end

function ginisimpson(abt::AbstractAbundanceTable)
Expand Down

0 comments on commit ada4530

Please sign in to comment.