Skip to content

Commit 61b5c69

Browse files
authored
fix: wrong calculation for WeightedMean variance NaN's via UHI (#695)
1 parent 8bb66b7 commit 61b5c69

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/boost_histogram/_internal/hist.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1067,11 +1067,12 @@ def variances(self, flow: bool = False) -> Optional["np.typing.NDArray[Any]"]:
10671067
return view if self._variance_known else None
10681068

10691069
if hasattr(view, "sum_of_weights"):
1070+
valid = view.sum_of_weights**2 > view.sum_of_weights_squared # type: ignore[union-attr]
10701071
return np.divide( # type: ignore[no-any-return]
10711072
view.variance, # type: ignore[union-attr]
10721073
view.sum_of_weights, # type: ignore[union-attr]
10731074
out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr]
1074-
where=view.sum_of_weights > 1, # type: ignore[union-attr]
1075+
where=valid,
10751076
)
10761077

10771078
if hasattr(view, "count"):

tests/test_storage.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import math
2+
13
import numpy as np
24
import pytest
35
from numpy.testing import assert_array_equal
@@ -258,3 +260,20 @@ def test_summing_weighted_mean_storage():
258260
assert s1.sum_of_weights == approx(s2.sum_of_weights)
259261
assert s1.sum_of_weights_squared == approx(s2.sum_of_weights_squared)
260262
assert s1.variance == approx(s2.variance)
263+
264+
265+
# Raised on Gitter
266+
def test_UHI_variance_counts():
267+
h = bh.Histogram(
268+
bh.axis.Regular(bins=1, start=0, stop=1), storage=bh.storage.WeightedMean()
269+
)
270+
h.fill(0.5, sample=[1], weight=[0.5])
271+
h.fill(0.5, sample=[2], weight=[0.4])
272+
assert not math.isnan(h.variances()[0])
273+
274+
h = bh.Histogram(
275+
bh.axis.Regular(bins=1, start=0, stop=1), storage=bh.storage.WeightedMean()
276+
)
277+
h.fill(0.5, sample=[1], weight=[0.5])
278+
h.fill(0.5, sample=[1], weight=[0.5])
279+
assert not math.isnan(h.variances()[0])

0 commit comments

Comments
 (0)