Skip to content

Commit d2c3143

Browse files
committed
[Python][Hist] Add TH1.FillN tests
1 parent 65f236f commit d2c3143

File tree

1 file changed

+39
-19
lines changed

1 file changed

+39
-19
lines changed

bindings/pyroot/pythonizations/test/th1_fillN.py

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,59 @@
33
import ROOT
44

55

6-
class FillWithNumpyArray(unittest.TestCase):
6+
class FillWithArrayLike(unittest.TestCase):
77
"""
88
Test for the FillN method of TH1 and subclasses, which fills
9-
the histogram with a numpy array.
9+
the histogram with array-like input.
1010
"""
1111

12-
# Tests
13-
def test_fill(self):
12+
def _run_fill_test(self, data):
1413
import numpy as np
15-
# Create sample data
16-
data = np.array([1., 2, 2, 3, 3, 3, 4, 4, 5])
14+
15+
# Convert once for the reference FillN call
16+
data_np = np.asanyarray(data, dtype=np.float64)
17+
n = len(data_np)
18+
1719
# Create histograms
1820
nbins = 5
19-
min_val = 0
20-
max_val = 10
21-
verbose_hist = ROOT.TH1F("verbose_hist", "verbose_hist", nbins, min_val, max_val)
22-
simple_hist = ROOT.TH1F("simple_hist", "simple_hist", nbins, min_val, max_val)
23-
# Fill histograms
24-
verbose_hist.FillN(len(data), data, np.ones(len(data)))
21+
verbose_hist = ROOT.TH1F("verbose_hist", "verbose_hist", nbins, 0, 10)
22+
simple_hist = ROOT.TH1F("simple_hist", "simple_hist", nbins, 0, 10)
23+
24+
# Test filling without weights
25+
verbose_hist.FillN(n, data_np, np.ones(n))
2526
simple_hist.Fill(data)
26-
# Test if the histograms have the same content
27+
2728
for i in range(nbins):
2829
self.assertAlmostEqual(verbose_hist.GetBinContent(i), simple_hist.GetBinContent(i))
30+
2931
# Test filling with weights
30-
weights = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
31-
verbose_hist.FillN(len(data), data, weights)
32+
weights_np = np.linspace(0.1, 0.9, n)
33+
weights = list(weights_np) # also array-like
34+
35+
verbose_hist.FillN(n, data_np, weights_np)
3236
simple_hist.Fill(data, weights)
37+
3338
for i in range(nbins):
3439
self.assertAlmostEqual(verbose_hist.GetBinContent(i), simple_hist.GetBinContent(i))
35-
# Test filling with weights with a different length
36-
weights = np.array([0.1, 0.2, 0.3, 0.4])
40+
41+
# Test mismatched weight size
3742
with self.assertRaises(ValueError):
38-
simple_hist.Fill(data, weights)
43+
simple_hist.Fill(data, [0.1, 0.2, 0.3]) # too short
44+
45+
# Run with différent inputs
46+
def test_fill_arraylike(self):
47+
import numpy as np
48+
49+
inputs = [
50+
np.array([1.0, 2, 2, 3, 3, 3, 4, 4, 5]), # numpy
51+
[1.0, 2, 2, 3, 3, 3, 4, 4, 5], # list
52+
range(9), # range
53+
]
54+
55+
for input_data in inputs:
56+
with self.subTest(input_type=type(input_data).__name__):
57+
self._run_fill_test(input_data)
58+
3959

40-
if __name__ == '__main__':
60+
if __name__ == "__main__":
4161
unittest.main()

0 commit comments

Comments
 (0)