guide_custom_accumulators_3.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //[ guide_custom_accumulators_3
  7. #include <boost/format.hpp>
  8. #include <boost/histogram.hpp>
  9. #include <iostream>
  10. #include <sstream>
  11. int main() {
  12. using namespace boost::histogram;
  13. // Accumulator accepts two samples and an optional weight and computes the mean of each.
  14. struct multi_mean {
  15. accumulators::mean<> mx, my;
  16. // called when no weight is passed
  17. void operator()(double x, double y) {
  18. mx(x);
  19. my(y);
  20. }
  21. // called when a weight is passed
  22. void operator()(weight_type<double> w, double x, double y) {
  23. mx(w, x);
  24. my(w, y);
  25. }
  26. };
  27. // Note: The implementation can be made more efficient by sharing the sum of weights.
  28. // Create a 1D histogram that uses the custom accumulator.
  29. auto h = make_histogram_with(dense_storage<multi_mean>(), axis::integer<>(0, 2));
  30. h(0, sample(1, 2)); // samples go to first cell
  31. h(0, sample(3, 4)); // samples go to first cell
  32. h(1, sample(5, 6), weight(2)); // samples go to second cell
  33. h(1, sample(7, 8), weight(3)); // samples go to second cell
  34. std::ostringstream os;
  35. for (auto&& bin : indexed(h)) {
  36. os << boost::format("index %i mean-x %.1f mean-y %.1f\n") % bin.index() %
  37. bin->mx.value() % bin->my.value();
  38. }
  39. std::cout << os.str() << std::flush;
  40. assert(os.str() == "index 0 mean-x 2.0 mean-y 3.0\n"
  41. "index 1 mean-x 6.2 mean-y 7.2\n");
  42. }
  43. //]