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
Ejemplo n.º 2
0
    def test_double(self):
        h = (
            Hist.new.Reg(10, 0, 1, name="x")
            .Reg(10, 0, 1, name="y")
            .Double()
            .fill(x=[0.5, 0.5], y=[0.2, 0.6])
        )

        assert h[0.5j, 0.2j] == 1
        assert h[bh.loc(0.5), bh.loc(0.6)] == 1
        assert isinstance(h[0.5j, 0.5j], float)

        # add storage to existing storage
        with pytest.raises(Exception):
            h.Double()

        assert (
            Hist(axis.Regular(10, 0, 1, name="x"), "double")._storage_type
            == storage.Double
        )
        assert (
            Hist(axis.Regular(10, 0, 1, name="x"), storage="DouBle")._storage_type
            == storage.Double
        )
        assert (
            Hist(axis.Regular(10, 0, 1, name="x"), storage.Double())._storage_type
            == storage.Double
        )
Ejemplo n.º 3
0
def test_named_access():
    """
    Test named access -- whether NamedHist bins can be accessed.
    """

    h = NamedHist(axis.Regular(10, -5, 5, name="X", label="x [units]")).fill(
        X=np.random.normal(size=1000)
    )

    assert h[6] == h[bh.loc(1)] == h[1j] == h[0j + 1] == h[-3j + 4] == h[bh.loc(1, 0)]
    h[6] = h[bh.loc(1)] = h[1j] = h[0j + 1] = h[-3j + 4] = h[bh.loc(1, 0)] = 0

    h = NamedHist(
        axis.Regular(50, -5, 5, name="Norm", label="normal distribution"),
        axis.Regular(50, -5, 5, name="Unif", label="uniform distribution"),
        axis.StrCategory(["hi", "hello"], name="Greet"),
        axis.Boolean(name="Yes"),
        axis.Integer(0, 1000, name="Int"),
    ).fill(
        Norm=np.random.normal(size=1000),
        Unif=np.random.uniform(size=1000),
        Greet=["hi"] * 800 + ["hello"] * 200,
        Yes=[True] * 600 + [False] * 400,
        Int=np.ones(1000),
    )

    assert h[0j, -0j + 2, "hi", True, 1]

    # mismatch dimension
    with pytest.raises(Exception):
        h[0j, -0j + 2, "hi", True]
Ejemplo n.º 4
0
def test_bool_axis():
    '''
        Test bool axis -- whether Bool is enabled and work properly.\
        As our bool axis is derived from boost-histogram.axis.Regular,\
        we won't test all thoses features. If it is justified as the\
        subclass of boost-histogram.axis.Regular, then it should pass\
        those axis tests.
    '''

    # Test bool axis
    assert isinstance(hist.axis.Bool(name="B"), bh.axis.Regular)

    # Test histograms with bool axes
    h = hist.NamedHist(hist.axis.Bool(name="S"), hist.axis.Bool(name="L"))

    valid_s = [True, True, True, False]
    valid_l = [True, True, False, False]
    h.fill(L=valid_l, S=valid_s)
    assert h[0, 0] == 1
    assert h[1, 0] == 1
    assert h[1, 1] == 2

    s_valid_only = h[{'S': bh.loc(True)}]
    assert s_valid_only[0] == 1
    assert s_valid_only[1] == 2

    l_valid_only = h[{'L': bh.loc(True)}]
    assert l_valid_only[0] == 0
    assert l_valid_only[1] == 2
Ejemplo n.º 5
0
def test_shrink_1d():
    h = bh.Histogram(bh.axis.Regular(20, 1, 5))
    h.fill(1.1)
    hs = h[{0: slice(bh.loc(1), bh.loc(2))}]
    assert_array_equal(hs.view(), [1, 0, 0, 0, 0])

    d = OrderedDict({0: slice(bh.loc(1), bh.loc(2))})
    hs = h[d]
    assert_array_equal(hs.view(), [1, 0, 0, 0, 0])
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
Ejemplo n.º 7
0
    def test_double(self):
        h = (NamedHist.new.Reg(10, 0, 1, name="x").Reg(
            10, 0, 1, name="y").Double().fill(x=[0.5, 0.5], y=[0.2, 0.6]))

        assert h[0.5j, 0.2j] == 1
        assert h[bh.loc(0.5), bh.loc(0.6)] == 1
        assert isinstance(h[0.5j, 0.5j], float)

        # add storage to existing storage
        with pytest.raises(Exception):
            h.Double()
