File: guide_histogram_reduction.cpp

package info (click to toggle)
boost1.74 1.74.0%2Bds1-21
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 463,588 kB
  • sloc: cpp: 3,338,117; xml: 131,293; python: 33,088; ansic: 14,292; asm: 4,038; sh: 3,353; makefile: 1,193; perl: 1,036; yacc: 478; php: 212; ruby: 102; lisp: 24; sql: 13; csh: 6
file content (48 lines) | stat: -rw-r--r-- 1,706 bytes parent folder | download | duplicates (14)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2015-2018 Hans Dembinski
//
// 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)

//[ guide_histogram_reduction

#include <boost/histogram.hpp>
#include <cassert>

int main() {
  using namespace boost::histogram;
  // import reduce commands into local namespace to save typing
  using algorithm::rebin;
  using algorithm::shrink;
  using algorithm::slice;

  // make a 2d histogram
  auto h = make_histogram(axis::regular<>(4, 0.0, 4.0), axis::regular<>(4, -2.0, 2.0));

  h(0, -0.9);
  h(1, 0.9);
  h(2, 0.1);
  h(3, 0.1);

  // reduce takes positional commands which are applied to the axes in order
  // - shrink is applied to the first axis; the new axis range is 0.0 to 3.0
  // - rebin is applied to the second axis; pairs of adjacent bins are merged
  auto h2 = algorithm::reduce(h, shrink(0.0, 3.0), rebin(2));

  assert(h2.axis(0) == axis::regular<>(3, 0.0, 3.0));
  assert(h2.axis(1) == axis::regular<>(2, -2.0, 2.0));

  // reduce does not change the total count if the histogram has underflow/overflow bins
  assert(algorithm::sum(h) == 4 && algorithm::sum(h2) == 4);

  // One can also explicitly specify the index of the axis in the histogram on which the
  // command should act, by using this index as the the first parameter. The position of
  // the command in the argument list of reduce is then ignored. We use this to slice only
  // the second axis (axis has index 1 in the histogram) from bin index 2 to 4.
  auto h3 = algorithm::reduce(h, slice(1, 2, 4));

  assert(h3.axis(0) == h.axis(0)); // unchanged
  assert(h3.axis(1) == axis::regular<>(2, 0.0, 2.0));
}

//]