From ada453071d3706d835f367fd96acff916b239084 Mon Sep 17 00:00:00 2001 From: Denis Barucic Date: Fri, 19 Aug 2022 16:27:38 +0200 Subject: [PATCH] Improve speed of `shannon` and `ginisimpson` (#135) This commit improves the speed of `shannon` and `ginisimpsons` by avoiding creation of temporary arrays. The `shannon` function is also simplified a little. --- src/diversity.jl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/diversity.jl b/src/diversity.jl index ce033bf..768a242 100644 --- a/src/diversity.jl +++ b/src/diversity.jl @@ -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) @@ -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)