def test_get_1D_slice():
    h1 = bh.Histogram(bh.axis.Regular(10, 0, 1))
    h2 = bh.Histogram(bh.axis.Regular(5, 0, 0.5))
    h1.fill([0.25, 0.25, 0.25, 0.15])
    h2.fill([0.25, 0.25, 0.25, 0.15])

    assert h1 != h2
    assert h1[:5] == h2
    assert h1[:bh.loc(0.5)] == h2
    assert h1[2:4] == h2[2:4]
    assert h1[bh.loc(0.2):bh.loc(0.4)] == h2[bh.loc(0.2):bh.loc(0.4)]

    assert len(h1[2:4].view()) == 2
    assert len(h1[2:4:bh.rebin(2)].view()) == 1
Ejemplo n.º 9
0
 def _hist_to_result(
         hist: bh.Histogram,
         nanto: Optional[float] = None) -> "BootstrapEfficiency.Histogram":
     numerator = cast(bh.Histogram, hist[bh.loc(1), ...])  # type: ignore
     notselected = cast(bh.Histogram, hist[bh.loc(0), ...])  # type: ignore
     denominator = numerator + notselected
     ratio = numerator / denominator
     if nanto is not None:
         np.nan_to_num(ratio.view(),
                       copy=False,
                       nan=nanto,
                       posinf=nanto,
                       neginf=nanto)
     return BootstrapEfficiency.Histogram(numerator, denominator, ratio)
def test_repr():
    assert repr(bh.loc(2)) == "loc(2)"
    assert repr(bh.loc(3) + 1) == "loc(3) + 1"
    assert repr(bh.loc(1) - 2) == "loc(1) - 2"

    assert repr(bh.underflow) == "underflow"
    assert repr(bh.underflow + 1) == "underflow + 1"
    assert repr(bh.underflow - 1) == "underflow - 1"

    assert repr(bh.overflow) == "overflow"
    assert repr(bh.overflow + 1) == "overflow + 1"
    assert repr(bh.overflow - 1) == "overflow - 1"

    assert repr(bh.rebin(2)) == "rebin(2)"
Ejemplo n.º 11
0
def test_general_index_access():
    """
    Test general index access -- whether Hist can be accessed by index.
    """

    h = Hist(
        axis.Regular(10, -5, 5, name="Ones"),
        axis.Regular(10, -5, 5, name="Twos"),
        axis.StrCategory(["hi", "hello"], name="Greet"),
        axis.Boolean(name="Yes"),
        axis.Integer(0, 10, name="Int"),
    ).fill(
        np.ones(10),
        np.ones(10) * 2,
        ["hi"] * 8 + ["hello"] * 2,
        [True] * 6 + [False] * 4,
        np.ones(10),
    )

    assert h[1j, 2j, "hi", True, 1] == 6
    assert h[{0: 6, 1: 7, 2: bh.loc("hi"), 3: bh.loc(True), 4: bh.loc(1)}] == 6
    assert h[0j + 1, -2j + 4, "hi", True, 1] == 6
    assert (h[{
        "Greet": "hi",
        "Ones": bh.loc(1, 0),
        1: bh.loc(3, -1),
        3: True,
        "Int": 1
    }] == 6)

    assert h[0:10:2j, 0:5:5j, "hello", False, 5]
    assert len(h[::2j, 0:5, :, :, :].axes[1]) == 5
    assert len(h[:, 0:5, :, :, :].axes[1]) == 5

    # wrong loc shortcut
    with pytest.raises(Exception):
        h[0.5, 1 / 2, "hi", True, 1]

    with pytest.raises(Exception):
        h[0.5 + 1j, 1 / 2 + 1j, "hi", True, 1]

    # wrong rebin shortcut
    with pytest.raises(Exception):
        h[0:10:0.2j, 0:5:0.5j, "hello", False, 5]

    with pytest.raises(Exception):
        h[0:10:1 + 2j, 0:5:1 + 5j, "hello", False, 5]

    with pytest.raises(Exception):
        h[0:10:20j, 0:5:10j, "hello", False, 5]
Ejemplo n.º 12
0
def test_np_scalars():
    hist = bh.Histogram(
        bh.axis.Regular(30, 1, 500, transform=bh.axis.transform.log))
    hist.fill([7, 7])

    hist2 = hist / np.float64(2.0)
    assert hist2[bh.loc(7)] == 1.0

    hist2 = hist / hist.axes.widths.prod(axis=0)
    assert hist2[bh.loc(7)] == approx(1.3467513416439476)

    with pytest.raises(ValueError):
        hist / np.array([1, 2, 3])

    hist /= np.float64(2.0)
    assert hist[bh.loc(7)] == 1.0
