File: test_internal_histogram.py

package info (click to toggle)
python-boost-histogram 1.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,236 kB
  • sloc: python: 7,940; cpp: 3,243; makefile: 22; sh: 1
file content (387 lines) | stat: -rw-r--r-- 10,991 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
from __future__ import annotations

import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal
from pytest import approx

import boost_histogram as bh

methods = (bh.storage.Double, bh.storage.Int64, bh.storage.Unlimited)


@pytest.mark.parametrize("dtype", [np.double, np.int_, np.float32])
def test_noncontig_fill(dtype):
    a = np.array([[0, 0], [1, 1]], dtype=dtype, order="C")
    b = np.array([[0, 0], [1, 1]], dtype=dtype, order="F")

    h1 = bh.Histogram(bh.axis.Regular(10, 0, 2)).fill(a[0])
    h2 = bh.Histogram(bh.axis.Regular(10, 0, 2)).fill(b[0])

    assert h1 == h2


@pytest.mark.parametrize("storage", methods)
def test_1D_fill_int(storage):
    bins = 10
    ranges = (0, 1)

    vals = (0.15, 0.25, 0.25)

    hist = bh.Histogram(bh.axis.Regular(bins, *ranges), storage=storage())
    assert hist.storage_type == storage
    hist.fill(vals)

    H = np.array([0, 1, 2, 0, 0, 0, 0, 0, 0, 0])

    assert_array_equal(np.asarray(hist), H)
    assert_array_equal(hist.view(flow=False), H)
    assert_array_equal(hist.view(flow=True)[1:-1], H)

    assert hist.axes[0].size == bins
    assert hist.axes[0].extent == bins + 2


@pytest.mark.parametrize("storage", methods)
def test_2D_fill_int(storage):
    bins = (10, 15)
    ranges = ((0, 3), (0, 2))

    vals = ((0.15, 0.25, 0.25), (0.35, 0.45, 0.45))

    hist = bh.Histogram(
        bh.axis.Regular(bins[0], *ranges[0]),
        bh.axis.Regular(bins[1], *ranges[1]),
        storage=storage(),
    )
    assert hist.storage_type == storage
    hist.fill(*vals)

    H = np.histogram2d(*vals, bins=bins, range=ranges)[0]

    assert_array_equal(np.asarray(hist), H)
    assert_array_equal(hist.view(flow=True)[1:-1, 1:-1], H)
    assert_array_equal(hist.view(flow=False), H)

    assert hist.axes[0].size == bins[0]
    assert hist.axes[0].extent == bins[0] + 2

    assert hist.axes[1].size == bins[1]
    assert hist.axes[1].extent == bins[1] + 2


def test_edges_histogram():
    edges = (1, 12, 22, 79)
    hist = bh.Histogram(bh.axis.Variable(edges), storage=bh.storage.Int64())

    vals = (13, 15, 24, 29)
    hist.fill(vals)

    bins = np.asarray(hist)
    assert_array_equal(bins, [0, 2, 2])
    assert_array_equal(hist.view(flow=True), [0, 0, 2, 2, 0])
    assert_array_equal(hist.view(flow=False), [0, 2, 2])


def test_int_histogram():
    hist = bh.Histogram(bh.axis.Integer(3, 7), storage=bh.storage.Int64())

    vals = (1, 2, 3, 4, 5, 6, 7, 8, 9)
    hist.fill(vals)

    bins = np.asarray(hist)
    assert_array_equal(bins, [1, 1, 1, 1])
    assert_array_equal(hist.view(flow=False), [1, 1, 1, 1])
    assert_array_equal(hist.view(flow=True), [2, 1, 1, 1, 1, 3])


def test_str_categories_histogram():
    hist = bh.Histogram(
        bh.axis.StrCategory(["a", "b", "c"]), storage=bh.storage.Int64()
    )

    vals = ["a", "b", "b", "c"]

    hist.fill(vals)

    assert hist[bh.loc("a")] == 1
    assert hist[bh.loc("b")] == 2
    assert hist[bh.loc("c")] == 1


# Issue 715


def test_select_many():
    hist = bh.Histogram(
        bh.axis.StrCategory(["a", "b"]),
        bh.axis.StrCategory(["x", "y", "z"]),
        bh.axis.Regular(10, 0, 1),
    )

    pick_a = hist[bh.loc("a"), ...]
    with pytest.warns(UserWarning, match="List indexing selection is experimental"):
        pick_b = pick_a[[bh.loc("x"), bh.loc("y")], ...]

    with pytest.warns(UserWarning, match="List indexing selection is experimental"):
        pick = hist[bh.loc("a"), [bh.loc("x"), bh.loc("y")], ...]

    assert pick_b.axes[0] == pick.axes[0]
    assert len(pick_b.axes) == len(pick.axes)


