guide_histogram_projection.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2015-2018 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_histogram_projection
  7. #include <boost/histogram.hpp>
  8. #include <cassert>
  9. #include <iostream>
  10. #include <sstream>
  11. int main() {
  12. using namespace boost::histogram;
  13. using namespace literals; // enables _c suffix
  14. // make a 2d histogram
  15. auto h = make_histogram(axis::regular<>(3, -1.0, 1.0), axis::integer<>(0, 2));
  16. h(-0.9, 0);
  17. h(0.9, 1);
  18. h(0.1, 0);
  19. auto hr0 = algorithm::project(h, 0_c); // keep only first axis
  20. auto hr1 = algorithm::project(h, 1_c); // keep only second axis
  21. // reduce does not remove counts; returned histograms are summed over
  22. // the removed axes, so h, hr0, and hr1 have same number of total counts;
  23. // we compute the sum of counts with the sum algorithm
  24. assert(algorithm::sum(h) == 3 && algorithm::sum(hr0) == 3 && algorithm::sum(hr1) == 3);
  25. std::ostringstream os1;
  26. for (auto&& x : indexed(h))
  27. os1 << "(" << x.index(0) << ", " << x.index(1) << "): " << *x << "\n";
  28. std::cout << os1.str() << std::flush;
  29. assert(os1.str() == "(0, 0): 1\n"
  30. "(1, 0): 1\n"
  31. "(2, 0): 0\n"
  32. "(0, 1): 0\n"
  33. "(1, 1): 0\n"
  34. "(2, 1): 1\n");
  35. std::ostringstream os2;
  36. for (auto&& x : indexed(hr0)) os2 << "(" << x.index(0) << ", -): " << *x << "\n";
  37. std::cout << os2.str() << std::flush;
  38. assert(os2.str() == "(0, -): 1\n"
  39. "(1, -): 1\n"
  40. "(2, -): 1\n");
  41. std::ostringstream os3;
  42. for (auto&& x : indexed(hr1)) os3 << "(- ," << x.index(0) << "): " << *x << "\n";
  43. std::cout << os3.str() << std::flush;
  44. assert(os3.str() == "(- ,0): 2\n"
  45. "(- ,1): 1\n");
  46. }
  47. //]