Ejemplo n.º 13
0
def test_basic_usage():

    # Check hist with only one axis
    h = Hist(axis.Regular(10, 0, 1))

    h.fill([0.35, 0.35, 0.45])

    assert h[2] == 0
    assert h[3] == 2
    assert h[4] == 1
    assert h[5] == 0

    # Check hist with two axes
    h = Hist(axis.Regular(10, 0, 1), axis.Regular(10, 0, 1))

    h.fill([0.35, 0.35, 0.45], [0.65, 0.65, 0.85])

    assert h[3, 6] == 2
    assert h[4, 8] == 1
    assert h[3, 5] == 0

    # Checking hist with axis type bool
    h = Hist(axis.bool())

    h.fill([0, 1, 1])

    assert h[0] == 1
    assert h[1] == 2

    # check if there are exactly two bins (accessing h[2] raises IndexError)
    with pytest.raises(IndexError):
        assert h[2] == 0

    # check if flow is disabled (if view() with or without flow gives the same output)
    assert (h.view() == h.view(flow=True)).all()

    h = Hist(axis.Regular(10, 0, 1), axis.Regular(10, 0, 1))

    h.fill([0.35, 0.35, 0.45], [0.65, 0.65, 0.85])

    # Check indexing using dict and bh.loc()
    h2 = h[loc(0.35), :]

    # Broken in 0.6.2, fixed now
    h3 = h[{0: loc(0.35)}]

    assert (h2.view() == h3.view()).all()
Ejemplo n.º 14
0
    def fitSliceY(self,
                  ax=None,
                  num_slices: int = 10,
                  NSIMA: int = 3,
                  fit_range=None,
                  center: bool = False,
                  params=None,
                  plot: bool = True):
        if not ax:
            ax = plt.gca()
        if fit_range:
            slices = np.linspace(*fit_range, num_slices)
        else:
            slices = np.linspace(np.min(self.hist.axes[1]),
                                 np.max(self.hist.axes[1]), num_slices)
        width = np.abs(slices[0] - slices[1])
        outs = []
        ys = []
        xst = []
        xsb = []
        for sl in slices[:-1]:
            y_val = (sl + sl + width) / 2
            try:
                slic = self.hist[:, bh.loc(sl):bh.loc(sl + width):bh.sum]
            except ValueError:
                continue

            temp_hist = Hist1D(boost_hist=slic)
            if center:
                params = GaussianModel().make_params()
                params['center'].set(value=0, min=-0.5, max=0.5)
                params['sigma'].set(value=0.1, min=0, max=1.0)

            try:
                out = temp_hist.fitGaussian(plots=False, params=params)
                outs.append(out)
                ys.append(y_val)
                xst.append(out.params['center'] + NSIMA * out.params['sigma'])
                xsb.append(out.params['center'] - NSIMA * out.params['sigma'])

            except TypeError:
                print(f"Cannot fit from [{sl}, {sl + width}]")
                continue
        left = Scatter(np.array(xst), np.array(ys))
        right = Scatter(np.array(xsb), np.array(ys))
        return outs, left, right
def test_2D_get_bin():

    h = bh.Histogram(bh.axis.Regular(10, 0, 0.99),
                     bh.axis.Regular(10, 0, 0.99))
    h.fill(0.15, [0.25, 0.25, 0.25, 0.15])

    assert h[0, 0] == 0
    assert h[0, 1] == 0
    assert h[1, 1] == 1
    assert h[1, 2] == 3
    assert h[bh.loc(0.1), bh.loc(0.2)] == 3
    assert h[bh.loc(0) + 1, bh.loc(0.3) - 1] == 3

    assert h.view()[1, 2] == h[1, 2]

    with pytest.raises(IndexError):
        h[1]
Ejemplo n.º 16
0
def test_metadata_add():
    h1 = bh.Histogram(bh.axis.IntCategory([1, 2, 3]),
                      bh.axis.StrCategory(["1", "2", "3"]))
    h2 = bh.Histogram(bh.axis.IntCategory([1, 2, 3]),
                      bh.axis.StrCategory(["1", "2", "3"]))
    h1.fill([1, 2, 1, 2], ["1", "1", "2", "2"])
    h2.fill([2, 3, 2, 3], ["2", "2", "3", "3"])

    h3 = h1 + h2

    assert h1.axes[0].size == 3
    assert h2.axes[0].size == 3
    assert h3.axes[0].size == 3

    assert h1.axes[1].size == 3
    assert h2.axes[1].size == 3
    assert h3.axes[1].size == 3

    assert h3[bh.loc(2), bh.loc("2")] == 2.0
