diff --git a/benchmark/histogram_reduce.cpp b/benchmark/histogram_reduce.cpp index 12e8c97b..2e6ac652 100644 --- a/benchmark/histogram_reduce.cpp +++ b/benchmark/histogram_reduce.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -82,6 +83,47 @@ static void ShrinkAndRebin(benchmark::State& state, Tag, boost::mp11::mp_int +auto make_category_histogram(Tag, int n) { + std::vector cats; + for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); + using C = axis::category; + auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), + axis::regular<>(n, 0.0, 10.0 * n)); + for (auto&& v : unsafe_access::storage(h)) v = 1.0; + return h; +} + +// mirrors the boost-histogram python benchmark: h[loc(a), loc(b), loc(c), :] +template +static void Pick(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + const auto h = make_category_histogram(Tag{}, n); + std::vector opts; + for (int i = 0; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); + run_reduce(state, h, opts); +} + +template +static void PickCrop(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + const auto h = make_category_histogram(Tag{}, n); + std::vector opts; + for (int i = 0; i < 3; ++i) + opts.push_back(algorithm::pick(i, {13 % n}, algorithm::slice_mode::crop)); + run_reduce(state, h, opts); +} + +template +static void PickAndSlice(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + const auto h = make_category_histogram(Tag{}, n); + std::vector opts; + opts.push_back(algorithm::slice(0, 3, 29 % n)); + for (int i = 1; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); + run_reduce(state, h, opts); +} + #define BENCH(Type, Tag, Dim) \ BENCHMARK_CAPTURE(Type, (Tag, Dim), Tag{}, Dim_t{}) \ ->RangeMultiplier(4) \ @@ -110,3 +152,8 @@ BENCH(ShrinkAndRebin, unlimited, 2); BENCH(Rebin, unlimited, 3); BENCH(Shrink, unlimited, 3); BENCH(ShrinkAndRebin, unlimited, 3); + +BENCHMARK_CAPTURE(Pick, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(PickCrop, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(PickAndSlice, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(Pick, (unlimited), unlimited{})->Arg(32); diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index 9fc931cc..07a652e1 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -10,11 +10,12 @@ #include #include #include +#include #include +#include #include #include #include -#include #include #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include @@ -415,13 +417,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { [&o](const auto& a_in) { static_assert(!axis::traits::is_ordered::value, "pick requires an unordered axis"); - // lut maps old index to new index; unpicked bins and the - // overflow bin map to the overflow bin of the new axis o.reduced_end = static_cast(o.indices.size()); - o.lut.assign(static_cast(a_in.size()) + 1, - o.reduced_end); - for (index_type k = 0; k < o.reduced_end; ++k) - o.lut[o.indices[k]] = k; return std::decay_t( a_in, o.indices.data(), o.indices.data() + o.indices.size()); }, @@ -488,37 +484,92 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { auto result = Histogram(std::move(axes), detail::make_default(unsafe_access::storage(hist))); - auto idx = detail::make_stack_buffer(unsafe_access::axes(result)); - for (auto&& x : indexed(hist, coverage::all)) { - auto i = idx.begin(); - auto o = opts.begin(); - bool skip = false; - - for (auto j : x.indices()) { - if (o->range == reduce_command::range_t::indices_list) { - *i = o->lut[j]; + // maps each input cell to its output cell + detail::cell_map> map(old_axes); + { + std::size_t out_stride = 1; + unsigned iaxis = 0; + detail::for_each_axis(old_axes, [&](const auto& a_in) { + using A = std::decay_t; + using AO = axis::traits::get_options; + const index_type u = AO::test(axis::option::underflow); + const index_type ov = AO::test(axis::option::overflow); + const auto& o = opts[iaxis]; + const auto extent = static_cast(axis::traits::extent(a_in)); + std::size_t* l = map.add_axis(extent); + if (o.range == reduce_command::range_t::indices_list) { + // unpicked bins and flow bins go to the overflow bin of the new axis + std::fill(l, l + extent, + o.use_overflow_bin + ? static_cast(o.reduced_end + u) * out_stride + : detail::invalid_index); + for (index_type k = 0; k < o.reduced_end; ++k) + l[o.indices[k] + u] = static_cast(k + u) * out_stride; } else { - *i = (j - o->begin.index); - if (o->is_ordered && *i <= -1) { - *i = -1; - if (!o->use_underflow_bin) skip = true; - } else if (*i >= 0) - *i /= static_cast(o->merge); - else - *i = o->reduced_end; - } - if (*i >= o->reduced_end) { - *i = o->reduced_end; - if (!o->use_overflow_bin) skip = true; + for (index_type j = -u; j < a_in.size() + ov; ++j) { + index_type i = (j - o.begin.index); + bool skip = false; + if (o.is_ordered && i <= -1) { + i = -1; + if (!o.use_underflow_bin) skip = true; + } else if (i >= 0) + i /= static_cast(o.merge); + else + i = o.reduced_end; + if (i >= o.reduced_end) { + i = o.reduced_end; + if (!o.use_overflow_bin) skip = true; + } + *l++ = + skip ? detail::invalid_index : static_cast(i + u) * out_stride; + } } - - ++i; - ++o; - } - - if (!skip) result.at(idx) += *x; + out_stride *= static_cast(o.reduced_end + u + ov); + ++iaxis; + }); + assert(map.input_size() == hist.size()); + assert(out_stride == result.size()); } + const auto& in = unsafe_access::storage(hist); + auto& out = unsafe_access::storage(result); + // local accumulation needs a true reference to an arithmetic cell + using ref_t = decltype(out[std::size_t{}]); + detail::static_if_c::value && + std::is_arithmetic>::value>( + [&map, &in](auto& res) { + map.for_each_line([&](std::size_t in_off, std::size_t out_off, + const std::size_t* l, std::size_t n) { + // sum runs of input cells with the same output cell in a local accumulator; + // this breaks the store-to-load chain on the output cell + std::size_t p = 0; + while (p < n) { + const auto o = l[p]; + std::size_t q = p + 1; + while (q < n && l[q] == o) ++q; + if (o != detail::invalid_index) { + auto& dst = res[out_off + o]; + if (q == p + 1) { // faster for the common run of length 1 + dst += in[in_off + p]; + } else { + auto acc = dst; + for (; p < q; ++p) acc += in[in_off + p]; + dst = acc; + } + } + p = q; + } + }); + }, + [&map, &in](auto& res) { + map.for_each_line([&](std::size_t in_off, std::size_t out_off, + const std::size_t* l, std::size_t n) { + for (std::size_t p = 0; p < n; ++p) + if (l[p] != detail::invalid_index) res[out_off + l[p]] += in[in_off + p]; + }); + }, + out); + return result; } diff --git a/include/boost/histogram/detail/cell_map.hpp b/include/boost/histogram/detail/cell_map.hpp new file mode 100644 index 00000000..3c01a29c --- /dev/null +++ b/include/boost/histogram/detail/cell_map.hpp @@ -0,0 +1,86 @@ +// Copyright 2026 Henry Schreiner +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt +// or copy at http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_HISTOGRAM_DETAIL_CELL_MAP_HPP +#define BOOST_HISTOGRAM_DETAIL_CELL_MAP_HPP + +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace histogram { +namespace detail { + +// Maps each cell of an input storage to an offset in an output storage. Each axis has one +// lookup table with one entry per stored input bin, flow bins included. An entry is the +// output offset contributed by that bin. invalid_index skips the input cell and, for an +// outer axis, the whole block of cells below it. +template +class cell_map { + struct axis_row { + std::size_t begin; // first entry of this axis in lut_ + std::size_t extent; // number of stored input bins + std::size_t stride; // input stride + }; + +public: + explicit cell_map(const Axes& axes) : rows_(make_stack_buffer(axes)) {} + + // Adds the table for the next axis and returns it, to be filled with `extent` entries. + // The pointer is valid until the next call. + std::size_t* add_axis(std::size_t extent) { + assert(naxes_ < rows_.size()); + rows_[naxes_++] = {lut_.size(), extent, in_size_}; + in_size_ *= extent; + lut_.resize(lut_.size() + extent); + return lut_.data() + lut_.size() - extent; + } + + std::size_t input_size() const noexcept { return in_size_; } + + // Calls f(in_offset, out_offset, lut, extent) for each line of cells along the first + // axis which is not skipped. Cell p of that line goes to out_offset + lut[p]. + template + void for_each_line(F&& f) const { + assert(naxes_ == rows_.size()); + if (naxes_ == 0) { + // a histogram without axes has one cell + const std::size_t zero = 0; + f(std::size_t{0}, std::size_t{0}, &zero, std::size_t{1}); + } else { + visit(f, 0, 0, naxes_ - 1); + } + } + +private: + template + void visit(F& f, std::size_t in_off, std::size_t out_off, unsigned iaxis) const { + const auto& r = rows_[iaxis]; + const std::size_t* const l = lut_.data() + r.begin; + if (iaxis == 0) { + f(in_off, out_off, l, r.extent); + return; + } + for (std::size_t p = 0; p < r.extent; ++p) + if (l[p] != invalid_index) + visit(f, in_off + p * r.stride, out_off + l[p], iaxis - 1); + } + + decltype(make_stack_buffer(std::declval())) rows_; + std::vector lut_; + std::size_t in_size_ = 1; + unsigned naxes_ = 0; +}; + +} // namespace detail +} // namespace histogram +} // namespace boost + +#endif diff --git a/include/boost/histogram/detail/fill.hpp b/include/boost/histogram/detail/fill.hpp index 9b8038f9..8e30a845 100644 --- a/include/boost/histogram/detail/fill.hpp +++ b/include/boost/histogram/detail/fill.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -52,83 +53,51 @@ struct sample_args_passed_vs_expected, std::tuple struct storage_grower { const A& axes_; - struct { - axis::index_type idx, old_extent; - std::size_t new_stride; - } data_[buffer_size::value]; - std::size_t new_size_; + decltype(make_stack_buffer(std::declval())) old_extents_; - storage_grower(const A& axes) noexcept : axes_(axes) {} + storage_grower(const A& axes) noexcept + : axes_(axes), old_extents_(make_stack_buffer(axes)) {} void from_shifts(const axis::index_type* shifts) noexcept { - auto dit = data_; - std::size_t s = 1; + auto eit = old_extents_.begin(); for_each_axis(axes_, [&](const auto& a) { - const auto n = axis::traits::extent(a); - *dit++ = {0, n - std::abs(*shifts++), s}; - s *= n; + *eit++ = axis::traits::extent(a) - std::abs(*shifts++); }); - new_size_ = s; } // must be extents before any shifts were applied void from_extents(const axis::index_type* old_extents) noexcept { - auto dit = data_; - std::size_t s = 1; - for_each_axis(axes_, [&](const auto& a) { - const auto n = axis::traits::extent(a); - *dit++ = {0, *old_extents++, s}; - s *= n; - }); - new_size_ = s; + std::copy(old_extents, old_extents + old_extents_.size(), old_extents_.begin()); } template void apply(S& storage, const axis::index_type* shifts) { + cell_map map(axes_); + std::size_t out_stride = 1; + auto eit = old_extents_.begin(); + for_each_axis(axes_, [&](const auto& a) { + using opt = axis::traits::get_options>; + const auto n = axis::traits::extent(a); + const auto old_extent = *eit++; + // normal bins move by the positive shift, if any + const auto shift = (std::max)(*shifts++, 0); + std::size_t* l = map.add_axis(static_cast(old_extent)); + for (axis::index_type i = 0; i < old_extent; ++i) + l[i] = static_cast(i + shift) * out_stride; + if (opt::test(axis::option::overflow)) + l[old_extent - 1] = static_cast(n - 1) * out_stride; + if (opt::test(axis::option::underflow)) l[0] = 0; + out_stride *= static_cast(n); + }); + assert(map.input_size() == storage.size()); + auto new_storage = make_default(storage); - new_storage.reset(new_size_); - const auto dlast = data_ + axes_rank(axes_) - 1; - for (auto&& x : storage) { - auto ns = new_storage.begin(); - auto sit = shifts; - auto dit = data_; - for_each_axis(axes_, [&](const auto& a) { - using opt = axis::traits::get_options>; - if (opt::test(axis::option::underflow)) { - if (dit->idx == 0) { - // axis has underflow and we are in the underflow bin: - // keep storage pointer unchanged - ++dit; - ++sit; - return; - } - } - if (opt::test(axis::option::overflow)) { - if (dit->idx == dit->old_extent - 1) { - // axis has overflow and we are in the overflow bin: - // move storage pointer to corresponding overflow bin position - ns += (axis::traits::extent(a) - 1) * dit->new_stride; - ++dit; - ++sit; - return; - } - } - // we are in a normal bin: - // move storage pointer to index position; apply positive shifts if any - ns += (dit->idx + (*sit >= 0 ? *sit : 0)) * dit->new_stride; - ++dit; - ++sit; - }); - // assign old value to new location - *ns = x; - // advance multi-dimensional index - dit = data_; - ++dit->idx; - while (dit != dlast && dit->idx == dit->old_extent) { - dit->idx = 0; - ++(++dit)->idx; - } - } + new_storage.reset(out_stride); + map.for_each_line([&](std::size_t in_off, std::size_t out_off, const std::size_t* l, + std::size_t n) { + for (std::size_t p = 0; p < n; ++p) + new_storage[out_off + l[p]] = storage[in_off + p]; + }); storage = std::move(new_storage); } }; diff --git a/include/boost/histogram/detail/reduce_command.hpp b/include/boost/histogram/detail/reduce_command.hpp index cd60c46d..43c69bf3 100644 --- a/include/boost/histogram/detail/reduce_command.hpp +++ b/include/boost/histogram/detail/reduce_command.hpp @@ -36,8 +36,7 @@ struct reduce_command { unsigned merge = 0; // default value indicates unset option bool crop = false; // for internal use by the reduce algorithm - axis::index_type reduced_end = 0; // overflow index of the new axis - std::vector lut; // pick: maps old bin index to new bin index + axis::index_type reduced_end = 0; // overflow index of the new axis bool is_ordered = true; bool use_underflow_bin = true; bool use_overflow_bin = true; diff --git a/test/algorithm_reduce_test.cpp b/test/algorithm_reduce_test.cpp index 7caa4ac7..caafd97d 100644 --- a/test/algorithm_reduce_test.cpp +++ b/test/algorithm_reduce_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -518,11 +519,35 @@ void run_tests() { BOOST_TEST_EQ(hr.at(1, 1), 4); BOOST_TEST_EQ(hr.at(2, 1), 0); } + + // large axes; the lookup tables of reduce do not fit on the stack + { + auto h = make_s(Tag(), std::vector(), R(300, 0, 300), ID(0, 300)); + for (auto&& x : indexed(h, coverage::all)) *x = x.index(0) + 1; + auto hr = reduce(h, shrink_and_rebin(0, 10, 290, 10), slice(1, 100, 200)); + BOOST_TEST_EQ(hr.axis(0), R(28, 10, 290)); + BOOST_TEST_EQ(hr.axis(1), ID(100, 200)); + BOOST_TEST_EQ(sum(hr), sum(h)); + // bin k of axis 0 merges original bins 10k+10..10k+19 of weight (index + 1) + for (int k = 0; k < 28; ++k) BOOST_TEST_EQ(hr.at(k, 0), 10 * (10 * k + 11) + 45); + BOOST_TEST_EQ(hr.at(-1, 0), 10 * 1 + 45); // bins 0..9, original underflow is 0 + BOOST_TEST_EQ(hr.at(28, 0), 10 * 291 + 45 + 301); // bins 290..299 + original overflow + } } int main() { run_tests(); run_tests(); + // zero-dimensional histogram + { + auto h = make_histogram(std::vector>()); + BOOST_TEST_EQ(h.rank(), 0); + unsafe_access::storage(h)[0] = 3; + auto hr = reduce(h, std::vector()); + BOOST_TEST_EQ(hr.rank(), 0); + BOOST_TEST_EQ(unsafe_access::storage(hr)[0], 3); + } + return boost::report_errors(); }