Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:38:09

0001 // Copyright 2018 Hans Dembinski
0002 //
0003 // Distributed under the Boost Software License, Version 1.0.
0004 // (See accompanying file LICENSE_1_0.txt
0005 // or copy at http://www.boost.org/LICENSE_1_0.txt)
0006 
0007 #ifndef BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
0008 #define BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
0009 
0010 #include <boost/histogram/accumulators/sum.hpp>
0011 #include <boost/histogram/fwd.hpp>
0012 #include <boost/histogram/indexed.hpp>
0013 #include <boost/mp11/utility.hpp>
0014 #include <type_traits>
0015 
0016 namespace boost {
0017 namespace histogram {
0018 namespace algorithm {
0019 
0020 /** Compute the sum over all histogram cells (underflow/overflow included by default).
0021 
0022   The implementation favors accuracy and protection against overflow over speed. If the
0023   value type of the histogram is an integral or floating point type,
0024   accumulators::sum<double> is used to compute the sum, else the original value type is
0025   used. Compilation fails, if the value type does not support operator+=. The return type
0026   is double if the value type of the histogram is integral or floating point, and the
0027   original value type otherwise.
0028 
0029   If you need a different trade-off, you can write your own loop or use `std::accumulate`:
0030   ```
0031   // iterate over all bins
0032   auto sum_all = std::accumulate(hist.begin(), hist.end(), 0.0);
0033 
0034   // skip underflow/overflow bins
0035   double sum = 0;
0036   for (auto&& x : indexed(hist))
0037     sum += *x; // dereference accessor
0038 
0039   // or:
0040   // auto ind = boost::histogram::indexed(hist);
0041   // auto sum = std::accumulate(ind.begin(), ind.end(), 0.0);
0042   ```
0043 
0044   @returns accumulator type or double
0045 
0046   @param hist Const reference to the histogram.
0047   @param cov  Iterate over all or only inner bins (optional, default: all).
0048 */
0049 template <class A, class S>
0050 auto sum(const histogram<A, S>& hist, const coverage cov = coverage::all) {
0051   using T = typename histogram<A, S>::value_type;
0052   // T is arithmetic, compute sum accurately with high dynamic range
0053   using sum_type = mp11::mp_if<std::is_arithmetic<T>, accumulators::sum<double>, T>;
0054   sum_type sum;
0055   if (cov == coverage::all)
0056     for (auto&& x : hist) sum += x;
0057   else
0058     // sum += x also works if sum_type::operator+=(const sum_type&) exists
0059     for (auto&& x : indexed(hist)) sum += *x;
0060   using R = mp11::mp_if<std::is_arithmetic<T>, double, T>;
0061   return static_cast<R>(sum);
0062 }
0063 
0064 } // namespace algorithm
0065 } // namespace histogram
0066 } // namespace boost
0067 
0068 #endif