Ejemplo n.º 17
0
def test_setting(storage):
    h = bh.Histogram(bh.axis.Regular(10, 0, 1), storage=storage())
    h[bh.underflow] = 1
    h[0] = 2
    h[1] = 3
    h[bh.loc(0.55)] = 4
    h[-1] = 5
    h[bh.overflow] = 6

    assert h[bh.underflow] == 1
    assert h[0] == 2
    assert h[1] == 3
    assert h[bh.loc(0.55)] == 4
    assert h[5] == 4
    assert h[-1] == 5
    assert h[9] == 5
    assert h[bh.overflow] == 6

    assert_array_equal(h.view(flow=True), [1, 2, 3, 0, 0, 0, 4, 0, 0, 0, 5, 6])
Ejemplo n.º 18
0
def test_grow_and_add():
    h1 = bh.Histogram(bh.axis.IntCategory([], growth=True),
                      bh.axis.StrCategory([], growth=True))
    h2 = bh.Histogram(bh.axis.IntCategory([], growth=True),
                      bh.axis.StrCategory([], growth=True))
    h1.fill([1, 2, 1, 2], ["hi", "hi", "ho", "ho"])
    h2.fill([2, 3, 4, 5], ["ho", "ho", "hum", "hum"])

    h3 = h1 + h2

    assert h1.axes[0].size == 2
    assert h2.axes[0].size == 4
    assert h3.axes[0].size == 5

    assert h1.axes[1].size == 2
    assert h2.axes[1].size == 2
    assert h3.axes[1].size == 3

    assert h3[bh.loc(2), bh.loc("ho")] == 2.0
Ejemplo n.º 19
0
    def slice_to_xy(self, slice_range, density: bool = True):
        """Return the x, y values from a histogram in the range
        Useful for plotting in different ways and for fitting

        Args:
            slice_range (Required) : Range to return x, y slice from
            density (bool, optional): Choose to plot y values or density of y values. Defaults to True.

        Returns:
            Tuple(x, y): Returns a tuple of np arrays for x and y values of histogram
        """
        slic = self.hist[bh.loc(slice_range[0]):bh.loc(slice_range[1])]

        x = slic.axes[0].centers
        if density:
            y = slic.view() / np.max(slic.view())
        else:
            y = slic.view()

        return (x, y)
Ejemplo n.º 20
0
    def _loc_shortcut(self, x: Any) -> Any:
        """
        Convert some specific indices to location.
        """

        if isinstance(x, slice):
            return slice(
                self._loc_shortcut(x.start),
                self._loc_shortcut(x.stop),
                self._step_shortcut(x.step),
            )
        elif isinstance(x, complex):
            if x.real % 1 != 0:
                raise ValueError("The real part should be an integer")
            else:
                return bh.loc(x.imag, int(x.real))
        elif isinstance(x, str):
            return bh.loc(x)
        else:
            return x
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))))
Ejemplo n.º 22
0
def test_pick_int_category():
    noflow = dict(underflow=False, overflow=False)

    h = bh.Histogram(
        bh.axis.Regular(10, 0, 10),
        bh.axis.Regular(10, 0, 10, **noflow),
        bh.axis.IntCategory([3, 5, 7, 12, 13]),
    )

    vals = np.arange(100).reshape(10, 10)
    h[:, :, bh.loc(3)] = vals
    h[:, :, bh.loc(5)] = vals + 1
    h[:, :, 3] = vals + 100

    assert h[0, 1, bh.loc(3)] == 1
    assert h[1, 0, bh.loc(5)] == 10 + 1
    assert h[1, 1, bh.loc(5)] == 11 + 1
    assert h[3, 4, bh.loc(7)] == 0
    assert h[3, 4, bh.loc(12)] == 134

    assert_array_equal(h[:, :, bh.loc(3)].view(), vals)
    assert_array_equal(h[:, :, bh.loc(5)].view(), vals + 1)
    assert_array_equal(h[:, :, bh.loc(7)].view(), 0)
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")
def test_string_requirement():
    h = bh.Histogram(
        bh.axis.Integer(0, 10),
        bh.axis.StrCategory(["1", "a", "hello"]),
        storage=bh.storage.Int64(),
    )

    with pytest.raises(TypeError):
        h[bh.loc("1"), bh.loc(1)]

    with pytest.raises(TypeError):
        h[bh.loc(1), bh.loc(1)]

    with pytest.raises(TypeError):
        h[bh.loc("1"), bh.loc("1")]

    assert h[bh.loc(1), bh.loc("1")] == 0
