Files
histogram/doc/tutorial.qbk
2017-05-02 14:43:02 +02:00

101 lines
3.0 KiB
Plaintext

[section Tutorial]
Example 1: How to make a 1d-histogram in C++ and to fill it.
[c++]
```
#include <boost/histogram.hpp>
#include <iostream>
#include <cmath>
int main(int, char**) {
namespace bh = boost::histogram;
// create 1d-histogram with 10 equidistant bins from -1.0 to 2.0,
// with axis of histogram labeled as "x"
auto h = bh::make_static_histogram(bh::regular_axis(10, -1.0, 2.0, "x"));
// fill histogram with data
h.fill(-1.5); // put in underflow bin
h.fill(-1.0); // included in first bin, bin interval is semi-open
h.fill(-0.5);
h.fill(1.1);
h.fill(0.3);
h.fill(1.7);
h.fill(2.0); // put in overflow bin, bin interval is semi-open
h.fill(20.0); // put in overflow bin
h.fill(0.1, bh::weight(5.0)); // fill with a weighted entry, weight is 5
// iterate over bins, loop includes under- and overflow bin
for (const auto& bin : h.axis<0>()) {
std::cout << "bin " << bin.idx
<< " x in [" << bin.left << ", " << bin.right << "): "
<< h.value(bin.idx) << " +/- " << std::sqrt(h.variance(bin.idx))
<< std::endl;
}
/* program output:
bin -1 x in [-inf, -1): 1 +/- 1
bin 0 x in [-1, -0.7): 1 +/- 1
bin 1 x in [-0.7, -0.4): 1 +/- 1
bin 2 x in [-0.4, -0.1): 0 +/- 0
bin 3 x in [-0.1, 0.2): 5 +/- 5
bin 4 x in [0.2, 0.5): 1 +/- 1
bin 5 x in [0.5, 0.8): 0 +/- 0
bin 6 x in [0.8, 1.1): 0 +/- 0
bin 7 x in [1.1, 1.4): 1 +/- 1
bin 8 x in [1.4, 1.7): 0 +/- 0
bin 9 x in [1.7, 2): 1 +/- 1
bin 10 x in [2, inf): 2 +/- 1.41421
*/
}
```
Example 2: How to make, fill, and use a 2d-histogram in Python.
[python]
```
import histogram as bh
import numpy as np
# create 2d-histogram over polar coordinates, with
# 10 equidistant bins in radius from 0 to 5 and
# 4 equidistant bins in polar angle
h = bh.histogram(bh.regular_axis(10, 0.0, 5.0, "radius",
uoflow=False),
bh.circular_axis(4, 0.0, 2*np.pi, "phi"))
# generate some numpy arrays with data to fill into histogram,
# in this case normal distributed random numbers in x and y,
# converted into polar coordinates
x = np.random.randn(1000) # generate x
y = np.random.randn(1000) # generate y
rphi = np.empty((1000, 2))
rphi[:, 0] = (x ** 2 + y ** 2) ** 0.5 # compute radius
rphi[:, 1] = np.arctan2(y, x) # compute phi
# fill histogram with numpy array
h.fill(rphi)
# access histogram counts (no copy)
count_matrix = np.asarray(h)
print count_matrix
# program output:
#
# [[37 26 33 37]
# [60 69 76 62]
# [48 80 80 77]
# [38 49 45 49]
# [22 24 20 23]
# [ 7 9 9 8]
# [ 3 2 3 3]
# [ 0 0 0 0]
# [ 0 1 0 0]
# [ 0 0 0 0]]
```
[endsect]