histogram.hpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. #ifndef BOOST_HISTOGRAM_HISTOGRAM_HPP
  7. #define BOOST_HISTOGRAM_HISTOGRAM_HPP
  8. #include <boost/histogram/detail/accumulator_traits.hpp>
  9. #include <boost/histogram/detail/argument_traits.hpp>
  10. #include <boost/histogram/detail/axes.hpp>
  11. #include <boost/histogram/detail/common_type.hpp>
  12. #include <boost/histogram/detail/fill.hpp>
  13. #include <boost/histogram/detail/fill_n.hpp>
  14. #include <boost/histogram/detail/index_translator.hpp>
  15. #include <boost/histogram/detail/mutex_base.hpp>
  16. #include <boost/histogram/detail/nonmember_container_access.hpp>
  17. #include <boost/histogram/detail/span.hpp>
  18. #include <boost/histogram/detail/static_if.hpp>
  19. #include <boost/histogram/fwd.hpp>
  20. #include <boost/histogram/indexed.hpp>
  21. #include <boost/histogram/multi_index.hpp>
  22. #include <boost/histogram/sample.hpp>
  23. #include <boost/histogram/storage_adaptor.hpp>
  24. #include <boost/histogram/unsafe_access.hpp>
  25. #include <boost/histogram/weight.hpp>
  26. #include <boost/mp11/integral.hpp>
  27. #include <boost/mp11/list.hpp>
  28. #include <boost/mp11/tuple.hpp>
  29. #include <boost/throw_exception.hpp>
  30. #include <mutex>
  31. #include <stdexcept>
  32. #include <tuple>
  33. #include <type_traits>
  34. #include <utility>
  35. #include <vector>
  36. namespace boost {
  37. namespace histogram {
  38. /** Central class of the histogram library.
  39. Histogram uses the call operator to insert data, like the
  40. [Boost.Accumulators](https://www.boost.org/doc/libs/develop/doc/html/accumulators.html).
  41. Use factory functions (see
  42. [make_histogram.hpp](histogram/reference.html#header.boost.histogram.make_histogram_hpp)
  43. and
  44. [make_profile.hpp](histogram/reference.html#header.boost.histogram.make_profile_hpp)) to
  45. conveniently create histograms rather than calling the ctors directly.
  46. Use the [indexed](boost/histogram/indexed.html) range generator to iterate over filled
  47. histograms, which is convenient and faster than hand-written loops for multi-dimensional
  48. histograms.
  49. @tparam Axes std::tuple of axis types OR std::vector of an axis type or axis::variant
  50. @tparam Storage class that implements the storage interface
  51. */
  52. template <class Axes, class Storage>
  53. class histogram : detail::mutex_base<Axes, Storage> {
  54. static_assert(std::is_same<std::decay_t<Storage>, Storage>::value,
  55. "Storage may not be a reference or const or volatile");
  56. static_assert(mp11::mp_size<Axes>::value > 0, "at least one axis required");
  57. public:
  58. using axes_type = Axes;
  59. using storage_type = Storage;
  60. using value_type = typename storage_type::value_type;
  61. // typedefs for boost::range_iterator
  62. using iterator = typename storage_type::iterator;
  63. using const_iterator = typename storage_type::const_iterator;
  64. using multi_index_type = multi_index<detail::relaxed_tuple_size_t<axes_type>::value>;
  65. private:
  66. using mutex_base = typename detail::mutex_base<axes_type, storage_type>;
  67. public:
  68. histogram() = default;
  69. template <class A, class S>
  70. explicit histogram(histogram<A, S>&& rhs)
  71. : storage_(std::move(unsafe_access::storage(rhs)))
  72. , offset_(unsafe_access::offset(rhs)) {
  73. detail::axes_assign(axes_, std::move(unsafe_access::axes(rhs)));
  74. detail::throw_if_axes_is_too_large(axes_);
  75. }
  76. template <class A, class S>
  77. explicit histogram(const histogram<A, S>& rhs)
  78. : storage_(unsafe_access::storage(rhs)), offset_(unsafe_access::offset(rhs)) {
  79. detail::axes_assign(axes_, unsafe_access::axes(rhs));
  80. detail::throw_if_axes_is_too_large(axes_);
  81. }
  82. template <class A, class S>
  83. histogram& operator=(histogram<A, S>&& rhs) {
  84. detail::axes_assign(axes_, std::move(unsafe_access::axes(rhs)));
  85. detail::throw_if_axes_is_too_large(axes_);
  86. storage_ = std::move(unsafe_access::storage(rhs));
  87. offset_ = unsafe_access::offset(rhs);
  88. return *this;
  89. }
  90. template <class A, class S>
  91. histogram& operator=(const histogram<A, S>& rhs) {
  92. detail::axes_assign(axes_, unsafe_access::axes(rhs));
  93. detail::throw_if_axes_is_too_large(axes_);
  94. storage_ = unsafe_access::storage(rhs);
  95. offset_ = unsafe_access::offset(rhs);
  96. return *this;
  97. }
  98. template <class A, class = detail::requires_axes<A>>
  99. histogram(A&& a, Storage s)
  100. : axes_(std::forward<A>(a))
  101. , storage_(std::move(s))
  102. , offset_(detail::offset(axes_)) {
  103. detail::throw_if_axes_is_too_large(axes_);
  104. storage_.reset(detail::bincount(axes_));
  105. }
  106. explicit histogram(Axes axes) : histogram(axes, storage_type()) {}
  107. template <class... As, class = detail::requires_axes<std::tuple<std::decay_t<As>...>>>
  108. explicit histogram(As&&... as)
  109. : histogram(std::tuple<std::decay_t<As>...>(std::forward<As>(as)...),
  110. storage_type()) {}
  111. /// Number of axes (dimensions).
  112. constexpr unsigned rank() const noexcept { return detail::axes_rank(axes_); }
  113. /// Total number of bins (including underflow/overflow).
  114. std::size_t size() const noexcept { return storage_.size(); }
  115. /// Reset all bins to default initialized values.
  116. void reset() { storage_.reset(size()); }
  117. /// Get N-th axis using a compile-time number.
  118. /// This version is more efficient than the one accepting a run-time number.
  119. template <unsigned N = 0>
  120. decltype(auto) axis(std::integral_constant<unsigned, N> = {}) const {
  121. assert(N < rank());
  122. return detail::axis_get<N>(axes_);
  123. }
  124. /// Get N-th axis with run-time number.
  125. /// Prefer the version that accepts a compile-time number, if you can use it.
  126. decltype(auto) axis(unsigned i) const {
  127. assert(i < rank());
  128. return detail::axis_get(axes_, i);
  129. }
  130. /// Apply unary functor/function to each axis.
  131. template <class Unary>
  132. auto for_each_axis(Unary&& unary) const {
  133. return detail::for_each_axis(axes_, std::forward<Unary>(unary));
  134. }
  135. /** Fill histogram with values, an optional weight, and/or a sample.
  136. Returns iterator to located cell.
  137. Arguments are passed in order to the axis objects. Passing an argument type that is
  138. not convertible to the value type accepted by the axis or passing the wrong number
  139. of arguments causes a throw of `std::invalid_argument`.
  140. __Optional weight__
  141. An optional weight can be passed as the first or last argument
  142. with the [weight](boost/histogram/weight.html) helper function. Compilation fails if
  143. the storage elements do not support weights.
  144. __Samples__
  145. If the storage elements accept samples, pass them with the sample helper function
  146. in addition to the axis arguments, which can be the first or last argument. The
  147. [sample](boost/histogram/sample.html) helper function can pass one or more arguments
  148. to the storage element. If samples and weights are used together, they can be passed
  149. in any order at the beginning or end of the argument list.
  150. __Axis with multiple arguments__
  151. If the histogram contains an axis which accepts a `std::tuple` of arguments, the
  152. arguments for that axis need to be passed as a `std::tuple`, for example,
  153. `std::make_tuple(1.2, 2.3)`. If the histogram contains only this axis and no other,
  154. the arguments can be passed directly.
  155. */
  156. template <class T0, class... Ts,
  157. class = std::enable_if_t<(detail::is_tuple<T0>::value == false ||
  158. sizeof...(Ts) > 0)>>
  159. iterator operator()(const T0& arg0, const Ts&... args) {
  160. return operator()(std::forward_as_tuple(arg0, args...));
  161. }
  162. /// Fill histogram with values, an optional weight, and/or a sample from a `std::tuple`.
  163. template <class... Ts>
  164. iterator operator()(const std::tuple<Ts...>& args) {
  165. using arg_traits = detail::argument_traits<std::decay_t<Ts>...>;
  166. using acc_traits = detail::accumulator_traits<value_type>;
  167. constexpr bool weight_valid =
  168. arg_traits::wpos::value == -1 || acc_traits::weight_support;
  169. static_assert(weight_valid, "error: accumulator does not support weights");
  170. detail::sample_args_passed_vs_expected<typename arg_traits::sargs,
  171. typename acc_traits::args>();
  172. constexpr bool sample_valid =
  173. std::is_convertible<typename arg_traits::sargs, typename acc_traits::args>::value;
  174. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  175. return detail::fill(mp11::mp_bool<(weight_valid && sample_valid)>{}, arg_traits{},
  176. offset_, storage_, axes_, args);
  177. }
  178. /** Fill histogram with several values at once.
  179. The argument must be an iterable with a size that matches the
  180. rank of the histogram. The element of an iterable may be 1) a value or 2) an iterable
  181. with contiguous storage over values or 3) a variant of 1) and 2). Sub-iterables must
  182. have the same length.
  183. Values are passed to the corresponding histogram axis in order. If a single value is
  184. passed together with an iterable of values, the single value is treated like an
  185. iterable with matching length of copies of this value.
  186. If the histogram has only one axis, an iterable of values may be passed directly.
  187. @param args iterable as explained in the long description.
  188. */
  189. template <class Iterable, class = detail::requires_iterable<Iterable>>
  190. void fill(const Iterable& args) {
  191. using acc_traits = detail::accumulator_traits<value_type>;
  192. constexpr unsigned n_sample_args_expected =
  193. std::tuple_size<typename acc_traits::args>::value;
  194. static_assert(n_sample_args_expected == 0,
  195. "sample argument is missing but required by accumulator");
  196. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  197. detail::fill_n(mp11::mp_bool<(n_sample_args_expected == 0)>{}, offset_, storage_,
  198. axes_, detail::make_span(args));
  199. }
  200. /** Fill histogram with several values and weights at once.
  201. @param args iterable of values.
  202. @param weights single weight or an iterable of weights.
  203. */
  204. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  205. void fill(const Iterable& args, const weight_type<T>& weights) {
  206. using acc_traits = detail::accumulator_traits<value_type>;
  207. constexpr bool weight_valid = acc_traits::weight_support;
  208. static_assert(weight_valid, "error: accumulator does not support weights");
  209. detail::sample_args_passed_vs_expected<std::tuple<>, typename acc_traits::args>();
  210. constexpr bool sample_valid =
  211. std::is_convertible<std::tuple<>, typename acc_traits::args>::value;
  212. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  213. detail::fill_n(mp11::mp_bool<(weight_valid && sample_valid)>{}, offset_, storage_,
  214. axes_, detail::make_span(args),
  215. weight(detail::to_ptr_size(weights.value)));
  216. }
  217. /** Fill histogram with several values and weights at once.
  218. @param weights single weight or an iterable of weights.
  219. @param args iterable of values.
  220. */
  221. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  222. void fill(const weight_type<T>& weights, const Iterable& args) {
  223. fill(args, weights);
  224. }
  225. /** Fill histogram with several values and samples at once.
  226. @param args iterable of values.
  227. @param samples single sample or an iterable of samples.
  228. */
  229. template <class Iterable, class... Ts, class = detail::requires_iterable<Iterable>>
  230. void fill(const Iterable& args, const sample_type<std::tuple<Ts...>>& samples) {
  231. using acc_traits = detail::accumulator_traits<value_type>;
  232. using sample_args_passed =
  233. std::tuple<decltype(*detail::to_ptr_size(std::declval<Ts>()).first)...>;
  234. detail::sample_args_passed_vs_expected<sample_args_passed,
  235. typename acc_traits::args>();
  236. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  237. mp11::tuple_apply(
  238. [&](const auto&... sargs) {
  239. constexpr bool sample_valid =
  240. std::is_convertible<sample_args_passed, typename acc_traits::args>::value;
  241. detail::fill_n(mp11::mp_bool<(sample_valid)>{}, offset_, storage_, axes_,
  242. detail::make_span(args), detail::to_ptr_size(sargs)...);
  243. },
  244. samples.value);
  245. }
  246. /** Fill histogram with several values and samples at once.
  247. @param samples single sample or an iterable of samples.
  248. @param args iterable of values.
  249. */
  250. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  251. void fill(const sample_type<T>& samples, const Iterable& args) {
  252. fill(args, samples);
  253. }
  254. template <class Iterable, class T, class... Ts,
  255. class = detail::requires_iterable<Iterable>>
  256. void fill(const Iterable& args, const weight_type<T>& weights,
  257. const sample_type<std::tuple<Ts...>>& samples) {
  258. using acc_traits = detail::accumulator_traits<value_type>;
  259. using sample_args_passed =
  260. std::tuple<decltype(*detail::to_ptr_size(std::declval<Ts>()).first)...>;
  261. detail::sample_args_passed_vs_expected<sample_args_passed,
  262. typename acc_traits::args>();
  263. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  264. mp11::tuple_apply(
  265. [&](const auto&... sargs) {
  266. constexpr bool weight_valid = acc_traits::weight_support;
  267. static_assert(weight_valid, "error: accumulator does not support weights");
  268. constexpr bool sample_valid =
  269. std::is_convertible<sample_args_passed, typename acc_traits::args>::value;
  270. detail::fill_n(mp11::mp_bool<(weight_valid && sample_valid)>{}, offset_,
  271. storage_, axes_, detail::make_span(args),
  272. weight(detail::to_ptr_size(weights.value)),
  273. detail::to_ptr_size(sargs)...);
  274. },
  275. samples.value);
  276. }
  277. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  278. void fill(const sample_type<T>& samples, const weight_type<U>& weights,
  279. const Iterable& args) {
  280. fill(args, weights, samples);
  281. }
  282. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  283. void fill(const weight_type<T>& weights, const sample_type<U>& samples,
  284. const Iterable& args) {
  285. fill(args, weights, samples);
  286. }
  287. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  288. void fill(const Iterable& args, const sample_type<T>& samples,
  289. const weight_type<U>& weights) {
  290. fill(args, weights, samples);
  291. }
  292. /** Access cell value at integral indices.
  293. You can pass indices as individual arguments, as a std::tuple of integers, or as an
  294. interable range of integers. Passing the wrong number of arguments causes a throw of
  295. std::invalid_argument. Passing an index which is out of bounds causes a throw of
  296. std::out_of_range.
  297. @param i index of first axis.
  298. @param is indices of second, third, ... axes.
  299. @returns reference to cell value.
  300. */
  301. template <class... Is>
  302. decltype(auto) at(axis::index_type i, Is... is) {
  303. return at(multi_index_type{i, static_cast<axis::index_type>(is)...});
  304. }
  305. /// Access cell value at integral indices (read-only).
  306. template <class... Is>
  307. decltype(auto) at(axis::index_type i, Is... is) const {
  308. return at(multi_index_type{i, static_cast<axis::index_type>(is)...});
  309. }
  310. /// Access cell value at integral indices stored in iterable.
  311. decltype(auto) at(const multi_index_type& is) {
  312. if (rank() != is.size())
  313. BOOST_THROW_EXCEPTION(
  314. std::invalid_argument("number of arguments != histogram rank"));
  315. const auto idx = detail::linearize_indices(axes_, is);
  316. if (!is_valid(idx))
  317. BOOST_THROW_EXCEPTION(std::out_of_range("at least one index out of bounds"));
  318. assert(idx < storage_.size());
  319. return storage_[idx];
  320. }
  321. /// Access cell value at integral indices stored in iterable (read-only).
  322. decltype(auto) at(const multi_index_type& is) const {
  323. if (rank() != is.size())
  324. BOOST_THROW_EXCEPTION(
  325. std::invalid_argument("number of arguments != histogram rank"));
  326. const auto idx = detail::linearize_indices(axes_, is);
  327. if (!is_valid(idx))
  328. BOOST_THROW_EXCEPTION(std::out_of_range("at least one index out of bounds"));
  329. assert(idx < storage_.size());
  330. return storage_[idx];
  331. }
  332. /// Access value at index (for rank = 1).
  333. decltype(auto) operator[](axis::index_type i) {
  334. const axis::index_type shift =
  335. axis::traits::options(axis()) & axis::option::underflow ? 1 : 0;
  336. return storage_[static_cast<std::size_t>(i + shift)];
  337. }
  338. /// Access value at index (for rank = 1, read-only).
  339. decltype(auto) operator[](axis::index_type i) const {
  340. const axis::index_type shift =
  341. axis::traits::options(axis()) & axis::option::underflow ? 1 : 0;
  342. return storage_[static_cast<std::size_t>(i + shift)];
  343. }
  344. /// Access value at index tuple.
  345. decltype(auto) operator[](const multi_index_type& is) {
  346. return storage_[detail::linearize_indices(axes_, is)];
  347. }
  348. /// Access value at index tuple (read-only).
  349. decltype(auto) operator[](const multi_index_type& is) const {
  350. return storage_[detail::linearize_indices(axes_, is)];
  351. }
  352. /// Equality operator, tests equality for all axes and the storage.
  353. template <class A, class S>
  354. bool operator==(const histogram<A, S>& rhs) const noexcept {
  355. // testing offset is redundant, but offers fast return if it fails
  356. return offset_ == unsafe_access::offset(rhs) &&
  357. detail::axes_equal(axes_, unsafe_access::axes(rhs)) &&
  358. storage_ == unsafe_access::storage(rhs);
  359. }
  360. /// Negation of the equality operator.
  361. template <class A, class S>
  362. bool operator!=(const histogram<A, S>& rhs) const noexcept {
  363. return !operator==(rhs);
  364. }
  365. /** Add values of another histogram.
  366. This operator is only available if the value_type supports operator+=.
  367. Both histograms must be compatible to be addable. The histograms are compatible, if
  368. the axes are either all identical. If the axes only differ in the states of their
  369. discrete growing axis types, then they are also compatible. The discrete growing
  370. axes are merged in this case.
  371. */
  372. template <class A, class S>
  373. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  374. histogram&
  375. #else
  376. std::enable_if_t<
  377. detail::has_operator_radd<value_type, typename histogram<A, S>::value_type>::value,
  378. histogram&>
  379. #endif
  380. operator+=(const histogram<A, S>& rhs) {
  381. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  382. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  383. auto rit = unsafe_access::storage(rhs).begin();
  384. for (auto&& x : storage_) x += *rit++;
  385. return *this;
  386. }
  387. // specialization that allows axes merging
  388. template <class S>
  389. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  390. histogram&
  391. #else
  392. std::enable_if_t<detail::has_operator_radd<
  393. value_type, typename histogram<axes_type, S>::value_type>::value,
  394. histogram&>
  395. #endif
  396. operator+=(const histogram<axes_type, S>& rhs) {
  397. const auto& raxes = unsafe_access::axes(rhs);
  398. if (detail::axes_equal(axes_, unsafe_access::axes(rhs))) {
  399. auto rit = unsafe_access::storage(rhs).begin();
  400. for (auto&& x : storage_) x += *rit++;
  401. return *this;
  402. }
  403. if (rank() != detail::axes_rank(raxes))
  404. BOOST_THROW_EXCEPTION(std::invalid_argument("axes have different length"));
  405. auto h = histogram<axes_type, storage_type>(
  406. detail::axes_transform(axes_, raxes, detail::axis_merger{}),
  407. detail::make_default(storage_));
  408. const auto& axes = unsafe_access::axes(h);
  409. const auto tr1 = detail::make_index_translator(axes, axes_);
  410. for (auto&& x : indexed(*this, coverage::all)) h[tr1(x.indices())] += *x;
  411. const auto tr2 = detail::make_index_translator(axes, raxes);
  412. for (auto&& x : indexed(rhs, coverage::all)) h[tr2(x.indices())] += *x;
  413. *this = std::move(h);
  414. return *this;
  415. }
  416. /** Subtract values of another histogram.
  417. This operator is only available if the value_type supports operator-=.
  418. */
  419. template <class A, class S>
  420. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  421. histogram&
  422. #else
  423. std::enable_if_t<
  424. detail::has_operator_rsub<value_type, typename histogram<A, S>::value_type>::value,
  425. histogram&>
  426. #endif
  427. operator-=(const histogram<A, S>& rhs) {
  428. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  429. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  430. auto rit = unsafe_access::storage(rhs).begin();
  431. for (auto&& x : storage_) x -= *rit++;
  432. return *this;
  433. }
  434. /** Multiply by values of another histogram.
  435. This operator is only available if the value_type supports operator*=.
  436. */
  437. template <class A, class S>
  438. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  439. histogram&
  440. #else
  441. std::enable_if_t<
  442. detail::has_operator_rmul<value_type, typename histogram<A, S>::value_type>::value,
  443. histogram&>
  444. #endif
  445. operator*=(const histogram<A, S>& rhs) {
  446. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  447. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  448. auto rit = unsafe_access::storage(rhs).begin();
  449. for (auto&& x : storage_) x *= *rit++;
  450. return *this;
  451. }
  452. /** Divide by values of another histogram.
  453. This operator is only available if the value_type supports operator/=.
  454. */
  455. template <class A, class S>
  456. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  457. histogram&
  458. #else
  459. std::enable_if_t<
  460. detail::has_operator_rdiv<value_type, typename histogram<A, S>::value_type>::value,
  461. histogram&>
  462. #endif
  463. operator/=(const histogram<A, S>& rhs) {
  464. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  465. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  466. auto rit = unsafe_access::storage(rhs).begin();
  467. for (auto&& x : storage_) x /= *rit++;
  468. return *this;
  469. }
  470. /** Multiply all values with a scalar.
  471. This operator is only available if the value_type supports operator*=.
  472. */
  473. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  474. histogram&
  475. #else
  476. template <class V = value_type>
  477. std::enable_if_t<(detail::has_operator_rmul<V, double>::value), histogram&>
  478. #endif
  479. operator*=(const double x) {
  480. // use special storage implementation of scaling if available,
  481. // else fallback to scaling item by item
  482. detail::static_if<detail::has_operator_rmul<storage_type, double>>(
  483. [x](auto& s) { s *= x; },
  484. [x](auto& s) {
  485. for (auto&& si : s) si *= x;
  486. },
  487. storage_);
  488. return *this;
  489. }
  490. /** Divide all values by a scalar.
  491. This operator is only available if operator*= is available.
  492. */
  493. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  494. histogram&
  495. #else
  496. template <class H = histogram>
  497. std::enable_if_t<(detail::has_operator_rmul<H, double>::value), histogram&>
  498. #endif
  499. operator/=(const double x) {
  500. return operator*=(1.0 / x);
  501. }
  502. /// Return value iterator to the beginning of the histogram.
  503. iterator begin() noexcept { return storage_.begin(); }
  504. /// Return value iterator to the end in the histogram.
  505. iterator end() noexcept { return storage_.end(); }
  506. /// Return value iterator to the beginning of the histogram (read-only).
  507. const_iterator begin() const noexcept { return storage_.begin(); }
  508. /// Return value iterator to the end in the histogram (read-only).
  509. const_iterator end() const noexcept { return storage_.end(); }
  510. /// Return value iterator to the beginning of the histogram (read-only).
  511. const_iterator cbegin() const noexcept { return begin(); }
  512. /// Return value iterator to the end in the histogram (read-only).
  513. const_iterator cend() const noexcept { return end(); }
  514. template <class Archive>
  515. void serialize(Archive& ar, unsigned /* version */) {
  516. detail::axes_serialize(ar, axes_);
  517. ar& make_nvp("storage", storage_);
  518. if (Archive::is_loading::value) {
  519. offset_ = detail::offset(axes_);
  520. detail::throw_if_axes_is_too_large(axes_);
  521. }
  522. }
  523. private:
  524. axes_type axes_;
  525. storage_type storage_;
  526. std::size_t offset_ = 0;
  527. friend struct unsafe_access;
  528. };
  529. /**
  530. Pairwise add cells of two histograms and return histogram with the sum.
  531. The returned histogram type is the most efficient and safest one constructible from the
  532. inputs, if they are not the same type. If one histogram has a tuple axis, the result has
  533. a tuple axis. The chosen storage is the one with the larger dynamic range.
  534. */
  535. template <class A1, class S1, class A2, class S2>
  536. auto operator+(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  537. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  538. return r += b;
  539. }
  540. /** Pairwise multiply cells of two histograms and return histogram with the product.
  541. For notes on the returned histogram type, see operator+.
  542. */
  543. template <class A1, class S1, class A2, class S2>
  544. auto operator*(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  545. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  546. return r *= b;
  547. }
  548. /** Pairwise subtract cells of two histograms and return histogram with the difference.
  549. For notes on the returned histogram type, see operator+.
  550. */
  551. template <class A1, class S1, class A2, class S2>
  552. auto operator-(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  553. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  554. return r -= b;
  555. }
  556. /** Pairwise divide cells of two histograms and return histogram with the quotient.
  557. For notes on the returned histogram type, see operator+.
  558. */
  559. template <class A1, class S1, class A2, class S2>
  560. auto operator/(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  561. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  562. return r /= b;
  563. }
  564. /** Multiply all cells of the histogram by a number and return a new histogram.
  565. If the original histogram has integer cells, the result has double cells.
  566. */
  567. template <class A, class S>
  568. auto operator*(const histogram<A, S>& h, double x) {
  569. auto r = histogram<A, detail::common_storage<S, dense_storage<double>>>(h);
  570. return r *= x;
  571. }
  572. /** Multiply all cells of the histogram by a number and return a new histogram.
  573. If the original histogram has integer cells, the result has double cells.
  574. */
  575. template <class A, class S>
  576. auto operator*(double x, const histogram<A, S>& h) {
  577. return h * x;
  578. }
  579. /** Divide all cells of the histogram by a number and return a new histogram.
  580. If the original histogram has integer cells, the result has double cells.
  581. */
  582. template <class A, class S>
  583. auto operator/(const histogram<A, S>& h, double x) {
  584. return h * (1.0 / x);
  585. }
  586. #if __cpp_deduction_guides >= 201606
  587. template <class... Axes, class = detail::requires_axes<std::tuple<std::decay_t<Axes>...>>>
  588. histogram(Axes...) -> histogram<std::tuple<std::decay_t<Axes>...>>;
  589. template <class... Axes, class S, class = detail::requires_storage_or_adaptible<S>>
  590. histogram(std::tuple<Axes...>, S)
  591. -> histogram<std::tuple<Axes...>, std::conditional_t<detail::is_adaptible<S>::value,
  592. storage_adaptor<S>, S>>;
  593. template <class Iterable, class = detail::requires_iterable<Iterable>,
  594. class = detail::requires_any_axis<typename Iterable::value_type>>
  595. histogram(Iterable) -> histogram<std::vector<typename Iterable::value_type>>;
  596. template <class Iterable, class S, class = detail::requires_iterable<Iterable>,
  597. class = detail::requires_any_axis<typename Iterable::value_type>,
  598. class = detail::requires_storage_or_adaptible<S>>
  599. histogram(Iterable, S) -> histogram<
  600. std::vector<typename Iterable::value_type>,
  601. std::conditional_t<detail::is_adaptible<S>::value, storage_adaptor<S>, S>>;
  602. #endif
  603. } // namespace histogram
  604. } // namespace boost
  605. #endif