Ejemplo n.º 25
0
def test_boost_histogram(selenium):
    import unittest

    import boost_histogram as bh

    h = bh.Histogram(bh.axis.Integer(0, 10))
    h.fill([1, 1, 1, 14])
    assert h[bh.underflow] == 0
    assert h[bh.loc(0)] == 0
    assert h[bh.loc(1)] == 3
    assert h[bh.overflow] == 1

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

    h = bh.Histogram(bh.axis.Regular(10, 0, 10), bh.axis.Boolean())
    assert len(h.axes[0]) == 10
    assert len(h.axes[1]) == 2

    h.fill([0.5, 0.5, 3.5], [True, False, True])
    assert h[sum, bh.loc(True)] == 2
    assert h[sum, bh.loc(False)] == 1
    assert h[0, sum] == 2
    assert h[0, bh.loc(True)] == 1

    h = bh.Histogram(bh.axis.StrCategory([], growth=True))
    h.fill("fear leads to anger anger leads to hate hate leads to suffering".
           split())

    assert h[bh.loc("fear")] == 1
    assert h[bh.loc("anger")] == 2
    assert h[bh.loc("hate")] == 2
    assert h[bh.loc("to")] == 3

    # Test exception handling
    mean = bh.accumulators.Mean()

    with unittest.TestCase().assertRaises(KeyError):
        mean["invalid"]
Ejemplo n.º 26
0
def test_basic_usage():
    '''
        Test basic usage -- whether NamedHist are properly derived from\
        boost-histogram and whether it can be filled by names.
    '''

    # Test normal NamedHist
    h = NamedHist(axis.Regular(10, 0, 1, name="x"))
    h.fill(x=[0.35, 0.35, 0.45])

    assert h[2] == 0
    assert h[3] == 2
    assert h[4] == 1
    assert h[5] == 0

    assert h[{0: 2}] == 0
    assert h[{0: 3}] == 2
    assert h[{0: 4}] == 1
    assert h[{0: 5}] == 0

    assert h[{'x': 2}] == 0
    assert h[{'x': 3}] == 2
    assert h[{'x': 4}] == 1
    assert h[{'x': 5}] == 0

    # Test multi-axis NamedHist
    h = NamedHist(axis.Regular(10, 0, 1, name="x"),
                  axis.Regular(10, 0, 1, name="y"), axis.Integer(0,
                                                                 2,
                                                                 name="z"))

    h.fill(x=[0.35, 0.35, 0.35, 0.45, 0.55, 0.55, 0.55],
           y=[0.35, 0.35, 0.45, 0.45, 0.45, 0.45, 0.45],
           z=[0, 0, 1, 1, 1, 1, 1])

    z_one_only = h[{'z': bh.loc(1)}]
    assert z_one_only[{'x': 3, 'y': 4}] == 1
    assert z_one_only[{'x': 4, 'y': 4}] == 1
    assert z_one_only[{'x': 5, 'y': 4}] == 3
    assert z_one_only[{'x': 5, 'y': 5}] == 0
    assert z_one_only[{'x': 6, 'y': 5}] == 0

    assert z_one_only[3, 4] == 1
    assert z_one_only[4, 4] == 1
    assert z_one_only[5, 4] == 3
    assert z_one_only[5, 5] == 0
    assert z_one_only[6, 5] == 0
Ejemplo n.º 27
0
    def sort(
        self: T,
        axis: int | str,
        key: (Callable[[int], SupportsLessThan]
              | Callable[[str], SupportsLessThan] | None) = None,
        reverse: bool = False,
    ) -> T:
        """
        Sort a categorical axis.
        """

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            sorted_cats = sorted(self.axes[axis], key=key, reverse=reverse)
            # This can only return T, not float, etc., so we ignore the extra types here
            return self[{
                axis: [bh.loc(x) for x in sorted_cats]
            }]  # type: ignore[dict-item, return-value]
