Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions benchmark/histogram_reduce.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include <benchmark/benchmark.h>
#include <boost/histogram/algorithm/reduce.hpp>
#include <boost/histogram/axis/category.hpp>
#include <boost/histogram/axis/regular.hpp>
#include <boost/histogram/make_histogram.hpp>
#include <boost/histogram/storage_adaptor.hpp>
Expand Down Expand Up @@ -82,6 +83,47 @@ static void ShrinkAndRebin(benchmark::State& state, Tag, boost::mp11::mp_int<Dim
run_reduce(state, h, opts);
}

template <class Tag>
auto make_category_histogram(Tag, int n) {
std::vector<std::string> cats;
for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i));
using C = axis::category<std::string>;
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 <class Tag>
static void Pick(benchmark::State& state, Tag) {
const int n = static_cast<int>(state.range(0));
const auto h = make_category_histogram(Tag{}, n);
std::vector<algorithm::reduce_command> opts;
for (int i = 0; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n}));
run_reduce(state, h, opts);
}

template <class Tag>
static void PickCrop(benchmark::State& state, Tag) {
const int n = static_cast<int>(state.range(0));
const auto h = make_category_histogram(Tag{}, n);
std::vector<algorithm::reduce_command> 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 <class Tag>
static void PickAndSlice(benchmark::State& state, Tag) {
const int n = static_cast<int>(state.range(0));
const auto h = make_category_histogram(Tag{}, n);
std::vector<algorithm::reduce_command> 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<Dim>{}) \
->RangeMultiplier(4) \
Expand Down Expand Up @@ -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);
119 changes: 85 additions & 34 deletions include/boost/histogram/algorithm/reduce.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,20 @@
#include <algorithm>
#include <boost/histogram/axis/traits.hpp>
#include <boost/histogram/detail/axes.hpp>
#include <boost/histogram/detail/cell_map.hpp>
#include <boost/histogram/detail/make_default.hpp>
#include <boost/histogram/detail/optional_index.hpp>
#include <boost/histogram/detail/reduce_command.hpp>
#include <boost/histogram/detail/static_if.hpp>
#include <boost/histogram/fwd.hpp>
#include <boost/histogram/indexed.hpp>
#include <boost/histogram/unsafe_access.hpp>
#include <boost/throw_exception.hpp>
#include <cassert>
#include <cmath>
#include <initializer_list>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

Expand Down Expand Up @@ -415,13 +417,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) {
[&o](const auto& a_in) {
static_assert(!axis::traits::is_ordered<A>::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<index_type>(o.indices.size());
o.lut.assign(static_cast<std::size_t>(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<decltype(a_in)>(
a_in, o.indices.data(), o.indices.data() + o.indices.size());
},
Expand Down Expand Up @@ -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<index_type>(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<std::decay_t<decltype(old_axes)>> 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<decltype(a_in)>;
using AO = axis::traits::get_options<A>;
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<std::size_t>(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<std::size_t>(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<std::size_t>(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<index_type>(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<index_type>(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<std::size_t>(i + u) * out_stride;
}
}

++i;
++o;
}

if (!skip) result.at(idx) += *x;
out_stride *= static_cast<std::size_t>(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<std::is_lvalue_reference<ref_t>::value &&
std::is_arithmetic<std::decay_t<ref_t>>::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;
}

Expand Down
86 changes: 86 additions & 0 deletions include/boost/histogram/detail/cell_map.hpp
Original file line number Diff line number Diff line change
@@ -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 <boost/histogram/detail/axes.hpp>
#include <boost/histogram/detail/optional_index.hpp>
#include <cassert>
#include <cstddef>
#include <utility>
#include <vector>

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 Axes>
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<axis_row>(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 <class F>
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 <class F>
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<axis_row>(std::declval<const Axes&>())) rows_;
std::vector<std::size_t> lut_;
std::size_t in_size_ = 1;
unsigned naxes_ = 0;
};

} // namespace detail
} // namespace histogram
} // namespace boost

#endif
Loading
Loading