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

Implement a square root binning function #280

Merged
merged 4 commits into from
Aug 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions becquerel/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,20 @@ def bin_centers_from_edges(edges_kev):
edges_kev = np.array(edges_kev)
centers_kev = (edges_kev[:-1] + edges_kev[1:]) / 2
return centers_kev


def sqrt_bins(bin_edge_min, bin_edge_max, nbins):
"""
Square root binning

Args:
bin_edge_min (float): Minimum bin edge (must be >= 0)
bin_edge_max (float): Maximum bin edge (must be greater than bin_min)
nbins (int): Number of bins

Returns:
np.array of bin edges (length = nbins + 1)
"""
assert bin_edge_min >= 0
assert bin_edge_max > bin_edge_min
return np.linspace(np.sqrt(bin_edge_min), np.sqrt(bin_edge_max), nbins + 1) ** 2
28 changes: 28 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pytest
import numpy as np
import becquerel as bq


# ----------------------------------------------
# Test utils
# ----------------------------------------------


def test_sqrt_bins():
"""Test basic functionality of utils.sqrt_bins."""
edge_min = 0
edge_max = 3000
n_bins = 128
be = bq.utils.sqrt_bins(edge_min, edge_max, n_bins)
bc = (be[1:] + be[:-1]) / 2
bw = np.diff(be)
# compute slope of line
m = np.diff(bw ** 2) / np.diff(bc)
# assert that the square of the bin
assert np.allclose(m[0], m)
# negative edge_min
with pytest.raises(AssertionError):
be = bq.utils.sqrt_bins(-10, edge_max, n_bins)
# edge_max < edge_min
with pytest.raises(AssertionError):
be = bq.utils.sqrt_bins(100, 50, n_bins)