Skip to content

Commit

Permalink
Fix histogram normalization (#78)
Browse files Browse the repository at this point in the history
* Fix histogram normalization

* get rid of un-needed if/else statements

* Fix tests
  • Loading branch information
chrisjonesBSU authored Feb 8, 2024
1 parent fc6b40f commit dca592a
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
6 changes: 3 additions & 3 deletions cmeutils/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def get_histogram(data, normalize=False, bins="auto", x_range=None):
Array of the bin height values
"""
bin_heights, bin_borders = np.histogram(data, bins=bins, range=x_range)
if normalize is True:
bin_heights = bin_heights / sum(bin_heights)
bin_heights, bin_borders = np.histogram(
a=data, bins=bins, range=x_range, density=normalize
)
bin_widths = np.diff(bin_borders)
bin_centers = bin_borders[:-1] + bin_widths / 2
return bin_centers, bin_heights
Expand Down
3 changes: 3 additions & 0 deletions cmeutils/tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ def test_histogram_normalize(self):
sample = np.random.randn(100) * -1
bin_c, bin_h = get_histogram(sample, normalize=True)
assert all(bin_h <= 1)
bin_width = bin_c[1] - bin_c[0]
area = np.sum(bin_h * bin_width)
assert np.allclose(area, 1.0, atol=1e-3)

def test_3dplot(self):
x = [1, 2, 3, 4, 5]
Expand Down
6 changes: 4 additions & 2 deletions cmeutils/tests/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ def test_bond_dist_normalize(self, p3ht_gsd):
histogram=True,
normalize=True,
)
assert np.allclose(np.sum(bonds_hist[:, 1]), 1, 1e-3)
bin_width = bonds_hist[:, 0][1] - bonds_hist[:, 0][0]
assert np.allclose(np.sum(bonds_hist[:, 1] * bin_width), 1, 1e-3)

def test_bond_range_outside(self, p3ht_gsd):
with pytest.warns(UserWarning):
Expand Down Expand Up @@ -172,7 +173,8 @@ def test_angle_dist_normalize(self, p3ht_gsd):
histogram=True,
normalize=True,
)
assert np.allclose(np.sum(angles_hist[:, 1]), 1, 1e-3)
bin_width = angles_hist[:, 0][1] - angles_hist[:, 0][0]
assert np.allclose(np.sum(angles_hist[:, 1] * bin_width), 1, 1e-3)

def test_angle_range_outside(self, p3ht_gsd):
with pytest.warns(UserWarning):
Expand Down

0 comments on commit dca592a

Please sign in to comment.