def test_growing_histogram():
    hist = bh.Histogram(
        bh.axis.Regular(10, 0, 1, growth=True), storage=bh.storage.Int64()
    )

    hist.fill(1.45)

    assert hist.size == 17


def test_numpy_dd():
    h = bh.Histogram(
        bh.axis.Regular(10, 0, 1), bh.axis.Regular(5, 0, 1), storage=bh.storage.Int64()
    )

    for i in range(10):
        for j in range(5):
            x, y = h.axes[0].centers[i], h.axes[1].centers[j]
            v = i + j * 10 + 1
            h.fill([x] * v, [y] * v)

    h2, x2, y2 = h.to_numpy()
    h1, (x1, y1) = h.to_numpy(dd=True)

    assert_array_equal(h1, h2)
    assert_array_equal(x1, x2)
    assert_array_equal(y1, y2)


def test_numpy_weights():
    h = bh.Histogram(
        bh.axis.Regular(10, 0, 1), bh.axis.Regular(5, 0, 1), storage=bh.storage.Weight()
    )

    for i in range(10):
        for j in range(5):
            x, y = h.axes[0].centers[i], h.axes[1].centers[j]
            v = i + j * 10 + 1
            h.fill([x] * v, [y] * v)

    h2, x2, y2 = h.to_numpy(view=False)
    h1, (x1, y1) = h.to_numpy(dd=True, view=False)

    assert_array_equal(h1, h2)
    assert_array_equal(x1, x2)
    assert_array_equal(y1, y2)

    h1, (x1, y1) = h.to_numpy(dd=True, view=False)
    h2, x2, y2 = h.to_numpy(view=True)

    assert_array_equal(h1, h2.value)
    assert_array_equal(x1, x2)
    assert_array_equal(y1, y2)


def test_numpy_flow():
    h = bh.Histogram(
        bh.axis.Regular(10, 0, 1), bh.axis.Regular(5, 0, 1), storage=bh.storage.Int64()
    )

    for i in range(10):
        for j in range(5):
            x, y = h.axes[0].centers[i], h.axes[1].centers[j]
            v = i + j * 10 + 1
            h.fill([x] * v, [y] * v)

    flow_true = h.to_numpy(True)[0][1:-1, 1:-1]
    flow_false = h.to_numpy(False)[0]

    assert_array_equal(flow_true, flow_false)

    view_flow_true = h.view(flow=True)
    view_flow_false = h.view(flow=False)
    view_flow_default = h.view()

    assert_array_equal(view_flow_true[1:-1, 1:-1], view_flow_false)
    assert_array_equal(view_flow_default, view_flow_false)


def test_numpy_compare():
    h = bh.Histogram(
        bh.axis.Regular(10, 0, 1), bh.axis.Regular(5, 0, 1), storage=bh.storage.Int64()
    )

    xs = []
    ys = []
    for i in range(10):
        for j in range(5):
            x, y = h.axes[0].centers[i], h.axes[1].centers[j]
            v = i + j * 10 + 1
            xs += [x] * v
            ys += [y] * v

    h.fill(xs, ys)

    H, E1, E2 = h.to_numpy()

    nH, nE1, nE2 = np.histogram2d(xs, ys, bins=(10, 5), range=((0, 1), (0, 1)))

    assert_array_equal(H, nH)
    assert_allclose(E1, nE1)
    assert_allclose(E2, nE2)


def test_project():
    h = bh.Histogram(
        bh.axis.Regular(10, 0, 1), bh.axis.Regular(5, 0, 1), storage=bh.storage.Int64()
    )
    h0 = bh.Histogram(bh.axis.Regular(10, 0, 1), storage=bh.storage.Int64())
    h1 = bh.Histogram(bh.axis.Regular(5, 0, 1), storage=bh.storage.Int64())

    for x, y in (
        (0.3, 0.3),
        (0.7, 0.7),
        (0.5, 0.6),
        (0.23, 0.92),
        (0.15, 0.32),
        (0.43, 0.54),
    ):
        h.fill(x, y)
        h0.fill(x)
        h1.fill(y)

    assert h.project(0, 1) == h
    assert h.project(0) == h0
    assert h.project(1) == h1

    assert_array_equal(h.project(0, 1), h)
    assert_array_equal(h.project(0), h0)
    assert_array_equal(h.project(1), h1)


def test_sums():
    h = bh.Histogram(bh.axis.Regular(4, 0, 1))
    h.fill([0.1, 0.2, 0.3, 10])

    assert h.sum() == 3
    assert h.sum(flow=True) == 4


def test_int_cat_hist():
    h = bh.Histogram(bh.axis.IntCategory([1, 2, 3]), storage=bh.storage.Int64())

    h.fill(1)
    h.fill(2)
    h.fill(3)

    assert_array_equal(h.view(), [1, 1, 1])
    assert h.sum() == 3

    with pytest.raises(TypeError):
        h.fill(0.5)


