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

overload Base.clamp()/Base.clamp!() for clipping histogram bincounts #119

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions src/FHist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,25 @@ for (H, N) in ((:Hist1D, 1), (:Hist2D, 2), (:Hist3D, 3))
binerrors(f::T, h::$H) where T<:Function = f.(sumw2(h))
binerrors(h::$H) = binerrors(sqrt, h)

@doc """
clamp(hist::H, lo_limit, hi_limit) --> new_hist::H
FHist.clamp!(hist, lo_limit, hi_limit) --> hist

Clamp (or called clip) the `bincounts()` of a histogram and return a copy of the histogram. `FHist.clamp!()` is the in-place variation.

!!! note
By construction, the `integral()` of the histogram will also change. Clamping does not change `sumw2` values.
"""
function Base.clamp(h::$H, lo_limit, hi_limit)
newh = deepcopy(h)
return clamp!(newh, lo_limit, hi_limit)
end
function Base.clamp!(h::$H, lo_limit, hi_limit)
bc = bincounts(h)
@. bc = clamp(bc, lo_limit, hi_limit)
return h
end

function Base.:(==)(h1::$H, h2::$H)
bincounts(h1) == bincounts(h2) &&
binedges(h1) == binedges(h2) &&
Expand Down
15 changes: 15 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -612,4 +612,19 @@ end
@test all(significance(h1,h2) .≈ (9.839916447569484, 0.30998654607114046))
end

@testset "Clamping histogram bincounts" begin
bc_1D = [-0.1, 1.0]
h = Hist1D(;binedges=0:2, bincounts=bc_1D, sumw2=[0.1, 0.2])
h2 = Hist1D(;binedges=0:2, bincounts=clamp.(bc_1D, eps(), Inf), sumw2=[0.1, 0.2])
@test clamp(h, eps(), Inf) == h2
@test h2 == clamp!(deepcopy(h), eps(), Inf)

bc_2D = [-0.1 1.0;
-0.2 3.0]
h2d = Hist2D(;binedges=(0:2, 0:2), bincounts=bc_2D)
h2d2 = Hist2D(;binedges=(0:2, 0:2), bincounts=clamp.(bc_2D, eps(), Inf))
@test clamp(h2d, eps(), Inf) == h2d2
@test h2d2 == clamp!(deepcopy(h2d), eps(), Inf)
end

include("hdf5.jl")
Loading