Skip to content

Commit

Permalink
Add :percentage normalization mode for hist
Browse files Browse the repository at this point in the history
  • Loading branch information
rgivry committed Oct 18, 2024
1 parent 74ef7f0 commit 63375a0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/hist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -475,11 +475,12 @@ arrays appropriately. See description of `normalize` for details. Returns `h`.

if mode == :none
# nothing to do
elseif mode == :pdf || mode == :density || mode == :probability
elseif mode == :pdf || mode == :density || mode == :probability || mode == :percentage
if h.isdensity
if mode == :pdf || mode == :probability
if mode == :pdf || mode == :probability || mode == :percentage
# histogram already represents a density, just divide weights by norm
s = 1/norm(h)
multiplier = mode == :percentage ? 100.0 : 1.0
s = 1 / norm(h) * multiplier
weights .*= s
for A in aux_weights
A .*= s
Expand All @@ -502,7 +503,8 @@ arrays appropriately. See description of `normalize` for details. Returns `h`.
else
# :probability - divide weights by sum of weights
nf = inv(sum(weights))
weights .*= nf
multiplier = mode == :percentage ? 100.0 : 1.0
weights .*= nf * multiplier
for A in aux_weights
A .*= nf
end
Expand Down Expand Up @@ -531,7 +533,8 @@ Valid values for `mode` are:
* `:probability`: Normalize by sum of weights only. Resulting histogram
represents the fraction of probability mass for each bin and does not have
norm 1.
* `:none`: Leaves histogram unchanged. Useful to simplify code that has to
* `:percentage`: Normalize as a percentage of the sum of weights.
* `:none`: Leaves histogram unchanged. Useful to simplify code that has to
conditionally apply different modes of normalization.
Successive application of both `:probability` and `:density` normalization (in
Expand Down
2 changes: 2 additions & 0 deletions test/hist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,15 @@ end
@test normalize(h_density, mode = :pdf).weights h_pdf.weights
@test normalize(h_density, mode = :density) == h_density
@test normalize(h_density, mode = :probability).weights h_pdf.weights
@test normalize(h_density, mode = :percentage).weights h_pdf.weights * 100

h_fraction = normalize(h, mode = :probability)
@test sum(h_fraction.weights) 1
@test h_fraction.isdensity == false
@test normalize(h_fraction, mode = :pdf).weights h_pdf.weights
@test normalize(h_fraction, mode = :density).weights h_pdf.weights
@test normalize(h_fraction, mode = :probability).weights h_fraction.weights
@test normalize(h_fraction, mode = :percentage).weights h_fraction.weights * 100

h_copy = deepcopy(float(h))
@test @inferred(normalize!(h_copy, mode = :density)) == h_copy
Expand Down

0 comments on commit 63375a0

Please sign in to comment.