def test_pick_str_category():
    noflow = dict(underflow=False, overflow=False)

    h = bh.Histogram(
        bh.axis.Regular(10, 0, 10),
        bh.axis.Regular(10, 0, 10, **noflow),
        bh.axis.StrCategory(["on", "off", "maybe"]),
    )

    vals = np.arange(100).reshape(10, 10)
    h[:, :, bh.loc("on")] = vals

    assert h[0, 1, bh.loc("on")] == 1
    assert h[1, 0, bh.loc("on")] == 10
    assert h[1, 1, bh.loc("on")] == 11
    assert h[3, 4, bh.loc("maybe")] == 0

    assert_array_equal(h[:, :, bh.loc("on")].view(), vals)
    assert_array_equal(h[{2: bh.loc("on")}].view(), vals)
    assert_array_equal(h[:, :, bh.loc("off")].view(), 0)
def test_one_sided_slice():
    h = bh.Histogram(bh.axis.Regular(4, 1, 5))
    h.view(True)[:] = 1

    assert h[sum] == 6  # 4 (internal bins) + 2 (flow bins)
    assert h[bh.tag.at(-1):bh.tag.
             at(5):sum] == 6  # keeps underflow, keeps overflow

    # check that slicing without bh.sum adds removed counts to flow bins
    assert_array_equal(h[1:3].view(True), [2, 1, 1, 2])

    assert h[0::sum] == 5  # removes underflow, keeps overflow
    assert h[:4:sum] == 5  # removes overflow, keeps underflow
    assert h[0:4:sum] == 4  # removes underflow and overflow

    assert h[bh.loc(1)::sum] == 5  # remove underflow
    assert h[:bh.loc(5):sum] == 5  # remove overflow
    assert h[bh.loc(1):bh.loc(5):sum] == 4  # removes underflow and overflow

    assert h[bh.loc(0)::sum] == 6  # keep underflow
    assert h[:bh.loc(10) + 1:sum] == 6  # keep overflow
    assert h[bh.loc(0):bh.loc(10) + 1:sum] == 6
Ejemplo n.º 30
0
def test_named_hist_proxy():
    """
    Test named hist proxy -- whether NamedHist hist proxy works properly.
    """

    h = NamedHist.new.Reg(10, 0, 1, name="x").Double().fill(x=[0.5, 0.5])
    assert h[0.5j] == 2

    assert type(h) is NamedHist

    with pytest.raises(AttributeError):
        NamedHist().new

    h = (
        NamedHist.new.Reg(10, 0, 1, name="x")
        .Reg(10, 0, 1, name="y")
        .Double()
        .fill(x=[0.5, 0.5], y=[0.2, 0.6])
    )

    assert h[0.5j, 0.2j] == 1
    assert h[bh.loc(0.5), bh.loc(0.6)] == 1

    h = NamedHist.new.Bool(name="x").Double().fill(x=[True, True])
    assert h[bh.loc(True)] == 2

    h = (
        NamedHist.new.Bool(name="x")
        .Bool(name="y")
        .Double()
        .fill(x=[True, True], y=[True, False])
    )

    assert h[True, True] == 1
    assert h[True, False] == 1

    h = NamedHist.new.Var(range(10), name="x").Double().fill(x=[5, 5])
    assert h[5j] == 2

    h = (
        NamedHist.new.Var(range(10), name="x")
        .Var(range(10), name="y")
        .Double()
        .fill(x=[5, 5], y=[2, 6])
    )

    assert h[5j, 2j] == 1
    assert h[bh.loc(5), bh.loc(6)] == 1

    h = NamedHist.new.Int(0, 10, name="x").Double().fill(x=[5, 5])
    assert h[5j] == 2

    h = (
        NamedHist.new.Int(0, 10, name="x")
        .Int(0, 10, name="y")
        .Double()
        .fill(x=[5, 5], y=[2, 6])
    )

    assert h[5j, 2j] == 1
    assert h[bh.loc(5), bh.loc(6)] == 1

    h = NamedHist.new.IntCat(range(10), name="x").Double().fill(x=[5, 5])
    assert h[5j] == 2

    h = (
        NamedHist.new.IntCat(range(10), name="x")
        .IntCat(range(10), name="y")
        .Double()
        .fill(x=[5, 5], y=[2, 6])
    )

    assert h[5j, 2j] == 1
    assert h[bh.loc(5), bh.loc(6)] == 1

    h = NamedHist.new.StrCat("TF", name="x").Double().fill(x=["T", "T"])
    assert h["T"] == 2

    h = (
        NamedHist.new.StrCat("TF", name="x")
        .StrCat("TF", name="y")
        .Double()
        .fill(x=["T", "T"], y=["T", "F"])
    )

    assert h["T", "T"] == 1
    assert h["T", "F"] == 1