@pytest.mark.filterwarnings("ignore:List indexing selection is experimental")
def test_int_cat_hist_pick_several():
    h = bh.Histogram(
        bh.axis.IntCategory([1, 2, 7], __dict__={"xval": 5}), storage=bh.storage.Int64()
    )

    h.fill(1, weight=8)
    h.fill(2, weight=7)
    h.fill(7, weight=6)

    assert h.view() == approx(np.array([8, 7, 6]))
    assert h.sum() == 21

    assert h[[0, 2]].values() == approx(np.array([8, 6]))
    assert h[[2, 0]].values() == approx(np.array([6, 8]))
    assert h[[1]].values() == approx(np.array([7]))

    assert h[[bh.loc(1), bh.loc(7)]].values() == approx(np.array([8, 6]))
    assert h[[bh.loc(7), bh.loc(1)]].values() == approx(np.array([6, 8]))
    assert h[[bh.loc(2)]].values() == approx(np.array([7]))

    assert tuple(h[[0, 2]].axes[0]) == (1, 7)
    assert tuple(h[[2, 0]].axes[0]) == (7, 1)
    assert tuple(h[[1]].axes[0]) == (2,)

    assert h.axes[0].xval == 5
    assert h[[0]].axes[0].xval == 5
    assert h[[0, 1, 2]].axes[0].xval == 5


@pytest.mark.filterwarnings("ignore:List indexing selection is experimental")
def test_str_cat_pick_several():
    h = bh.Histogram(bh.axis.StrCategory(["a", "b", "c"]))

    h.fill(["a", "a", "a", "b", "b", "c"], weight=0.25)

    assert h[[0, 1, 2]].values() == approx(np.array([0.75, 0.5, 0.25]))
    assert h[[2, 1, 0]].values() == approx(np.array([0.25, 0.5, 0.75]))
    assert h[[1, 0]].values() == approx(np.array([0.5, 0.75]))

    assert h[[bh.loc("a"), bh.loc("b"), bh.loc("c")]].values() == approx(
        np.array([0.75, 0.5, 0.25])
    )
    assert h[[bh.loc("c"), bh.loc("b"), bh.loc("a")]].values() == approx(
        np.array([0.25, 0.5, 0.75])
    )
    assert h[[bh.loc("b"), bh.loc("a")]].values() == approx(np.array([0.5, 0.75]))

    assert tuple(h[[1, 0]].axes[0]) == ("b", "a")


@pytest.mark.filterwarnings("ignore:List indexing selection is experimental")
def test_pick_invalid():
    h = bh.Histogram(bh.axis.Regular(10, 0, 1))
    with pytest.raises(RuntimeError):
        h[[0, 1]]

    h = bh.Histogram(bh.axis.Integer(0, 10))
    with pytest.raises(RuntimeError):
        h[[0, 1]]


@pytest.mark.filterwarnings("ignore:List indexing selection is experimental")
def test_str_cat_pick_dual():
    h = bh.Histogram(
        bh.axis.StrCategory(["a", "b", "c"]), bh.axis.StrCategory(["d", "e", "f"])
    )
    vals = np.arange(9).reshape(3, 3)
    h.values()[...] = vals

    assert h[[0], [0]].values() == approx(vals[[0]][:, [0]])
    assert h[[1], [2]].values() == approx(vals[[1]][:, [2]])
    assert h[[1], [0, 1]].values() == approx(vals[[1]][:, [0, 1]])
    assert h[[0, 1], [1]].values() == approx(vals[[0, 1]][:, [1]])
    assert h[[0, 1], [0, 1]].values() == approx(vals[[0, 1]][:, [0, 1]])
    assert h[[0, 1], [2, 1]].values() == approx(vals[[0, 1]][:, [2, 1]])


@pytest.mark.filterwarnings("ignore:List indexing selection is experimental")
def test_pick_multiaxis():
    h = bh.Histogram(
        bh.axis.StrCategory(["a", "b", "c"]),
        bh.axis.IntCategory([-5, 0, 10]),
        bh.axis.Regular(5, 0, 1),
        bh.axis.StrCategory(["d", "e", "f"]),
        storage=bh.storage.Int64(),
    )

    h.fill("b", -5, 0.65, "f")
    h.fill("b", -5, 0.65, "e")

    mini = h[[bh.loc("b"), 2], [1, bh.loc(-5)], sum, bh.loc("f")]

    assert mini.ndim == 2
    assert tuple(mini.axes[0]) == ("b", "c")
    assert tuple(mini.axes[1]) == (0, -5)

    assert h[[1, 2], [0, 1], sum, bh.loc("f")].sum() == 1
    assert h[[1, 2], [1, 0], sum, bh.loc("f")].sum() == 1

    assert mini.values() == approx(np.array(((0, 1), (0, 0))))