histogram.hpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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/core/make_span.hpp>
  9. #include <boost/histogram/detail/accumulator_traits.hpp>
  10. #include <boost/histogram/detail/argument_traits.hpp>
  11. #include <boost/histogram/detail/axes.hpp>
  12. #include <boost/histogram/detail/common_type.hpp>
  13. #include <boost/histogram/detail/fill.hpp>
  14. #include <boost/histogram/detail/fill_n.hpp>
  15. #include <boost/histogram/detail/index_translator.hpp>
  16. #include <boost/histogram/detail/mutex_base.hpp>
  17. #include <boost/histogram/detail/nonmember_container_access.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. over a contiguous sequence of values or 3) a variant of 1) and 2). Sub-iterables must
  182. have the same length.
  183. Warning: `std::vector<bool>` is not a contiguous sequence over boolean values because
  184. of the infamous vector specialization for booleans. It cannot be used as an
  185. argument, but any truely contiguous sequence of boolean values can (`std::array<bool,
  186. N>` or `std::valarray<bool>`, for example).
  187. Values are passed to the corresponding histogram axis in order. If a single value is
  188. passed together with an iterable of values, the single value is treated like an
  189. iterable with matching length of copies of this value.
  190. If the histogram has only one axis, an iterable of values may be passed directly.
  191. @param args iterable as explained in the long description.
  192. */
  193. template <class Iterable, class = detail::requires_iterable<Iterable>>
  194. void fill(const Iterable& args) {
  195. using acc_traits = detail::accumulator_traits<value_type>;
  196. constexpr unsigned n_sample_args_expected =
  197. std::tuple_size<typename acc_traits::args>::value;
  198. static_assert(n_sample_args_expected == 0,
  199. "sample argument is missing but required by accumulator");
  200. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  201. detail::fill_n(mp11::mp_bool<(n_sample_args_expected == 0)>{}, offset_, storage_,
  202. axes_, make_span(args));
  203. }
  204. /** Fill histogram with several values and weights at once.
  205. @param args iterable of values.
  206. @param weights single weight or an iterable of weights.
  207. */
  208. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  209. void fill(const Iterable& args, const weight_type<T>& weights) {
  210. using acc_traits = detail::accumulator_traits<value_type>;
  211. constexpr bool weight_valid = acc_traits::weight_support;
  212. static_assert(weight_valid, "error: accumulator does not support weights");
  213. detail::sample_args_passed_vs_expected<std::tuple<>, typename acc_traits::args>();
  214. constexpr bool sample_valid =
  215. std::is_convertible<std::tuple<>, typename acc_traits::args>::value;
  216. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  217. detail::fill_n(mp11::mp_bool<(weight_valid && sample_valid)>{}, offset_, storage_,
  218. axes_, make_span(args), weight(detail::to_ptr_size(weights.value)));
  219. }
  220. /** Fill histogram with several values and weights at once.
  221. @param weights single weight or an iterable of weights.
  222. @param args iterable of values.
  223. */
  224. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  225. void fill(const weight_type<T>& weights, const Iterable& args) {
  226. fill(args, weights);
  227. }
  228. /** Fill histogram with several values and samples at once.
  229. @param args iterable of values.
  230. @param samples single sample or an iterable of samples.
  231. */
  232. template <class Iterable, class... Ts, class = detail::requires_iterable<Iterable>>
  233. void fill(const Iterable& args, const sample_type<std::tuple<Ts...>>& samples) {
  234. using acc_traits = detail::accumulator_traits<value_type>;
  235. using sample_args_passed =
  236. std::tuple<decltype(*detail::to_ptr_size(std::declval<Ts>()).first)...>;
  237. detail::sample_args_passed_vs_expected<sample_args_passed,
  238. typename acc_traits::args>();
  239. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  240. mp11::tuple_apply( // LCOV_EXCL_LINE: gcc-11 is missing this line for no reason
  241. [&](const auto&... sargs) {
  242. constexpr bool sample_valid =
  243. std::is_convertible<sample_args_passed, typename acc_traits::args>::value;
  244. detail::fill_n(mp11::mp_bool<(sample_valid)>{}, offset_, storage_, axes_,
  245. make_span(args), detail::to_ptr_size(sargs)...);
  246. },
  247. samples.value);
  248. }
  249. /** Fill histogram with several values and samples at once.
  250. @param samples single sample or an iterable of samples.
  251. @param args iterable of values.
  252. */
  253. template <class Iterable, class T, class = detail::requires_iterable<Iterable>>
  254. void fill(const sample_type<T>& samples, const Iterable& args) {
  255. fill(args, samples);
  256. }
  257. template <class Iterable, class T, class... Ts,
  258. class = detail::requires_iterable<Iterable>>
  259. void fill(const Iterable& args, const weight_type<T>& weights,
  260. const sample_type<std::tuple<Ts...>>& samples) {
  261. using acc_traits = detail::accumulator_traits<value_type>;
  262. using sample_args_passed =
  263. std::tuple<decltype(*detail::to_ptr_size(std::declval<Ts>()).first)...>;
  264. detail::sample_args_passed_vs_expected<sample_args_passed,
  265. typename acc_traits::args>();
  266. std::lock_guard<typename mutex_base::type> guard{mutex_base::get()};
  267. mp11::tuple_apply( // LCOV_EXCL_LINE: gcc-11 is missing this line for no reason
  268. [&](const auto&... sargs) {
  269. constexpr bool weight_valid = acc_traits::weight_support;
  270. static_assert(weight_valid, "error: accumulator does not support weights");
  271. constexpr bool sample_valid =
  272. std::is_convertible<sample_args_passed, typename acc_traits::args>::value;
  273. detail::fill_n(mp11::mp_bool<(weight_valid && sample_valid)>{}, offset_,
  274. storage_, axes_, make_span(args),
  275. weight(detail::to_ptr_size(weights.value)),
  276. detail::to_ptr_size(sargs)...);
  277. },
  278. samples.value);
  279. }
  280. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  281. void fill(const sample_type<T>& samples, const weight_type<U>& weights,
  282. const Iterable& args) {
  283. fill(args, weights, samples);
  284. }
  285. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  286. void fill(const weight_type<T>& weights, const sample_type<U>& samples,
  287. const Iterable& args) {
  288. fill(args, weights, samples);
  289. }
  290. template <class Iterable, class T, class U, class = detail::requires_iterable<Iterable>>
  291. void fill(const Iterable& args, const sample_type<T>& samples,
  292. const weight_type<U>& weights) {
  293. fill(args, weights, samples);
  294. }
  295. /** Access cell value at integral indices.
  296. You can pass indices as individual arguments, as a std::tuple of integers, or as an
  297. interable range of integers. Passing the wrong number of arguments causes a throw of
  298. std::invalid_argument. Passing an index which is out of bounds causes a throw of
  299. std::out_of_range.
  300. @param i index of first axis.
  301. @param is indices of second, third, ... axes.
  302. @returns reference to cell value.
  303. */
  304. template <class... Is>
  305. decltype(auto) at(axis::index_type i, Is... is) {
  306. return at(multi_index_type{i, static_cast<axis::index_type>(is)...});
  307. }
  308. /// Access cell value at integral indices (read-only).
  309. template <class... Is>
  310. decltype(auto) at(axis::index_type i, Is... is) const {
  311. return at(multi_index_type{i, static_cast<axis::index_type>(is)...});
  312. }
  313. /// Access cell value at integral indices stored in iterable.
  314. decltype(auto) at(const multi_index_type& is) {
  315. if (rank() != is.size())
  316. BOOST_THROW_EXCEPTION(
  317. std::invalid_argument("number of arguments != histogram rank"));
  318. const auto idx = detail::linearize_indices(axes_, is);
  319. if (!is_valid(idx))
  320. BOOST_THROW_EXCEPTION(std::out_of_range("at least one index out of bounds"));
  321. assert(idx < storage_.size());
  322. return storage_[idx];
  323. }
  324. /// Access cell value at integral indices stored in iterable (read-only).
  325. decltype(auto) at(const multi_index_type& is) const {
  326. if (rank() != is.size())
  327. BOOST_THROW_EXCEPTION(
  328. std::invalid_argument("number of arguments != histogram rank"));
  329. const auto idx = detail::linearize_indices(axes_, is);
  330. if (!is_valid(idx))
  331. BOOST_THROW_EXCEPTION(std::out_of_range("at least one index out of bounds"));
  332. assert(idx < storage_.size());
  333. return storage_[idx];
  334. }
  335. /// Access value at index (for rank = 1).
  336. decltype(auto) operator[](axis::index_type i) {
  337. const axis::index_type shift =
  338. axis::traits::options(axis()) & axis::option::underflow ? 1 : 0;
  339. return storage_[static_cast<std::size_t>(i + shift)];
  340. }
  341. /// Access value at index (for rank = 1, read-only).
  342. decltype(auto) operator[](axis::index_type i) const {
  343. const axis::index_type shift =
  344. axis::traits::options(axis()) & axis::option::underflow ? 1 : 0;
  345. return storage_[static_cast<std::size_t>(i + shift)];
  346. }
  347. /// Access value at index tuple.
  348. decltype(auto) operator[](const multi_index_type& is) {
  349. return storage_[detail::linearize_indices(axes_, is)];
  350. }
  351. /// Access value at index tuple (read-only).
  352. decltype(auto) operator[](const multi_index_type& is) const {
  353. return storage_[detail::linearize_indices(axes_, is)];
  354. }
  355. /// Equality operator, tests equality for all axes and the storage.
  356. template <class A, class S>
  357. bool operator==(const histogram<A, S>& rhs) const noexcept {
  358. // testing offset is redundant, but offers fast return if it fails
  359. return offset_ == unsafe_access::offset(rhs) &&
  360. detail::axes_equal(axes_, unsafe_access::axes(rhs)) &&
  361. storage_ == unsafe_access::storage(rhs);
  362. }
  363. /// Negation of the equality operator.
  364. template <class A, class S>
  365. bool operator!=(const histogram<A, S>& rhs) const noexcept {
  366. return !operator==(rhs);
  367. }
  368. /** Add values of another histogram.
  369. This operator is only available if the value_type supports operator+=.
  370. Both histograms must be compatible to be addable. The histograms are compatible, if
  371. the axes are either all identical. If the axes only differ in the states of their
  372. discrete growing axis types, then they are also compatible. The discrete growing
  373. axes are merged in this case.
  374. */
  375. template <class A, class S>
  376. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  377. histogram&
  378. #else
  379. std::enable_if_t<
  380. detail::has_operator_radd<value_type, typename histogram<A, S>::value_type>::value,
  381. histogram&>
  382. #endif
  383. operator+=(const histogram<A, S>& rhs) {
  384. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  385. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  386. auto rit = unsafe_access::storage(rhs).begin();
  387. for (auto&& x : storage_) x += *rit++;
  388. return *this;
  389. }
  390. // specialization that allows axes merging
  391. template <class S>
  392. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  393. histogram&
  394. #else
  395. std::enable_if_t<detail::has_operator_radd<
  396. value_type, typename histogram<axes_type, S>::value_type>::value,
  397. histogram&>
  398. #endif
  399. operator+=(const histogram<axes_type, S>& rhs) {
  400. const auto& raxes = unsafe_access::axes(rhs);
  401. if (detail::axes_equal(axes_, unsafe_access::axes(rhs))) {
  402. auto rit = unsafe_access::storage(rhs).begin();
  403. for (auto&& x : storage_) x += *rit++;
  404. return *this;
  405. }
  406. if (rank() != detail::axes_rank(raxes))
  407. BOOST_THROW_EXCEPTION(std::invalid_argument("axes have different length"));
  408. auto h = histogram<axes_type, storage_type>(
  409. detail::axes_transform(axes_, raxes, detail::axis_merger{}),
  410. detail::make_default(storage_));
  411. const auto& axes = unsafe_access::axes(h);
  412. const auto tr1 = detail::make_index_translator(axes, axes_);
  413. for (auto&& x : indexed(*this, coverage::all)) h[tr1(x.indices())] += *x;
  414. const auto tr2 = detail::make_index_translator(axes, raxes);
  415. for (auto&& x : indexed(rhs, coverage::all)) h[tr2(x.indices())] += *x;
  416. *this = std::move(h);
  417. return *this;
  418. }
  419. /** Subtract values of another histogram.
  420. This operator is only available if the value_type supports operator-=.
  421. */
  422. template <class A, class S>
  423. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  424. histogram&
  425. #else
  426. std::enable_if_t<
  427. detail::has_operator_rsub<value_type, typename histogram<A, S>::value_type>::value,
  428. histogram&>
  429. #endif
  430. operator-=(const histogram<A, S>& rhs) {
  431. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  432. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  433. auto rit = unsafe_access::storage(rhs).begin();
  434. for (auto&& x : storage_) x -= *rit++;
  435. return *this;
  436. }
  437. /** Multiply by values of another histogram.
  438. This operator is only available if the value_type supports operator*=.
  439. */
  440. template <class A, class S>
  441. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  442. histogram&
  443. #else
  444. std::enable_if_t<
  445. detail::has_operator_rmul<value_type, typename histogram<A, S>::value_type>::value,
  446. histogram&>
  447. #endif
  448. operator*=(const histogram<A, S>& rhs) {
  449. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  450. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  451. auto rit = unsafe_access::storage(rhs).begin();
  452. for (auto&& x : storage_) x *= *rit++;
  453. return *this;
  454. }
  455. /** Divide by values of another histogram.
  456. This operator is only available if the value_type supports operator/=.
  457. */
  458. template <class A, class S>
  459. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  460. histogram&
  461. #else
  462. std::enable_if_t<
  463. detail::has_operator_rdiv<value_type, typename histogram<A, S>::value_type>::value,
  464. histogram&>
  465. #endif
  466. operator/=(const histogram<A, S>& rhs) {
  467. if (!detail::axes_equal(axes_, unsafe_access::axes(rhs)))
  468. BOOST_THROW_EXCEPTION(std::invalid_argument("axes of histograms differ"));
  469. auto rit = unsafe_access::storage(rhs).begin();
  470. for (auto&& x : storage_) x /= *rit++;
  471. return *this;
  472. }
  473. /** Multiply all values with a scalar.
  474. This operator is only available if the value_type supports operator*=.
  475. */
  476. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  477. histogram&
  478. #else
  479. template <class V = value_type>
  480. std::enable_if_t<(detail::has_operator_rmul<V, double>::value), histogram&>
  481. #endif
  482. operator*=(const double x) {
  483. // use special storage implementation of scaling if available,
  484. // else fallback to scaling item by item
  485. detail::static_if<detail::has_operator_rmul<storage_type, double>>(
  486. [x](auto& s) { s *= x; },
  487. [x](auto& s) {
  488. for (auto&& si : s) si *= x;
  489. },
  490. storage_);
  491. return *this;
  492. }
  493. /** Divide all values by a scalar.
  494. This operator is only available if operator*= is available.
  495. */
  496. #ifdef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  497. histogram&
  498. #else
  499. template <class H = histogram>
  500. std::enable_if_t<(detail::has_operator_rmul<H, double>::value), histogram&>
  501. #endif
  502. operator/=(const double x) {
  503. return operator*=(1.0 / x);
  504. }
  505. /// Return value iterator to the beginning of the histogram.
  506. iterator begin() noexcept { return storage_.begin(); }
  507. /// Return value iterator to the end in the histogram.
  508. iterator end() noexcept { return storage_.end(); }
  509. /// Return value iterator to the beginning of the histogram (read-only).
  510. const_iterator begin() const noexcept { return storage_.begin(); }
  511. /// Return value iterator to the end in the histogram (read-only).
  512. const_iterator end() const noexcept { return storage_.end(); }
  513. /// Return value iterator to the beginning of the histogram (read-only).
  514. const_iterator cbegin() const noexcept { return begin(); }
  515. /// Return value iterator to the end in the histogram (read-only).
  516. const_iterator cend() const noexcept { return end(); }
  517. template <class Archive>
  518. void serialize(Archive& ar, unsigned /* version */) {
  519. detail::axes_serialize(ar, axes_);
  520. ar& make_nvp("storage", storage_);
  521. if (Archive::is_loading::value) {
  522. offset_ = detail::offset(axes_);
  523. detail::throw_if_axes_is_too_large(axes_);
  524. }
  525. }
  526. private:
  527. axes_type axes_;
  528. storage_type storage_;
  529. std::size_t offset_ = 0;
  530. friend struct unsafe_access;
  531. };
  532. /**
  533. Pairwise add cells of two histograms and return histogram with the sum.
  534. The returned histogram type is the most efficient and safest one constructible from the
  535. inputs, if they are not the same type. If one histogram has a tuple axis, the result has
  536. a tuple axis. The chosen storage is the one with the larger dynamic range.
  537. */
  538. template <class A1, class S1, class A2, class S2>
  539. auto operator+(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  540. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  541. return r += b;
  542. }
  543. /** Pairwise multiply cells of two histograms and return histogram with the product.
  544. For notes on the returned histogram type, see operator+.
  545. */
  546. template <class A1, class S1, class A2, class S2>
  547. auto operator*(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  548. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  549. return r *= b;
  550. }
  551. /** Pairwise subtract cells of two histograms and return histogram with the difference.
  552. For notes on the returned histogram type, see operator+.
  553. */
  554. template <class A1, class S1, class A2, class S2>
  555. auto operator-(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  556. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  557. return r -= b;
  558. }
  559. /** Pairwise divide cells of two histograms and return histogram with the quotient.
  560. For notes on the returned histogram type, see operator+.
  561. */
  562. template <class A1, class S1, class A2, class S2>
  563. auto operator/(const histogram<A1, S1>& a, const histogram<A2, S2>& b) {
  564. auto r = histogram<detail::common_axes<A1, A2>, detail::common_storage<S1, S2>>(a);
  565. return r /= b;
  566. }
  567. /** Multiply all cells of the histogram by a number and return a new histogram.
  568. If the original histogram has integer cells, the result has double cells.
  569. */
  570. template <class A, class S>
  571. auto operator*(const histogram<A, S>& h, double x) {
  572. auto r = histogram<A, detail::common_storage<S, dense_storage<double>>>(h);
  573. return r *= x;
  574. }
  575. /** Multiply all cells of the histogram by a number and return a new histogram.
  576. If the original histogram has integer cells, the result has double cells.
  577. */
  578. template <class A, class S>
  579. auto operator*(double x, const histogram<A, S>& h) {
  580. return h * x;
  581. }
  582. /** Divide all cells of the histogram by a number and return a new histogram.
  583. If the original histogram has integer cells, the result has double cells.
  584. */
  585. template <class A, class S>
  586. auto operator/(const histogram<A, S>& h, double x) {
  587. return h * (1.0 / x);
  588. }
  589. #if __cpp_deduction_guides >= 201606
  590. template <class... Axes, class = detail::requires_axes<std::tuple<std::decay_t<Axes>...>>>
  591. histogram(Axes...) -> histogram<std::tuple<std::decay_t<Axes>...>>;
  592. template <class... Axes, class S, class = detail::requires_storage_or_adaptible<S>>
  593. histogram(std::tuple<Axes...>, S)
  594. -> histogram<std::tuple<Axes...>, std::conditional_t<detail::is_adaptible<S>::value,
  595. storage_adaptor<S>, S>>;
  596. template <class Iterable, class = detail::requires_iterable<Iterable>,
  597. class = detail::requires_any_axis<typename Iterable::value_type>>
  598. histogram(Iterable) -> histogram<std::vector<typename Iterable::value_type>>;
  599. template <class Iterable, class S, class = detail::requires_iterable<Iterable>,
  600. class = detail::requires_any_axis<typename Iterable::value_type>,
  601. class = detail::requires_storage_or_adaptible<S>>
  602. histogram(Iterable, S) -> histogram<
  603. std::vector<typename Iterable::value_type>,
  604. std::conditional_t<detail::is_adaptible<S>::value, storage_adaptor<S>, S>>;
  605. #endif
  606. } // namespace histogram
  607. } // namespace boost
  608. #endif